echarts.esm.js 2.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820
  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. if (m) {
  5413. mIdentity(m);
  5414. this.invTransform = null;
  5415. }
  5416. return;
  5417. }
  5418. m = m || create$1();
  5419. if (needLocalTransform) {
  5420. this.getLocalTransform(m);
  5421. }
  5422. else {
  5423. mIdentity(m);
  5424. }
  5425. if (parentTransform) {
  5426. if (needLocalTransform) {
  5427. mul$1(m, parentTransform, m);
  5428. }
  5429. else {
  5430. copy$1(m, parentTransform);
  5431. }
  5432. }
  5433. this.transform = m;
  5434. this._resolveGlobalScaleRatio(m);
  5435. };
  5436. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  5437. var globalScaleRatio = this.globalScaleRatio;
  5438. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  5439. this.getGlobalScale(scaleTmp);
  5440. var relX = scaleTmp[0] < 0 ? -1 : 1;
  5441. var relY = scaleTmp[1] < 0 ? -1 : 1;
  5442. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  5443. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  5444. m[0] *= sx;
  5445. m[1] *= sx;
  5446. m[2] *= sy;
  5447. m[3] *= sy;
  5448. }
  5449. this.invTransform = this.invTransform || create$1();
  5450. invert(this.invTransform, m);
  5451. };
  5452. Transformable.prototype.getComputedTransform = function () {
  5453. var transformNode = this;
  5454. var ancestors = [];
  5455. while (transformNode) {
  5456. ancestors.push(transformNode);
  5457. transformNode = transformNode.parent;
  5458. }
  5459. while (transformNode = ancestors.pop()) {
  5460. transformNode.updateTransform();
  5461. }
  5462. return this.transform;
  5463. };
  5464. Transformable.prototype.setLocalTransform = function (m) {
  5465. if (!m) {
  5466. return;
  5467. }
  5468. var sx = m[0] * m[0] + m[1] * m[1];
  5469. var sy = m[2] * m[2] + m[3] * m[3];
  5470. var rotation = Math.atan2(m[1], m[0]);
  5471. var shearX = Math.PI / 2 + rotation - Math.atan2(m[3], m[2]);
  5472. sy = Math.sqrt(sy) * Math.cos(shearX);
  5473. sx = Math.sqrt(sx);
  5474. this.skewX = shearX;
  5475. this.skewY = 0;
  5476. this.rotation = -rotation;
  5477. this.x = +m[4];
  5478. this.y = +m[5];
  5479. this.scaleX = sx;
  5480. this.scaleY = sy;
  5481. this.originX = 0;
  5482. this.originY = 0;
  5483. };
  5484. Transformable.prototype.decomposeTransform = function () {
  5485. if (!this.transform) {
  5486. return;
  5487. }
  5488. var parent = this.parent;
  5489. var m = this.transform;
  5490. if (parent && parent.transform) {
  5491. mul$1(tmpTransform, parent.invTransform, m);
  5492. m = tmpTransform;
  5493. }
  5494. var ox = this.originX;
  5495. var oy = this.originY;
  5496. if (ox || oy) {
  5497. originTransform[4] = ox;
  5498. originTransform[5] = oy;
  5499. mul$1(tmpTransform, m, originTransform);
  5500. tmpTransform[4] -= ox;
  5501. tmpTransform[5] -= oy;
  5502. m = tmpTransform;
  5503. }
  5504. this.setLocalTransform(m);
  5505. };
  5506. Transformable.prototype.getGlobalScale = function (out) {
  5507. var m = this.transform;
  5508. out = out || [];
  5509. if (!m) {
  5510. out[0] = 1;
  5511. out[1] = 1;
  5512. return out;
  5513. }
  5514. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  5515. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  5516. if (m[0] < 0) {
  5517. out[0] = -out[0];
  5518. }
  5519. if (m[3] < 0) {
  5520. out[1] = -out[1];
  5521. }
  5522. return out;
  5523. };
  5524. Transformable.prototype.transformCoordToLocal = function (x, y) {
  5525. var v2 = [x, y];
  5526. var invTransform = this.invTransform;
  5527. if (invTransform) {
  5528. applyTransform(v2, v2, invTransform);
  5529. }
  5530. return v2;
  5531. };
  5532. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  5533. var v2 = [x, y];
  5534. var transform = this.transform;
  5535. if (transform) {
  5536. applyTransform(v2, v2, transform);
  5537. }
  5538. return v2;
  5539. };
  5540. Transformable.prototype.getLineScale = function () {
  5541. var m = this.transform;
  5542. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  5543. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  5544. : 1;
  5545. };
  5546. Transformable.prototype.copyTransform = function (source) {
  5547. copyTransform(this, source);
  5548. };
  5549. Transformable.getLocalTransform = function (target, m) {
  5550. m = m || [];
  5551. var ox = target.originX || 0;
  5552. var oy = target.originY || 0;
  5553. var sx = target.scaleX;
  5554. var sy = target.scaleY;
  5555. var ax = target.anchorX;
  5556. var ay = target.anchorY;
  5557. var rotation = target.rotation || 0;
  5558. var x = target.x;
  5559. var y = target.y;
  5560. var skewX = target.skewX ? Math.tan(target.skewX) : 0;
  5561. var skewY = target.skewY ? Math.tan(-target.skewY) : 0;
  5562. if (ox || oy || ax || ay) {
  5563. var dx = ox + ax;
  5564. var dy = oy + ay;
  5565. m[4] = -dx * sx - skewX * dy * sy;
  5566. m[5] = -dy * sy - skewY * dx * sx;
  5567. }
  5568. else {
  5569. m[4] = m[5] = 0;
  5570. }
  5571. m[0] = sx;
  5572. m[3] = sy;
  5573. m[1] = skewY * sx;
  5574. m[2] = skewX * sy;
  5575. rotation && rotate(m, m, rotation);
  5576. m[4] += ox + x;
  5577. m[5] += oy + y;
  5578. return m;
  5579. };
  5580. Transformable.initDefaultProps = (function () {
  5581. var proto = Transformable.prototype;
  5582. proto.scaleX =
  5583. proto.scaleY =
  5584. proto.globalScaleRatio = 1;
  5585. proto.x =
  5586. proto.y =
  5587. proto.originX =
  5588. proto.originY =
  5589. proto.skewX =
  5590. proto.skewY =
  5591. proto.rotation =
  5592. proto.anchorX =
  5593. proto.anchorY = 0;
  5594. })();
  5595. return Transformable;
  5596. }());
  5597. var TRANSFORMABLE_PROPS = [
  5598. 'x', 'y', 'originX', 'originY', 'anchorX', 'anchorY', 'rotation', 'scaleX', 'scaleY', 'skewX', 'skewY'
  5599. ];
  5600. function copyTransform(target, source) {
  5601. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  5602. var propName = TRANSFORMABLE_PROPS[i];
  5603. target[propName] = source[propName];
  5604. }
  5605. }
  5606. var textWidthCache = {};
  5607. function getWidth(text, font) {
  5608. font = font || DEFAULT_FONT;
  5609. var cacheOfFont = textWidthCache[font];
  5610. if (!cacheOfFont) {
  5611. cacheOfFont = textWidthCache[font] = new LRU(500);
  5612. }
  5613. var width = cacheOfFont.get(text);
  5614. if (width == null) {
  5615. width = platformApi.measureText(text, font).width;
  5616. cacheOfFont.put(text, width);
  5617. }
  5618. return width;
  5619. }
  5620. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  5621. var width = getWidth(text, font);
  5622. var height = getLineHeight(font);
  5623. var x = adjustTextX(0, width, textAlign);
  5624. var y = adjustTextY$1(0, height, textBaseline);
  5625. var rect = new BoundingRect(x, y, width, height);
  5626. return rect;
  5627. }
  5628. function getBoundingRect(text, font, textAlign, textBaseline) {
  5629. var textLines = ((text || '') + '').split('\n');
  5630. var len = textLines.length;
  5631. if (len === 1) {
  5632. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  5633. }
  5634. else {
  5635. var uniondRect = new BoundingRect(0, 0, 0, 0);
  5636. for (var i = 0; i < textLines.length; i++) {
  5637. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  5638. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  5639. }
  5640. return uniondRect;
  5641. }
  5642. }
  5643. function adjustTextX(x, width, textAlign) {
  5644. if (textAlign === 'right') {
  5645. x -= width;
  5646. }
  5647. else if (textAlign === 'center') {
  5648. x -= width / 2;
  5649. }
  5650. return x;
  5651. }
  5652. function adjustTextY$1(y, height, verticalAlign) {
  5653. if (verticalAlign === 'middle') {
  5654. y -= height / 2;
  5655. }
  5656. else if (verticalAlign === 'bottom') {
  5657. y -= height;
  5658. }
  5659. return y;
  5660. }
  5661. function getLineHeight(font) {
  5662. return getWidth('国', font);
  5663. }
  5664. function parsePercent(value, maxValue) {
  5665. if (typeof value === 'string') {
  5666. if (value.lastIndexOf('%') >= 0) {
  5667. return parseFloat(value) / 100 * maxValue;
  5668. }
  5669. return parseFloat(value);
  5670. }
  5671. return value;
  5672. }
  5673. function calculateTextPosition(out, opts, rect) {
  5674. var textPosition = opts.position || 'inside';
  5675. var distance = opts.distance != null ? opts.distance : 5;
  5676. var height = rect.height;
  5677. var width = rect.width;
  5678. var halfHeight = height / 2;
  5679. var x = rect.x;
  5680. var y = rect.y;
  5681. var textAlign = 'left';
  5682. var textVerticalAlign = 'top';
  5683. if (textPosition instanceof Array) {
  5684. x += parsePercent(textPosition[0], rect.width);
  5685. y += parsePercent(textPosition[1], rect.height);
  5686. textAlign = null;
  5687. textVerticalAlign = null;
  5688. }
  5689. else {
  5690. switch (textPosition) {
  5691. case 'left':
  5692. x -= distance;
  5693. y += halfHeight;
  5694. textAlign = 'right';
  5695. textVerticalAlign = 'middle';
  5696. break;
  5697. case 'right':
  5698. x += distance + width;
  5699. y += halfHeight;
  5700. textVerticalAlign = 'middle';
  5701. break;
  5702. case 'top':
  5703. x += width / 2;
  5704. y -= distance;
  5705. textAlign = 'center';
  5706. textVerticalAlign = 'bottom';
  5707. break;
  5708. case 'bottom':
  5709. x += width / 2;
  5710. y += height + distance;
  5711. textAlign = 'center';
  5712. break;
  5713. case 'inside':
  5714. x += width / 2;
  5715. y += halfHeight;
  5716. textAlign = 'center';
  5717. textVerticalAlign = 'middle';
  5718. break;
  5719. case 'insideLeft':
  5720. x += distance;
  5721. y += halfHeight;
  5722. textVerticalAlign = 'middle';
  5723. break;
  5724. case 'insideRight':
  5725. x += width - distance;
  5726. y += halfHeight;
  5727. textAlign = 'right';
  5728. textVerticalAlign = 'middle';
  5729. break;
  5730. case 'insideTop':
  5731. x += width / 2;
  5732. y += distance;
  5733. textAlign = 'center';
  5734. break;
  5735. case 'insideBottom':
  5736. x += width / 2;
  5737. y += height - distance;
  5738. textAlign = 'center';
  5739. textVerticalAlign = 'bottom';
  5740. break;
  5741. case 'insideTopLeft':
  5742. x += distance;
  5743. y += distance;
  5744. break;
  5745. case 'insideTopRight':
  5746. x += width - distance;
  5747. y += distance;
  5748. textAlign = 'right';
  5749. break;
  5750. case 'insideBottomLeft':
  5751. x += distance;
  5752. y += height - distance;
  5753. textVerticalAlign = 'bottom';
  5754. break;
  5755. case 'insideBottomRight':
  5756. x += width - distance;
  5757. y += height - distance;
  5758. textAlign = 'right';
  5759. textVerticalAlign = 'bottom';
  5760. break;
  5761. }
  5762. }
  5763. out = out || {};
  5764. out.x = x;
  5765. out.y = y;
  5766. out.align = textAlign;
  5767. out.verticalAlign = textVerticalAlign;
  5768. return out;
  5769. }
  5770. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  5771. var PRIMARY_STATES_KEYS = TRANSFORMABLE_PROPS.concat(['ignore']);
  5772. var DEFAULT_ANIMATABLE_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  5773. obj[key] = true;
  5774. return obj;
  5775. }, { ignore: false });
  5776. var tmpTextPosCalcRes = {};
  5777. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  5778. var Element = (function () {
  5779. function Element(props) {
  5780. this.id = guid();
  5781. this.animators = [];
  5782. this.currentStates = [];
  5783. this.states = {};
  5784. this._init(props);
  5785. }
  5786. Element.prototype._init = function (props) {
  5787. this.attr(props);
  5788. };
  5789. Element.prototype.drift = function (dx, dy, e) {
  5790. switch (this.draggable) {
  5791. case 'horizontal':
  5792. dy = 0;
  5793. break;
  5794. case 'vertical':
  5795. dx = 0;
  5796. break;
  5797. }
  5798. var m = this.transform;
  5799. if (!m) {
  5800. m = this.transform = [1, 0, 0, 1, 0, 0];
  5801. }
  5802. m[4] += dx;
  5803. m[5] += dy;
  5804. this.decomposeTransform();
  5805. this.markRedraw();
  5806. };
  5807. Element.prototype.beforeUpdate = function () { };
  5808. Element.prototype.afterUpdate = function () { };
  5809. Element.prototype.update = function () {
  5810. this.updateTransform();
  5811. if (this.__dirty) {
  5812. this.updateInnerText();
  5813. }
  5814. };
  5815. Element.prototype.updateInnerText = function (forceUpdate) {
  5816. var textEl = this._textContent;
  5817. if (textEl && (!textEl.ignore || forceUpdate)) {
  5818. if (!this.textConfig) {
  5819. this.textConfig = {};
  5820. }
  5821. var textConfig = this.textConfig;
  5822. var isLocal = textConfig.local;
  5823. var innerTransformable = textEl.innerTransformable;
  5824. var textAlign = void 0;
  5825. var textVerticalAlign = void 0;
  5826. var textStyleChanged = false;
  5827. innerTransformable.parent = isLocal ? this : null;
  5828. var innerOrigin = false;
  5829. innerTransformable.copyTransform(textEl);
  5830. if (textConfig.position != null) {
  5831. var layoutRect = tmpBoundingRect;
  5832. if (textConfig.layoutRect) {
  5833. layoutRect.copy(textConfig.layoutRect);
  5834. }
  5835. else {
  5836. layoutRect.copy(this.getBoundingRect());
  5837. }
  5838. if (!isLocal) {
  5839. layoutRect.applyTransform(this.transform);
  5840. }
  5841. if (this.calculateTextPosition) {
  5842. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5843. }
  5844. else {
  5845. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  5846. }
  5847. innerTransformable.x = tmpTextPosCalcRes.x;
  5848. innerTransformable.y = tmpTextPosCalcRes.y;
  5849. textAlign = tmpTextPosCalcRes.align;
  5850. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  5851. var textOrigin = textConfig.origin;
  5852. if (textOrigin && textConfig.rotation != null) {
  5853. var relOriginX = void 0;
  5854. var relOriginY = void 0;
  5855. if (textOrigin === 'center') {
  5856. relOriginX = layoutRect.width * 0.5;
  5857. relOriginY = layoutRect.height * 0.5;
  5858. }
  5859. else {
  5860. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  5861. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  5862. }
  5863. innerOrigin = true;
  5864. innerTransformable.originX = -innerTransformable.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  5865. innerTransformable.originY = -innerTransformable.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  5866. }
  5867. }
  5868. if (textConfig.rotation != null) {
  5869. innerTransformable.rotation = textConfig.rotation;
  5870. }
  5871. var textOffset = textConfig.offset;
  5872. if (textOffset) {
  5873. innerTransformable.x += textOffset[0];
  5874. innerTransformable.y += textOffset[1];
  5875. if (!innerOrigin) {
  5876. innerTransformable.originX = -textOffset[0];
  5877. innerTransformable.originY = -textOffset[1];
  5878. }
  5879. }
  5880. var isInside = textConfig.inside == null
  5881. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  5882. : textConfig.inside;
  5883. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  5884. var textFill = void 0;
  5885. var textStroke = void 0;
  5886. var autoStroke = void 0;
  5887. if (isInside && this.canBeInsideText()) {
  5888. textFill = textConfig.insideFill;
  5889. textStroke = textConfig.insideStroke;
  5890. if (textFill == null || textFill === 'auto') {
  5891. textFill = this.getInsideTextFill();
  5892. }
  5893. if (textStroke == null || textStroke === 'auto') {
  5894. textStroke = this.getInsideTextStroke(textFill);
  5895. autoStroke = true;
  5896. }
  5897. }
  5898. else {
  5899. textFill = textConfig.outsideFill;
  5900. textStroke = textConfig.outsideStroke;
  5901. if (textFill == null || textFill === 'auto') {
  5902. textFill = this.getOutsideFill();
  5903. }
  5904. if (textStroke == null || textStroke === 'auto') {
  5905. textStroke = this.getOutsideStroke(textFill);
  5906. autoStroke = true;
  5907. }
  5908. }
  5909. textFill = textFill || '#000';
  5910. if (textFill !== innerTextDefaultStyle.fill
  5911. || textStroke !== innerTextDefaultStyle.stroke
  5912. || autoStroke !== innerTextDefaultStyle.autoStroke
  5913. || textAlign !== innerTextDefaultStyle.align
  5914. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  5915. textStyleChanged = true;
  5916. innerTextDefaultStyle.fill = textFill;
  5917. innerTextDefaultStyle.stroke = textStroke;
  5918. innerTextDefaultStyle.autoStroke = autoStroke;
  5919. innerTextDefaultStyle.align = textAlign;
  5920. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  5921. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  5922. }
  5923. textEl.__dirty |= REDRAW_BIT;
  5924. if (textStyleChanged) {
  5925. textEl.dirtyStyle(true);
  5926. }
  5927. }
  5928. };
  5929. Element.prototype.canBeInsideText = function () {
  5930. return true;
  5931. };
  5932. Element.prototype.getInsideTextFill = function () {
  5933. return '#fff';
  5934. };
  5935. Element.prototype.getInsideTextStroke = function (textFill) {
  5936. return '#000';
  5937. };
  5938. Element.prototype.getOutsideFill = function () {
  5939. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  5940. };
  5941. Element.prototype.getOutsideStroke = function (textFill) {
  5942. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  5943. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  5944. if (!colorArr) {
  5945. colorArr = [255, 255, 255, 1];
  5946. }
  5947. var alpha = colorArr[3];
  5948. var isDark = this.__zr.isDarkMode();
  5949. for (var i = 0; i < 3; i++) {
  5950. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  5951. }
  5952. colorArr[3] = 1;
  5953. return stringify(colorArr, 'rgba');
  5954. };
  5955. Element.prototype.traverse = function (cb, context) { };
  5956. Element.prototype.attrKV = function (key, value) {
  5957. if (key === 'textConfig') {
  5958. this.setTextConfig(value);
  5959. }
  5960. else if (key === 'textContent') {
  5961. this.setTextContent(value);
  5962. }
  5963. else if (key === 'clipPath') {
  5964. this.setClipPath(value);
  5965. }
  5966. else if (key === 'extra') {
  5967. this.extra = this.extra || {};
  5968. extend(this.extra, value);
  5969. }
  5970. else {
  5971. this[key] = value;
  5972. }
  5973. };
  5974. Element.prototype.hide = function () {
  5975. this.ignore = true;
  5976. this.markRedraw();
  5977. };
  5978. Element.prototype.show = function () {
  5979. this.ignore = false;
  5980. this.markRedraw();
  5981. };
  5982. Element.prototype.attr = function (keyOrObj, value) {
  5983. if (typeof keyOrObj === 'string') {
  5984. this.attrKV(keyOrObj, value);
  5985. }
  5986. else if (isObject(keyOrObj)) {
  5987. var obj = keyOrObj;
  5988. var keysArr = keys(obj);
  5989. for (var i = 0; i < keysArr.length; i++) {
  5990. var key = keysArr[i];
  5991. this.attrKV(key, keyOrObj[key]);
  5992. }
  5993. }
  5994. this.markRedraw();
  5995. return this;
  5996. };
  5997. Element.prototype.saveCurrentToNormalState = function (toState) {
  5998. this._innerSaveToNormal(toState);
  5999. var normalState = this._normalState;
  6000. for (var i = 0; i < this.animators.length; i++) {
  6001. var animator = this.animators[i];
  6002. var fromStateTransition = animator.__fromStateTransition;
  6003. if (animator.getLoop() || fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  6004. continue;
  6005. }
  6006. var targetName = animator.targetName;
  6007. var target = targetName
  6008. ? normalState[targetName] : normalState;
  6009. animator.saveTo(target);
  6010. }
  6011. };
  6012. Element.prototype._innerSaveToNormal = function (toState) {
  6013. var normalState = this._normalState;
  6014. if (!normalState) {
  6015. normalState = this._normalState = {};
  6016. }
  6017. if (toState.textConfig && !normalState.textConfig) {
  6018. normalState.textConfig = this.textConfig;
  6019. }
  6020. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  6021. };
  6022. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  6023. for (var i = 0; i < primaryKeys.length; i++) {
  6024. var key = primaryKeys[i];
  6025. if (toState[key] != null && !(key in normalState)) {
  6026. normalState[key] = this[key];
  6027. }
  6028. }
  6029. };
  6030. Element.prototype.hasState = function () {
  6031. return this.currentStates.length > 0;
  6032. };
  6033. Element.prototype.getState = function (name) {
  6034. return this.states[name];
  6035. };
  6036. Element.prototype.ensureState = function (name) {
  6037. var states = this.states;
  6038. if (!states[name]) {
  6039. states[name] = {};
  6040. }
  6041. return states[name];
  6042. };
  6043. Element.prototype.clearStates = function (noAnimation) {
  6044. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  6045. };
  6046. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation, forceUseHoverLayer) {
  6047. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  6048. var hasStates = this.hasState();
  6049. if (!hasStates && toNormalState) {
  6050. return;
  6051. }
  6052. var currentStates = this.currentStates;
  6053. var animationCfg = this.stateTransition;
  6054. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  6055. return;
  6056. }
  6057. var state;
  6058. if (this.stateProxy && !toNormalState) {
  6059. state = this.stateProxy(stateName);
  6060. }
  6061. if (!state) {
  6062. state = (this.states && this.states[stateName]);
  6063. }
  6064. if (!state && !toNormalState) {
  6065. logError("State " + stateName + " not exists.");
  6066. return;
  6067. }
  6068. if (!toNormalState) {
  6069. this.saveCurrentToNormalState(state);
  6070. }
  6071. var useHoverLayer = !!((state && state.hoverLayer) || forceUseHoverLayer);
  6072. if (useHoverLayer) {
  6073. this._toggleHoverLayerFlag(true);
  6074. }
  6075. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6076. var textContent = this._textContent;
  6077. var textGuide = this._textGuide;
  6078. if (textContent) {
  6079. textContent.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6080. }
  6081. if (textGuide) {
  6082. textGuide.useState(stateName, keepCurrentStates, noAnimation, useHoverLayer);
  6083. }
  6084. if (toNormalState) {
  6085. this.currentStates = [];
  6086. this._normalState = {};
  6087. }
  6088. else {
  6089. if (!keepCurrentStates) {
  6090. this.currentStates = [stateName];
  6091. }
  6092. else {
  6093. this.currentStates.push(stateName);
  6094. }
  6095. }
  6096. this._updateAnimationTargets();
  6097. this.markRedraw();
  6098. if (!useHoverLayer && this.__inHover) {
  6099. this._toggleHoverLayerFlag(false);
  6100. this.__dirty &= ~REDRAW_BIT;
  6101. }
  6102. return state;
  6103. };
  6104. Element.prototype.useStates = function (states, noAnimation, forceUseHoverLayer) {
  6105. if (!states.length) {
  6106. this.clearStates();
  6107. }
  6108. else {
  6109. var stateObjects = [];
  6110. var currentStates = this.currentStates;
  6111. var len = states.length;
  6112. var notChange = len === currentStates.length;
  6113. if (notChange) {
  6114. for (var i = 0; i < len; i++) {
  6115. if (states[i] !== currentStates[i]) {
  6116. notChange = false;
  6117. break;
  6118. }
  6119. }
  6120. }
  6121. if (notChange) {
  6122. return;
  6123. }
  6124. for (var i = 0; i < len; i++) {
  6125. var stateName = states[i];
  6126. var stateObj = void 0;
  6127. if (this.stateProxy) {
  6128. stateObj = this.stateProxy(stateName, states);
  6129. }
  6130. if (!stateObj) {
  6131. stateObj = this.states[stateName];
  6132. }
  6133. if (stateObj) {
  6134. stateObjects.push(stateObj);
  6135. }
  6136. }
  6137. var lastStateObj = stateObjects[len - 1];
  6138. var useHoverLayer = !!((lastStateObj && lastStateObj.hoverLayer) || forceUseHoverLayer);
  6139. if (useHoverLayer) {
  6140. this._toggleHoverLayerFlag(true);
  6141. }
  6142. var mergedState = this._mergeStates(stateObjects);
  6143. var animationCfg = this.stateTransition;
  6144. this.saveCurrentToNormalState(mergedState);
  6145. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  6146. var textContent = this._textContent;
  6147. var textGuide = this._textGuide;
  6148. if (textContent) {
  6149. textContent.useStates(states, noAnimation, useHoverLayer);
  6150. }
  6151. if (textGuide) {
  6152. textGuide.useStates(states, noAnimation, useHoverLayer);
  6153. }
  6154. this._updateAnimationTargets();
  6155. this.currentStates = states.slice();
  6156. this.markRedraw();
  6157. if (!useHoverLayer && this.__inHover) {
  6158. this._toggleHoverLayerFlag(false);
  6159. this.__dirty &= ~REDRAW_BIT;
  6160. }
  6161. }
  6162. };
  6163. Element.prototype._updateAnimationTargets = function () {
  6164. for (var i = 0; i < this.animators.length; i++) {
  6165. var animator = this.animators[i];
  6166. if (animator.targetName) {
  6167. animator.changeTarget(this[animator.targetName]);
  6168. }
  6169. }
  6170. };
  6171. Element.prototype.removeState = function (state) {
  6172. var idx = indexOf(this.currentStates, state);
  6173. if (idx >= 0) {
  6174. var currentStates = this.currentStates.slice();
  6175. currentStates.splice(idx, 1);
  6176. this.useStates(currentStates);
  6177. }
  6178. };
  6179. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  6180. var currentStates = this.currentStates.slice();
  6181. var idx = indexOf(currentStates, oldState);
  6182. var newStateExists = indexOf(currentStates, newState) >= 0;
  6183. if (idx >= 0) {
  6184. if (!newStateExists) {
  6185. currentStates[idx] = newState;
  6186. }
  6187. else {
  6188. currentStates.splice(idx, 1);
  6189. }
  6190. }
  6191. else if (forceAdd && !newStateExists) {
  6192. currentStates.push(newState);
  6193. }
  6194. this.useStates(currentStates);
  6195. };
  6196. Element.prototype.toggleState = function (state, enable) {
  6197. if (enable) {
  6198. this.useState(state, true);
  6199. }
  6200. else {
  6201. this.removeState(state);
  6202. }
  6203. };
  6204. Element.prototype._mergeStates = function (states) {
  6205. var mergedState = {};
  6206. var mergedTextConfig;
  6207. for (var i = 0; i < states.length; i++) {
  6208. var state = states[i];
  6209. extend(mergedState, state);
  6210. if (state.textConfig) {
  6211. mergedTextConfig = mergedTextConfig || {};
  6212. extend(mergedTextConfig, state.textConfig);
  6213. }
  6214. }
  6215. if (mergedTextConfig) {
  6216. mergedState.textConfig = mergedTextConfig;
  6217. }
  6218. return mergedState;
  6219. };
  6220. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  6221. var needsRestoreToNormal = !(state && keepCurrentStates);
  6222. if (state && state.textConfig) {
  6223. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  6224. extend(this.textConfig, state.textConfig);
  6225. }
  6226. else if (needsRestoreToNormal) {
  6227. if (normalState.textConfig) {
  6228. this.textConfig = normalState.textConfig;
  6229. }
  6230. }
  6231. var transitionTarget = {};
  6232. var hasTransition = false;
  6233. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  6234. var key = PRIMARY_STATES_KEYS[i];
  6235. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  6236. if (state && state[key] != null) {
  6237. if (propNeedsTransition) {
  6238. hasTransition = true;
  6239. transitionTarget[key] = state[key];
  6240. }
  6241. else {
  6242. this[key] = state[key];
  6243. }
  6244. }
  6245. else if (needsRestoreToNormal) {
  6246. if (normalState[key] != null) {
  6247. if (propNeedsTransition) {
  6248. hasTransition = true;
  6249. transitionTarget[key] = normalState[key];
  6250. }
  6251. else {
  6252. this[key] = normalState[key];
  6253. }
  6254. }
  6255. }
  6256. }
  6257. if (!transition) {
  6258. for (var i = 0; i < this.animators.length; i++) {
  6259. var animator = this.animators[i];
  6260. var targetName = animator.targetName;
  6261. if (!animator.getLoop()) {
  6262. animator.__changeFinalValue(targetName
  6263. ? (state || normalState)[targetName]
  6264. : (state || normalState));
  6265. }
  6266. }
  6267. }
  6268. if (hasTransition) {
  6269. this._transitionState(stateName, transitionTarget, animationCfg);
  6270. }
  6271. };
  6272. Element.prototype._attachComponent = function (componentEl) {
  6273. if (componentEl.__zr && !componentEl.__hostTarget) {
  6274. if ("development" !== 'production') {
  6275. throw new Error('Text element has been added to zrender.');
  6276. }
  6277. return;
  6278. }
  6279. if (componentEl === this) {
  6280. if ("development" !== 'production') {
  6281. throw new Error('Recursive component attachment.');
  6282. }
  6283. return;
  6284. }
  6285. var zr = this.__zr;
  6286. if (zr) {
  6287. componentEl.addSelfToZr(zr);
  6288. }
  6289. componentEl.__zr = zr;
  6290. componentEl.__hostTarget = this;
  6291. };
  6292. Element.prototype._detachComponent = function (componentEl) {
  6293. if (componentEl.__zr) {
  6294. componentEl.removeSelfFromZr(componentEl.__zr);
  6295. }
  6296. componentEl.__zr = null;
  6297. componentEl.__hostTarget = null;
  6298. };
  6299. Element.prototype.getClipPath = function () {
  6300. return this._clipPath;
  6301. };
  6302. Element.prototype.setClipPath = function (clipPath) {
  6303. if (this._clipPath && this._clipPath !== clipPath) {
  6304. this.removeClipPath();
  6305. }
  6306. this._attachComponent(clipPath);
  6307. this._clipPath = clipPath;
  6308. this.markRedraw();
  6309. };
  6310. Element.prototype.removeClipPath = function () {
  6311. var clipPath = this._clipPath;
  6312. if (clipPath) {
  6313. this._detachComponent(clipPath);
  6314. this._clipPath = null;
  6315. this.markRedraw();
  6316. }
  6317. };
  6318. Element.prototype.getTextContent = function () {
  6319. return this._textContent;
  6320. };
  6321. Element.prototype.setTextContent = function (textEl) {
  6322. var previousTextContent = this._textContent;
  6323. if (previousTextContent === textEl) {
  6324. return;
  6325. }
  6326. if (previousTextContent && previousTextContent !== textEl) {
  6327. this.removeTextContent();
  6328. }
  6329. if ("development" !== 'production') {
  6330. if (textEl.__zr && !textEl.__hostTarget) {
  6331. throw new Error('Text element has been added to zrender.');
  6332. }
  6333. }
  6334. textEl.innerTransformable = new Transformable();
  6335. this._attachComponent(textEl);
  6336. this._textContent = textEl;
  6337. this.markRedraw();
  6338. };
  6339. Element.prototype.setTextConfig = function (cfg) {
  6340. if (!this.textConfig) {
  6341. this.textConfig = {};
  6342. }
  6343. extend(this.textConfig, cfg);
  6344. this.markRedraw();
  6345. };
  6346. Element.prototype.removeTextConfig = function () {
  6347. this.textConfig = null;
  6348. this.markRedraw();
  6349. };
  6350. Element.prototype.removeTextContent = function () {
  6351. var textEl = this._textContent;
  6352. if (textEl) {
  6353. textEl.innerTransformable = null;
  6354. this._detachComponent(textEl);
  6355. this._textContent = null;
  6356. this._innerTextDefaultStyle = null;
  6357. this.markRedraw();
  6358. }
  6359. };
  6360. Element.prototype.getTextGuideLine = function () {
  6361. return this._textGuide;
  6362. };
  6363. Element.prototype.setTextGuideLine = function (guideLine) {
  6364. if (this._textGuide && this._textGuide !== guideLine) {
  6365. this.removeTextGuideLine();
  6366. }
  6367. this._attachComponent(guideLine);
  6368. this._textGuide = guideLine;
  6369. this.markRedraw();
  6370. };
  6371. Element.prototype.removeTextGuideLine = function () {
  6372. var textGuide = this._textGuide;
  6373. if (textGuide) {
  6374. this._detachComponent(textGuide);
  6375. this._textGuide = null;
  6376. this.markRedraw();
  6377. }
  6378. };
  6379. Element.prototype.markRedraw = function () {
  6380. this.__dirty |= REDRAW_BIT;
  6381. var zr = this.__zr;
  6382. if (zr) {
  6383. if (this.__inHover) {
  6384. zr.refreshHover();
  6385. }
  6386. else {
  6387. zr.refresh();
  6388. }
  6389. }
  6390. if (this.__hostTarget) {
  6391. this.__hostTarget.markRedraw();
  6392. }
  6393. };
  6394. Element.prototype.dirty = function () {
  6395. this.markRedraw();
  6396. };
  6397. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  6398. this.__inHover = inHover;
  6399. var textContent = this._textContent;
  6400. var textGuide = this._textGuide;
  6401. if (textContent) {
  6402. textContent.__inHover = inHover;
  6403. }
  6404. if (textGuide) {
  6405. textGuide.__inHover = inHover;
  6406. }
  6407. };
  6408. Element.prototype.addSelfToZr = function (zr) {
  6409. if (this.__zr === zr) {
  6410. return;
  6411. }
  6412. this.__zr = zr;
  6413. var animators = this.animators;
  6414. if (animators) {
  6415. for (var i = 0; i < animators.length; i++) {
  6416. zr.animation.addAnimator(animators[i]);
  6417. }
  6418. }
  6419. if (this._clipPath) {
  6420. this._clipPath.addSelfToZr(zr);
  6421. }
  6422. if (this._textContent) {
  6423. this._textContent.addSelfToZr(zr);
  6424. }
  6425. if (this._textGuide) {
  6426. this._textGuide.addSelfToZr(zr);
  6427. }
  6428. };
  6429. Element.prototype.removeSelfFromZr = function (zr) {
  6430. if (!this.__zr) {
  6431. return;
  6432. }
  6433. this.__zr = null;
  6434. var animators = this.animators;
  6435. if (animators) {
  6436. for (var i = 0; i < animators.length; i++) {
  6437. zr.animation.removeAnimator(animators[i]);
  6438. }
  6439. }
  6440. if (this._clipPath) {
  6441. this._clipPath.removeSelfFromZr(zr);
  6442. }
  6443. if (this._textContent) {
  6444. this._textContent.removeSelfFromZr(zr);
  6445. }
  6446. if (this._textGuide) {
  6447. this._textGuide.removeSelfFromZr(zr);
  6448. }
  6449. };
  6450. Element.prototype.animate = function (key, loop, allowDiscreteAnimation) {
  6451. var target = key ? this[key] : this;
  6452. if ("development" !== 'production') {
  6453. if (!target) {
  6454. logError('Property "'
  6455. + key
  6456. + '" is not existed in element '
  6457. + this.id);
  6458. return;
  6459. }
  6460. }
  6461. var animator = new Animator(target, loop, allowDiscreteAnimation);
  6462. key && (animator.targetName = key);
  6463. this.addAnimator(animator, key);
  6464. return animator;
  6465. };
  6466. Element.prototype.addAnimator = function (animator, key) {
  6467. var zr = this.__zr;
  6468. var el = this;
  6469. animator.during(function () {
  6470. el.updateDuringAnimation(key);
  6471. }).done(function () {
  6472. var animators = el.animators;
  6473. var idx = indexOf(animators, animator);
  6474. if (idx >= 0) {
  6475. animators.splice(idx, 1);
  6476. }
  6477. });
  6478. this.animators.push(animator);
  6479. if (zr) {
  6480. zr.animation.addAnimator(animator);
  6481. }
  6482. zr && zr.wakeUp();
  6483. };
  6484. Element.prototype.updateDuringAnimation = function (key) {
  6485. this.markRedraw();
  6486. };
  6487. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  6488. var animators = this.animators;
  6489. var len = animators.length;
  6490. var leftAnimators = [];
  6491. for (var i = 0; i < len; i++) {
  6492. var animator = animators[i];
  6493. if (!scope || scope === animator.scope) {
  6494. animator.stop(forwardToLast);
  6495. }
  6496. else {
  6497. leftAnimators.push(animator);
  6498. }
  6499. }
  6500. this.animators = leftAnimators;
  6501. return this;
  6502. };
  6503. Element.prototype.animateTo = function (target, cfg, animationProps) {
  6504. animateTo(this, target, cfg, animationProps);
  6505. };
  6506. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  6507. animateTo(this, target, cfg, animationProps, true);
  6508. };
  6509. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  6510. var animators = animateTo(this, target, cfg, animationProps);
  6511. for (var i = 0; i < animators.length; i++) {
  6512. animators[i].__fromStateTransition = stateName;
  6513. }
  6514. };
  6515. Element.prototype.getBoundingRect = function () {
  6516. return null;
  6517. };
  6518. Element.prototype.getPaintRect = function () {
  6519. return null;
  6520. };
  6521. Element.initDefaultProps = (function () {
  6522. var elProto = Element.prototype;
  6523. elProto.type = 'element';
  6524. elProto.name = '';
  6525. elProto.ignore =
  6526. elProto.silent =
  6527. elProto.isGroup =
  6528. elProto.draggable =
  6529. elProto.dragging =
  6530. elProto.ignoreClip =
  6531. elProto.__inHover = false;
  6532. elProto.__dirty = REDRAW_BIT;
  6533. var logs = {};
  6534. function logDeprecatedError(key, xKey, yKey) {
  6535. if (!logs[key + xKey + yKey]) {
  6536. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  6537. logs[key + xKey + yKey] = true;
  6538. }
  6539. }
  6540. function createLegacyProperty(key, privateKey, xKey, yKey) {
  6541. Object.defineProperty(elProto, key, {
  6542. get: function () {
  6543. if ("development" !== 'production') {
  6544. logDeprecatedError(key, xKey, yKey);
  6545. }
  6546. if (!this[privateKey]) {
  6547. var pos = this[privateKey] = [];
  6548. enhanceArray(this, pos);
  6549. }
  6550. return this[privateKey];
  6551. },
  6552. set: function (pos) {
  6553. if ("development" !== 'production') {
  6554. logDeprecatedError(key, xKey, yKey);
  6555. }
  6556. this[xKey] = pos[0];
  6557. this[yKey] = pos[1];
  6558. this[privateKey] = pos;
  6559. enhanceArray(this, pos);
  6560. }
  6561. });
  6562. function enhanceArray(self, pos) {
  6563. Object.defineProperty(pos, 0, {
  6564. get: function () {
  6565. return self[xKey];
  6566. },
  6567. set: function (val) {
  6568. self[xKey] = val;
  6569. }
  6570. });
  6571. Object.defineProperty(pos, 1, {
  6572. get: function () {
  6573. return self[yKey];
  6574. },
  6575. set: function (val) {
  6576. self[yKey] = val;
  6577. }
  6578. });
  6579. }
  6580. }
  6581. if (Object.defineProperty) {
  6582. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  6583. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  6584. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  6585. }
  6586. })();
  6587. return Element;
  6588. }());
  6589. mixin(Element, Eventful);
  6590. mixin(Element, Transformable);
  6591. function animateTo(animatable, target, cfg, animationProps, reverse) {
  6592. cfg = cfg || {};
  6593. var animators = [];
  6594. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  6595. var finishCount = animators.length;
  6596. var doneHappened = false;
  6597. var cfgDone = cfg.done;
  6598. var cfgAborted = cfg.aborted;
  6599. var doneCb = function () {
  6600. doneHappened = true;
  6601. finishCount--;
  6602. if (finishCount <= 0) {
  6603. doneHappened
  6604. ? (cfgDone && cfgDone())
  6605. : (cfgAborted && cfgAborted());
  6606. }
  6607. };
  6608. var abortedCb = function () {
  6609. finishCount--;
  6610. if (finishCount <= 0) {
  6611. doneHappened
  6612. ? (cfgDone && cfgDone())
  6613. : (cfgAborted && cfgAborted());
  6614. }
  6615. };
  6616. if (!finishCount) {
  6617. cfgDone && cfgDone();
  6618. }
  6619. if (animators.length > 0 && cfg.during) {
  6620. animators[0].during(function (target, percent) {
  6621. cfg.during(percent);
  6622. });
  6623. }
  6624. for (var i = 0; i < animators.length; i++) {
  6625. var animator = animators[i];
  6626. if (doneCb) {
  6627. animator.done(doneCb);
  6628. }
  6629. if (abortedCb) {
  6630. animator.aborted(abortedCb);
  6631. }
  6632. if (cfg.force) {
  6633. animator.duration(cfg.duration);
  6634. }
  6635. animator.start(cfg.easing);
  6636. }
  6637. return animators;
  6638. }
  6639. function copyArrShallow(source, target, len) {
  6640. for (var i = 0; i < len; i++) {
  6641. source[i] = target[i];
  6642. }
  6643. }
  6644. function is2DArray(value) {
  6645. return isArrayLike(value[0]);
  6646. }
  6647. function copyValue(target, source, key) {
  6648. if (isArrayLike(source[key])) {
  6649. if (!isArrayLike(target[key])) {
  6650. target[key] = [];
  6651. }
  6652. if (isTypedArray(source[key])) {
  6653. var len = source[key].length;
  6654. if (target[key].length !== len) {
  6655. target[key] = new (source[key].constructor)(len);
  6656. copyArrShallow(target[key], source[key], len);
  6657. }
  6658. }
  6659. else {
  6660. var sourceArr = source[key];
  6661. var targetArr = target[key];
  6662. var len0 = sourceArr.length;
  6663. if (is2DArray(sourceArr)) {
  6664. var len1 = sourceArr[0].length;
  6665. for (var i = 0; i < len0; i++) {
  6666. if (!targetArr[i]) {
  6667. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  6668. }
  6669. else {
  6670. copyArrShallow(targetArr[i], sourceArr[i], len1);
  6671. }
  6672. }
  6673. }
  6674. else {
  6675. copyArrShallow(targetArr, sourceArr, len0);
  6676. }
  6677. targetArr.length = sourceArr.length;
  6678. }
  6679. }
  6680. else {
  6681. target[key] = source[key];
  6682. }
  6683. }
  6684. function isValueSame(val1, val2) {
  6685. return val1 === val2
  6686. || isArrayLike(val1) && isArrayLike(val2) && is1DArraySame(val1, val2);
  6687. }
  6688. function is1DArraySame(arr0, arr1) {
  6689. var len = arr0.length;
  6690. if (len !== arr1.length) {
  6691. return false;
  6692. }
  6693. for (var i = 0; i < len; i++) {
  6694. if (arr0[i] !== arr1[i]) {
  6695. return false;
  6696. }
  6697. }
  6698. return true;
  6699. }
  6700. function animateToShallow(animatable, topKey, animateObj, target, cfg, animationProps, animators, reverse) {
  6701. var targetKeys = keys(target);
  6702. var duration = cfg.duration;
  6703. var delay = cfg.delay;
  6704. var additive = cfg.additive;
  6705. var setToFinal = cfg.setToFinal;
  6706. var animateAll = !isObject(animationProps);
  6707. var existsAnimators = animatable.animators;
  6708. var animationKeys = [];
  6709. for (var k = 0; k < targetKeys.length; k++) {
  6710. var innerKey = targetKeys[k];
  6711. var targetVal = target[innerKey];
  6712. if (targetVal != null && animateObj[innerKey] != null
  6713. && (animateAll || animationProps[innerKey])) {
  6714. if (isObject(targetVal)
  6715. && !isArrayLike(targetVal)
  6716. && !isGradientObject(targetVal)) {
  6717. if (topKey) {
  6718. if (!reverse) {
  6719. animateObj[innerKey] = targetVal;
  6720. animatable.updateDuringAnimation(topKey);
  6721. }
  6722. continue;
  6723. }
  6724. animateToShallow(animatable, innerKey, animateObj[innerKey], targetVal, cfg, animationProps && animationProps[innerKey], animators, reverse);
  6725. }
  6726. else {
  6727. animationKeys.push(innerKey);
  6728. }
  6729. }
  6730. else if (!reverse) {
  6731. animateObj[innerKey] = targetVal;
  6732. animatable.updateDuringAnimation(topKey);
  6733. animationKeys.push(innerKey);
  6734. }
  6735. }
  6736. var keyLen = animationKeys.length;
  6737. if (!additive && keyLen) {
  6738. for (var i = 0; i < existsAnimators.length; i++) {
  6739. var animator = existsAnimators[i];
  6740. if (animator.targetName === topKey) {
  6741. var allAborted = animator.stopTracks(animationKeys);
  6742. if (allAborted) {
  6743. var idx = indexOf(existsAnimators, animator);
  6744. existsAnimators.splice(idx, 1);
  6745. }
  6746. }
  6747. }
  6748. }
  6749. if (!cfg.force) {
  6750. animationKeys = filter(animationKeys, function (key) { return !isValueSame(target[key], animateObj[key]); });
  6751. keyLen = animationKeys.length;
  6752. }
  6753. if (keyLen > 0
  6754. || (cfg.force && !animators.length)) {
  6755. var revertedSource = void 0;
  6756. var reversedTarget = void 0;
  6757. var sourceClone = void 0;
  6758. if (reverse) {
  6759. reversedTarget = {};
  6760. if (setToFinal) {
  6761. revertedSource = {};
  6762. }
  6763. for (var i = 0; i < keyLen; i++) {
  6764. var innerKey = animationKeys[i];
  6765. reversedTarget[innerKey] = animateObj[innerKey];
  6766. if (setToFinal) {
  6767. revertedSource[innerKey] = target[innerKey];
  6768. }
  6769. else {
  6770. animateObj[innerKey] = target[innerKey];
  6771. }
  6772. }
  6773. }
  6774. else if (setToFinal) {
  6775. sourceClone = {};
  6776. for (var i = 0; i < keyLen; i++) {
  6777. var innerKey = animationKeys[i];
  6778. sourceClone[innerKey] = cloneValue(animateObj[innerKey]);
  6779. copyValue(animateObj, target, innerKey);
  6780. }
  6781. }
  6782. var animator = new Animator(animateObj, false, false, additive ? filter(existsAnimators, function (animator) { return animator.targetName === topKey; }) : null);
  6783. animator.targetName = topKey;
  6784. if (cfg.scope) {
  6785. animator.scope = cfg.scope;
  6786. }
  6787. if (setToFinal && revertedSource) {
  6788. animator.whenWithKeys(0, revertedSource, animationKeys);
  6789. }
  6790. if (sourceClone) {
  6791. animator.whenWithKeys(0, sourceClone, animationKeys);
  6792. }
  6793. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animationKeys).delay(delay || 0);
  6794. animatable.addAnimator(animator, topKey);
  6795. animators.push(animator);
  6796. }
  6797. }
  6798. var Group = (function (_super) {
  6799. __extends(Group, _super);
  6800. function Group(opts) {
  6801. var _this = _super.call(this) || this;
  6802. _this.isGroup = true;
  6803. _this._children = [];
  6804. _this.attr(opts);
  6805. return _this;
  6806. }
  6807. Group.prototype.childrenRef = function () {
  6808. return this._children;
  6809. };
  6810. Group.prototype.children = function () {
  6811. return this._children.slice();
  6812. };
  6813. Group.prototype.childAt = function (idx) {
  6814. return this._children[idx];
  6815. };
  6816. Group.prototype.childOfName = function (name) {
  6817. var children = this._children;
  6818. for (var i = 0; i < children.length; i++) {
  6819. if (children[i].name === name) {
  6820. return children[i];
  6821. }
  6822. }
  6823. };
  6824. Group.prototype.childCount = function () {
  6825. return this._children.length;
  6826. };
  6827. Group.prototype.add = function (child) {
  6828. if (child) {
  6829. if (child !== this && child.parent !== this) {
  6830. this._children.push(child);
  6831. this._doAdd(child);
  6832. }
  6833. if ("development" !== 'production') {
  6834. if (child.__hostTarget) {
  6835. throw 'This elemenet has been used as an attachment';
  6836. }
  6837. }
  6838. }
  6839. return this;
  6840. };
  6841. Group.prototype.addBefore = function (child, nextSibling) {
  6842. if (child && child !== this && child.parent !== this
  6843. && nextSibling && nextSibling.parent === this) {
  6844. var children = this._children;
  6845. var idx = children.indexOf(nextSibling);
  6846. if (idx >= 0) {
  6847. children.splice(idx, 0, child);
  6848. this._doAdd(child);
  6849. }
  6850. }
  6851. return this;
  6852. };
  6853. Group.prototype.replace = function (oldChild, newChild) {
  6854. var idx = indexOf(this._children, oldChild);
  6855. if (idx >= 0) {
  6856. this.replaceAt(newChild, idx);
  6857. }
  6858. return this;
  6859. };
  6860. Group.prototype.replaceAt = function (child, index) {
  6861. var children = this._children;
  6862. var old = children[index];
  6863. if (child && child !== this && child.parent !== this && child !== old) {
  6864. children[index] = child;
  6865. old.parent = null;
  6866. var zr = this.__zr;
  6867. if (zr) {
  6868. old.removeSelfFromZr(zr);
  6869. }
  6870. this._doAdd(child);
  6871. }
  6872. return this;
  6873. };
  6874. Group.prototype._doAdd = function (child) {
  6875. if (child.parent) {
  6876. child.parent.remove(child);
  6877. }
  6878. child.parent = this;
  6879. var zr = this.__zr;
  6880. if (zr && zr !== child.__zr) {
  6881. child.addSelfToZr(zr);
  6882. }
  6883. zr && zr.refresh();
  6884. };
  6885. Group.prototype.remove = function (child) {
  6886. var zr = this.__zr;
  6887. var children = this._children;
  6888. var idx = indexOf(children, child);
  6889. if (idx < 0) {
  6890. return this;
  6891. }
  6892. children.splice(idx, 1);
  6893. child.parent = null;
  6894. if (zr) {
  6895. child.removeSelfFromZr(zr);
  6896. }
  6897. zr && zr.refresh();
  6898. return this;
  6899. };
  6900. Group.prototype.removeAll = function () {
  6901. var children = this._children;
  6902. var zr = this.__zr;
  6903. for (var i = 0; i < children.length; i++) {
  6904. var child = children[i];
  6905. if (zr) {
  6906. child.removeSelfFromZr(zr);
  6907. }
  6908. child.parent = null;
  6909. }
  6910. children.length = 0;
  6911. return this;
  6912. };
  6913. Group.prototype.eachChild = function (cb, context) {
  6914. var children = this._children;
  6915. for (var i = 0; i < children.length; i++) {
  6916. var child = children[i];
  6917. cb.call(context, child, i);
  6918. }
  6919. return this;
  6920. };
  6921. Group.prototype.traverse = function (cb, context) {
  6922. for (var i = 0; i < this._children.length; i++) {
  6923. var child = this._children[i];
  6924. var stopped = cb.call(context, child);
  6925. if (child.isGroup && !stopped) {
  6926. child.traverse(cb, context);
  6927. }
  6928. }
  6929. return this;
  6930. };
  6931. Group.prototype.addSelfToZr = function (zr) {
  6932. _super.prototype.addSelfToZr.call(this, zr);
  6933. for (var i = 0; i < this._children.length; i++) {
  6934. var child = this._children[i];
  6935. child.addSelfToZr(zr);
  6936. }
  6937. };
  6938. Group.prototype.removeSelfFromZr = function (zr) {
  6939. _super.prototype.removeSelfFromZr.call(this, zr);
  6940. for (var i = 0; i < this._children.length; i++) {
  6941. var child = this._children[i];
  6942. child.removeSelfFromZr(zr);
  6943. }
  6944. };
  6945. Group.prototype.getBoundingRect = function (includeChildren) {
  6946. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6947. var children = includeChildren || this._children;
  6948. var tmpMat = [];
  6949. var rect = null;
  6950. for (var i = 0; i < children.length; i++) {
  6951. var child = children[i];
  6952. if (child.ignore || child.invisible) {
  6953. continue;
  6954. }
  6955. var childRect = child.getBoundingRect();
  6956. var transform = child.getLocalTransform(tmpMat);
  6957. if (transform) {
  6958. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6959. rect = rect || tmpRect.clone();
  6960. rect.union(tmpRect);
  6961. }
  6962. else {
  6963. rect = rect || childRect.clone();
  6964. rect.union(childRect);
  6965. }
  6966. }
  6967. return rect || tmpRect;
  6968. };
  6969. return Group;
  6970. }(Element));
  6971. Group.prototype.type = 'group';
  6972. /*!
  6973. * ZRender, a high performance 2d drawing library.
  6974. *
  6975. * Copyright (c) 2013, Baidu Inc.
  6976. * All rights reserved.
  6977. *
  6978. * LICENSE
  6979. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6980. */
  6981. var painterCtors = {};
  6982. var instances = {};
  6983. function delInstance(id) {
  6984. delete instances[id];
  6985. }
  6986. function isDarkMode(backgroundColor) {
  6987. if (!backgroundColor) {
  6988. return false;
  6989. }
  6990. if (typeof backgroundColor === 'string') {
  6991. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6992. }
  6993. else if (backgroundColor.colorStops) {
  6994. var colorStops = backgroundColor.colorStops;
  6995. var totalLum = 0;
  6996. var len = colorStops.length;
  6997. for (var i = 0; i < len; i++) {
  6998. totalLum += lum(colorStops[i].color, 1);
  6999. }
  7000. totalLum /= len;
  7001. return totalLum < DARK_MODE_THRESHOLD;
  7002. }
  7003. return false;
  7004. }
  7005. var ZRender = (function () {
  7006. function ZRender(id, dom, opts) {
  7007. var _this = this;
  7008. this._sleepAfterStill = 10;
  7009. this._stillFrameAccum = 0;
  7010. this._needsRefresh = true;
  7011. this._needsRefreshHover = true;
  7012. this._darkMode = false;
  7013. opts = opts || {};
  7014. this.dom = dom;
  7015. this.id = id;
  7016. var storage = new Storage();
  7017. var rendererType = opts.renderer || 'canvas';
  7018. if (!painterCtors[rendererType]) {
  7019. rendererType = keys(painterCtors)[0];
  7020. }
  7021. if ("development" !== 'production') {
  7022. if (!painterCtors[rendererType]) {
  7023. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  7024. }
  7025. }
  7026. opts.useDirtyRect = opts.useDirtyRect == null
  7027. ? false
  7028. : opts.useDirtyRect;
  7029. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  7030. var ssrMode = opts.ssr || painter.ssrOnly;
  7031. this.storage = storage;
  7032. this.painter = painter;
  7033. var handerProxy = (!env.node && !env.worker && !ssrMode)
  7034. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  7035. : null;
  7036. var useCoarsePointer = opts.useCoarsePointer;
  7037. var usePointerSize = (useCoarsePointer == null || useCoarsePointer === 'auto')
  7038. ? env.touchEventsSupported
  7039. : !!useCoarsePointer;
  7040. var defaultPointerSize = 44;
  7041. var pointerSize;
  7042. if (usePointerSize) {
  7043. pointerSize = retrieve2(opts.pointerSize, defaultPointerSize);
  7044. }
  7045. this.handler = new Handler(storage, painter, handerProxy, painter.root, pointerSize);
  7046. this.animation = new Animation({
  7047. stage: {
  7048. update: ssrMode ? null : function () { return _this._flush(true); }
  7049. }
  7050. });
  7051. if (!ssrMode) {
  7052. this.animation.start();
  7053. }
  7054. }
  7055. ZRender.prototype.add = function (el) {
  7056. if (!el) {
  7057. return;
  7058. }
  7059. this.storage.addRoot(el);
  7060. el.addSelfToZr(this);
  7061. this.refresh();
  7062. };
  7063. ZRender.prototype.remove = function (el) {
  7064. if (!el) {
  7065. return;
  7066. }
  7067. this.storage.delRoot(el);
  7068. el.removeSelfFromZr(this);
  7069. this.refresh();
  7070. };
  7071. ZRender.prototype.configLayer = function (zLevel, config) {
  7072. if (this.painter.configLayer) {
  7073. this.painter.configLayer(zLevel, config);
  7074. }
  7075. this.refresh();
  7076. };
  7077. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  7078. if (this.painter.setBackgroundColor) {
  7079. this.painter.setBackgroundColor(backgroundColor);
  7080. }
  7081. this.refresh();
  7082. this._backgroundColor = backgroundColor;
  7083. this._darkMode = isDarkMode(backgroundColor);
  7084. };
  7085. ZRender.prototype.getBackgroundColor = function () {
  7086. return this._backgroundColor;
  7087. };
  7088. ZRender.prototype.setDarkMode = function (darkMode) {
  7089. this._darkMode = darkMode;
  7090. };
  7091. ZRender.prototype.isDarkMode = function () {
  7092. return this._darkMode;
  7093. };
  7094. ZRender.prototype.refreshImmediately = function (fromInside) {
  7095. if (!fromInside) {
  7096. this.animation.update(true);
  7097. }
  7098. this._needsRefresh = false;
  7099. this.painter.refresh();
  7100. this._needsRefresh = false;
  7101. };
  7102. ZRender.prototype.refresh = function () {
  7103. this._needsRefresh = true;
  7104. this.animation.start();
  7105. };
  7106. ZRender.prototype.flush = function () {
  7107. this._flush(false);
  7108. };
  7109. ZRender.prototype._flush = function (fromInside) {
  7110. var triggerRendered;
  7111. var start = getTime();
  7112. if (this._needsRefresh) {
  7113. triggerRendered = true;
  7114. this.refreshImmediately(fromInside);
  7115. }
  7116. if (this._needsRefreshHover) {
  7117. triggerRendered = true;
  7118. this.refreshHoverImmediately();
  7119. }
  7120. var end = getTime();
  7121. if (triggerRendered) {
  7122. this._stillFrameAccum = 0;
  7123. this.trigger('rendered', {
  7124. elapsedTime: end - start
  7125. });
  7126. }
  7127. else if (this._sleepAfterStill > 0) {
  7128. this._stillFrameAccum++;
  7129. if (this._stillFrameAccum > this._sleepAfterStill) {
  7130. this.animation.stop();
  7131. }
  7132. }
  7133. };
  7134. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  7135. this._sleepAfterStill = stillFramesCount;
  7136. };
  7137. ZRender.prototype.wakeUp = function () {
  7138. this.animation.start();
  7139. this._stillFrameAccum = 0;
  7140. };
  7141. ZRender.prototype.refreshHover = function () {
  7142. this._needsRefreshHover = true;
  7143. };
  7144. ZRender.prototype.refreshHoverImmediately = function () {
  7145. this._needsRefreshHover = false;
  7146. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  7147. this.painter.refreshHover();
  7148. }
  7149. };
  7150. ZRender.prototype.resize = function (opts) {
  7151. opts = opts || {};
  7152. this.painter.resize(opts.width, opts.height);
  7153. this.handler.resize();
  7154. };
  7155. ZRender.prototype.clearAnimation = function () {
  7156. this.animation.clear();
  7157. };
  7158. ZRender.prototype.getWidth = function () {
  7159. return this.painter.getWidth();
  7160. };
  7161. ZRender.prototype.getHeight = function () {
  7162. return this.painter.getHeight();
  7163. };
  7164. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  7165. this.handler.setCursorStyle(cursorStyle);
  7166. };
  7167. ZRender.prototype.findHover = function (x, y) {
  7168. return this.handler.findHover(x, y);
  7169. };
  7170. ZRender.prototype.on = function (eventName, eventHandler, context) {
  7171. this.handler.on(eventName, eventHandler, context);
  7172. return this;
  7173. };
  7174. ZRender.prototype.off = function (eventName, eventHandler) {
  7175. this.handler.off(eventName, eventHandler);
  7176. };
  7177. ZRender.prototype.trigger = function (eventName, event) {
  7178. this.handler.trigger(eventName, event);
  7179. };
  7180. ZRender.prototype.clear = function () {
  7181. var roots = this.storage.getRoots();
  7182. for (var i = 0; i < roots.length; i++) {
  7183. if (roots[i] instanceof Group) {
  7184. roots[i].removeSelfFromZr(this);
  7185. }
  7186. }
  7187. this.storage.delAllRoots();
  7188. this.painter.clear();
  7189. };
  7190. ZRender.prototype.dispose = function () {
  7191. this.animation.stop();
  7192. this.clear();
  7193. this.storage.dispose();
  7194. this.painter.dispose();
  7195. this.handler.dispose();
  7196. this.animation =
  7197. this.storage =
  7198. this.painter =
  7199. this.handler = null;
  7200. delInstance(this.id);
  7201. };
  7202. return ZRender;
  7203. }());
  7204. function init(dom, opts) {
  7205. var zr = new ZRender(guid(), dom, opts);
  7206. instances[zr.id] = zr;
  7207. return zr;
  7208. }
  7209. function dispose(zr) {
  7210. zr.dispose();
  7211. }
  7212. function disposeAll() {
  7213. for (var key in instances) {
  7214. if (instances.hasOwnProperty(key)) {
  7215. instances[key].dispose();
  7216. }
  7217. }
  7218. instances = {};
  7219. }
  7220. function getInstance(id) {
  7221. return instances[id];
  7222. }
  7223. function registerPainter(name, Ctor) {
  7224. painterCtors[name] = Ctor;
  7225. }
  7226. var version = '5.4.4';
  7227. var zrender = /*#__PURE__*/Object.freeze({
  7228. __proto__: null,
  7229. init: init,
  7230. dispose: dispose,
  7231. disposeAll: disposeAll,
  7232. getInstance: getInstance,
  7233. registerPainter: registerPainter,
  7234. version: version
  7235. });
  7236. var RADIAN_EPSILON = 1e-4; // Although chrome already enlarge this number to 100 for `toFixed`, but
  7237. // we sill follow the spec for compatibility.
  7238. var ROUND_SUPPORTED_PRECISION_MAX = 20;
  7239. function _trim(str) {
  7240. return str.replace(/^\s+|\s+$/g, '');
  7241. }
  7242. /**
  7243. * Linear mapping a value from domain to range
  7244. * @param val
  7245. * @param domain Domain extent domain[0] can be bigger than domain[1]
  7246. * @param range Range extent range[0] can be bigger than range[1]
  7247. * @param clamp Default to be false
  7248. */
  7249. function linearMap(val, domain, range, clamp) {
  7250. var d0 = domain[0];
  7251. var d1 = domain[1];
  7252. var r0 = range[0];
  7253. var r1 = range[1];
  7254. var subDomain = d1 - d0;
  7255. var subRange = r1 - r0;
  7256. if (subDomain === 0) {
  7257. return subRange === 0 ? r0 : (r0 + r1) / 2;
  7258. } // Avoid accuracy problem in edge, such as
  7259. // 146.39 - 62.83 === 83.55999999999999.
  7260. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  7261. // It is a little verbose for efficiency considering this method
  7262. // is a hotspot.
  7263. if (clamp) {
  7264. if (subDomain > 0) {
  7265. if (val <= d0) {
  7266. return r0;
  7267. } else if (val >= d1) {
  7268. return r1;
  7269. }
  7270. } else {
  7271. if (val >= d0) {
  7272. return r0;
  7273. } else if (val <= d1) {
  7274. return r1;
  7275. }
  7276. }
  7277. } else {
  7278. if (val === d0) {
  7279. return r0;
  7280. }
  7281. if (val === d1) {
  7282. return r1;
  7283. }
  7284. }
  7285. return (val - d0) / subDomain * subRange + r0;
  7286. }
  7287. /**
  7288. * Convert a percent string to absolute number.
  7289. * Returns NaN if percent is not a valid string or number
  7290. */
  7291. function parsePercent$1(percent, all) {
  7292. switch (percent) {
  7293. case 'center':
  7294. case 'middle':
  7295. percent = '50%';
  7296. break;
  7297. case 'left':
  7298. case 'top':
  7299. percent = '0%';
  7300. break;
  7301. case 'right':
  7302. case 'bottom':
  7303. percent = '100%';
  7304. break;
  7305. }
  7306. if (isString(percent)) {
  7307. if (_trim(percent).match(/%$/)) {
  7308. return parseFloat(percent) / 100 * all;
  7309. }
  7310. return parseFloat(percent);
  7311. }
  7312. return percent == null ? NaN : +percent;
  7313. }
  7314. function round(x, precision, returnStr) {
  7315. if (precision == null) {
  7316. precision = 10;
  7317. } // Avoid range error
  7318. precision = Math.min(Math.max(0, precision), ROUND_SUPPORTED_PRECISION_MAX); // PENDING: 1.005.toFixed(2) is '1.00' rather than '1.01'
  7319. x = (+x).toFixed(precision);
  7320. return returnStr ? x : +x;
  7321. }
  7322. /**
  7323. * Inplacd asc sort arr.
  7324. * The input arr will be modified.
  7325. */
  7326. function asc(arr) {
  7327. arr.sort(function (a, b) {
  7328. return a - b;
  7329. });
  7330. return arr;
  7331. }
  7332. /**
  7333. * Get precision.
  7334. */
  7335. function getPrecision(val) {
  7336. val = +val;
  7337. if (isNaN(val)) {
  7338. return 0;
  7339. } // It is much faster than methods converting number to string as follows
  7340. // let tmp = val.toString();
  7341. // return tmp.length - 1 - tmp.indexOf('.');
  7342. // especially when precision is low
  7343. // Notice:
  7344. // (1) If the loop count is over about 20, it is slower than `getPrecisionSafe`.
  7345. // (see https://jsbench.me/2vkpcekkvw/1)
  7346. // (2) If the val is less than for example 1e-15, the result may be incorrect.
  7347. // (see test/ut/spec/util/number.test.ts `getPrecision_equal_random`)
  7348. if (val > 1e-14) {
  7349. var e = 1;
  7350. for (var i = 0; i < 15; i++, e *= 10) {
  7351. if (Math.round(val * e) / e === val) {
  7352. return i;
  7353. }
  7354. }
  7355. }
  7356. return getPrecisionSafe(val);
  7357. }
  7358. /**
  7359. * Get precision with slow but safe method
  7360. */
  7361. function getPrecisionSafe(val) {
  7362. // toLowerCase for: '3.4E-12'
  7363. var str = val.toString().toLowerCase(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  7364. var eIndex = str.indexOf('e');
  7365. var exp = eIndex > 0 ? +str.slice(eIndex + 1) : 0;
  7366. var significandPartLen = eIndex > 0 ? eIndex : str.length;
  7367. var dotIndex = str.indexOf('.');
  7368. var decimalPartLen = dotIndex < 0 ? 0 : significandPartLen - 1 - dotIndex;
  7369. return Math.max(0, decimalPartLen - exp);
  7370. }
  7371. /**
  7372. * Minimal dicernible data precisioin according to a single pixel.
  7373. */
  7374. function getPixelPrecision(dataExtent, pixelExtent) {
  7375. var log = Math.log;
  7376. var LN10 = Math.LN10;
  7377. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  7378. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  7379. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  7380. return !isFinite(precision) ? 20 : precision;
  7381. }
  7382. /**
  7383. * Get a data of given precision, assuring the sum of percentages
  7384. * in valueList is 1.
  7385. * The largest remainder method is used.
  7386. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7387. *
  7388. * @param valueList a list of all data
  7389. * @param idx index of the data to be processed in valueList
  7390. * @param precision integer number showing digits of precision
  7391. * @return percent ranging from 0 to 100
  7392. */
  7393. function getPercentWithPrecision(valueList, idx, precision) {
  7394. if (!valueList[idx]) {
  7395. return 0;
  7396. }
  7397. var seats = getPercentSeats(valueList, precision);
  7398. return seats[idx] || 0;
  7399. }
  7400. /**
  7401. * Get a data of given precision, assuring the sum of percentages
  7402. * in valueList is 1.
  7403. * The largest remainder method is used.
  7404. * https://en.wikipedia.org/wiki/Largest_remainder_method
  7405. *
  7406. * @param valueList a list of all data
  7407. * @param precision integer number showing digits of precision
  7408. * @return {Array<number>}
  7409. */
  7410. function getPercentSeats(valueList, precision) {
  7411. var sum = reduce(valueList, function (acc, val) {
  7412. return acc + (isNaN(val) ? 0 : val);
  7413. }, 0);
  7414. if (sum === 0) {
  7415. return [];
  7416. }
  7417. var digits = Math.pow(10, precision);
  7418. var votesPerQuota = map(valueList, function (val) {
  7419. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  7420. });
  7421. var targetSeats = digits * 100;
  7422. var seats = map(votesPerQuota, function (votes) {
  7423. // Assign automatic seats.
  7424. return Math.floor(votes);
  7425. });
  7426. var currentSum = reduce(seats, function (acc, val) {
  7427. return acc + val;
  7428. }, 0);
  7429. var remainder = map(votesPerQuota, function (votes, idx) {
  7430. return votes - seats[idx];
  7431. }); // Has remainding votes.
  7432. while (currentSum < targetSeats) {
  7433. // Find next largest remainder.
  7434. var max = Number.NEGATIVE_INFINITY;
  7435. var maxId = null;
  7436. for (var i = 0, len = remainder.length; i < len; ++i) {
  7437. if (remainder[i] > max) {
  7438. max = remainder[i];
  7439. maxId = i;
  7440. }
  7441. } // Add a vote to max remainder.
  7442. ++seats[maxId];
  7443. remainder[maxId] = 0;
  7444. ++currentSum;
  7445. }
  7446. return map(seats, function (seat) {
  7447. return seat / digits;
  7448. });
  7449. }
  7450. /**
  7451. * Solve the floating point adding problem like 0.1 + 0.2 === 0.30000000000000004
  7452. * See <http://0.30000000000000004.com/>
  7453. */
  7454. function addSafe(val0, val1) {
  7455. var maxPrecision = Math.max(getPrecision(val0), getPrecision(val1)); // const multiplier = Math.pow(10, maxPrecision);
  7456. // return (Math.round(val0 * multiplier) + Math.round(val1 * multiplier)) / multiplier;
  7457. var sum = val0 + val1; // // PENDING: support more?
  7458. return maxPrecision > ROUND_SUPPORTED_PRECISION_MAX ? sum : round(sum, maxPrecision);
  7459. } // Number.MAX_SAFE_INTEGER, ie do not support.
  7460. var MAX_SAFE_INTEGER = 9007199254740991;
  7461. /**
  7462. * To 0 - 2 * PI, considering negative radian.
  7463. */
  7464. function remRadian(radian) {
  7465. var pi2 = Math.PI * 2;
  7466. return (radian % pi2 + pi2) % pi2;
  7467. }
  7468. /**
  7469. * @param {type} radian
  7470. * @return {boolean}
  7471. */
  7472. function isRadianAroundZero(val) {
  7473. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  7474. } // eslint-disable-next-line
  7475. 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
  7476. /**
  7477. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  7478. * These values can be accepted:
  7479. * + An instance of Date, represent a time in its own time zone.
  7480. * + Or string in a subset of ISO 8601, only including:
  7481. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  7482. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  7483. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  7484. * all of which will be treated as local time if time zone is not specified
  7485. * (see <https://momentjs.com/>).
  7486. * + Or other string format, including (all of which will be treated as local time):
  7487. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  7488. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  7489. * + a timestamp, which represent a time in UTC.
  7490. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  7491. */
  7492. function parseDate(value) {
  7493. if (value instanceof Date) {
  7494. return value;
  7495. } else if (isString(value)) {
  7496. // Different browsers parse date in different way, so we parse it manually.
  7497. // Some other issues:
  7498. // new Date('1970-01-01') is UTC,
  7499. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  7500. // See issue #3623
  7501. var match = TIME_REG.exec(value);
  7502. if (!match) {
  7503. // return Invalid Date.
  7504. return new Date(NaN);
  7505. } // Use local time when no timezone offset is specified.
  7506. if (!match[8]) {
  7507. // match[n] can only be string or undefined.
  7508. // But take care of '12' + 1 => '121'.
  7509. 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);
  7510. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  7511. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  7512. // For example, system timezone is set as "Time Zone: America/Toronto",
  7513. // then these code will get different result:
  7514. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  7515. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  7516. // So we should not use `new Date`, but use `Date.UTC`.
  7517. else {
  7518. var hour = +match[4] || 0;
  7519. if (match[8].toUpperCase() !== 'Z') {
  7520. hour -= +match[8].slice(0, 3);
  7521. }
  7522. 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));
  7523. }
  7524. } else if (value == null) {
  7525. return new Date(NaN);
  7526. }
  7527. return new Date(Math.round(value));
  7528. }
  7529. /**
  7530. * Quantity of a number. e.g. 0.1, 1, 10, 100
  7531. *
  7532. * @param val
  7533. * @return
  7534. */
  7535. function quantity(val) {
  7536. return Math.pow(10, quantityExponent(val));
  7537. }
  7538. /**
  7539. * Exponent of the quantity of a number
  7540. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  7541. *
  7542. * @param val non-negative value
  7543. * @return
  7544. */
  7545. function quantityExponent(val) {
  7546. if (val === 0) {
  7547. return 0;
  7548. }
  7549. var exp = Math.floor(Math.log(val) / Math.LN10);
  7550. /**
  7551. * exp is expected to be the rounded-down result of the base-10 log of val.
  7552. * But due to the precision loss with Math.log(val), we need to restore it
  7553. * using 10^exp to make sure we can get val back from exp. #11249
  7554. */
  7555. if (val / Math.pow(10, exp) >= 10) {
  7556. exp++;
  7557. }
  7558. return exp;
  7559. }
  7560. /**
  7561. * find a “nice” number approximately equal to x. Round the number if round = true,
  7562. * take ceiling if round = false. The primary observation is that the “nicest”
  7563. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  7564. *
  7565. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  7566. *
  7567. * @param val Non-negative value.
  7568. * @param round
  7569. * @return Niced number
  7570. */
  7571. function nice(val, round) {
  7572. var exponent = quantityExponent(val);
  7573. var exp10 = Math.pow(10, exponent);
  7574. var f = val / exp10; // 1 <= f < 10
  7575. var nf;
  7576. if (round) {
  7577. if (f < 1.5) {
  7578. nf = 1;
  7579. } else if (f < 2.5) {
  7580. nf = 2;
  7581. } else if (f < 4) {
  7582. nf = 3;
  7583. } else if (f < 7) {
  7584. nf = 5;
  7585. } else {
  7586. nf = 10;
  7587. }
  7588. } else {
  7589. if (f < 1) {
  7590. nf = 1;
  7591. } else if (f < 2) {
  7592. nf = 2;
  7593. } else if (f < 3) {
  7594. nf = 3;
  7595. } else if (f < 5) {
  7596. nf = 5;
  7597. } else {
  7598. nf = 10;
  7599. }
  7600. }
  7601. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  7602. // 20 is the uppper bound of toFixed.
  7603. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  7604. }
  7605. /**
  7606. * This code was copied from "d3.js"
  7607. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  7608. * See the license statement at the head of this file.
  7609. * @param ascArr
  7610. */
  7611. function quantile(ascArr, p) {
  7612. var H = (ascArr.length - 1) * p + 1;
  7613. var h = Math.floor(H);
  7614. var v = +ascArr[h - 1];
  7615. var e = H - h;
  7616. return e ? v + e * (ascArr[h] - v) : v;
  7617. }
  7618. /**
  7619. * Order intervals asc, and split them when overlap.
  7620. * expect(numberUtil.reformIntervals([
  7621. * {interval: [18, 62], close: [1, 1]},
  7622. * {interval: [-Infinity, -70], close: [0, 0]},
  7623. * {interval: [-70, -26], close: [1, 1]},
  7624. * {interval: [-26, 18], close: [1, 1]},
  7625. * {interval: [62, 150], close: [1, 1]},
  7626. * {interval: [106, 150], close: [1, 1]},
  7627. * {interval: [150, Infinity], close: [0, 0]}
  7628. * ])).toEqual([
  7629. * {interval: [-Infinity, -70], close: [0, 0]},
  7630. * {interval: [-70, -26], close: [1, 1]},
  7631. * {interval: [-26, 18], close: [0, 1]},
  7632. * {interval: [18, 62], close: [0, 1]},
  7633. * {interval: [62, 150], close: [0, 1]},
  7634. * {interval: [150, Infinity], close: [0, 0]}
  7635. * ]);
  7636. * @param list, where `close` mean open or close
  7637. * of the interval, and Infinity can be used.
  7638. * @return The origin list, which has been reformed.
  7639. */
  7640. function reformIntervals(list) {
  7641. list.sort(function (a, b) {
  7642. return littleThan(a, b, 0) ? -1 : 1;
  7643. });
  7644. var curr = -Infinity;
  7645. var currClose = 1;
  7646. for (var i = 0; i < list.length;) {
  7647. var interval = list[i].interval;
  7648. var close_1 = list[i].close;
  7649. for (var lg = 0; lg < 2; lg++) {
  7650. if (interval[lg] <= curr) {
  7651. interval[lg] = curr;
  7652. close_1[lg] = !lg ? 1 - currClose : 1;
  7653. }
  7654. curr = interval[lg];
  7655. currClose = close_1[lg];
  7656. }
  7657. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  7658. list.splice(i, 1);
  7659. } else {
  7660. i++;
  7661. }
  7662. }
  7663. return list;
  7664. function littleThan(a, b, lg) {
  7665. 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));
  7666. }
  7667. }
  7668. /**
  7669. * [Numeric is defined as]:
  7670. * `parseFloat(val) == val`
  7671. * For example:
  7672. * numeric:
  7673. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  7674. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  7675. * not-numeric:
  7676. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  7677. * empty string, string with only white-spaces or line-terminal (see es spec),
  7678. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  7679. * non-string, ...
  7680. *
  7681. * @test See full test cases in `test/ut/spec/util/number.js`.
  7682. * @return Must be a typeof number. If not numeric, return NaN.
  7683. */
  7684. function numericToNumber(val) {
  7685. var valFloat = parseFloat(val);
  7686. return valFloat == val // eslint-disable-line eqeqeq
  7687. && (valFloat !== 0 || !isString(val) || val.indexOf('x') <= 0) // For case ' 0x0 '.
  7688. ? valFloat : NaN;
  7689. }
  7690. /**
  7691. * Definition of "numeric": see `numericToNumber`.
  7692. */
  7693. function isNumeric(val) {
  7694. return !isNaN(numericToNumber(val));
  7695. }
  7696. /**
  7697. * Use random base to prevent users hard code depending on
  7698. * this auto generated marker id.
  7699. * @return An positive integer.
  7700. */
  7701. function getRandomIdBase() {
  7702. return Math.round(Math.random() * 9);
  7703. }
  7704. /**
  7705. * Get the greatest common divisor.
  7706. *
  7707. * @param {number} a one number
  7708. * @param {number} b the other number
  7709. */
  7710. function getGreatestCommonDividor(a, b) {
  7711. if (b === 0) {
  7712. return a;
  7713. }
  7714. return getGreatestCommonDividor(b, a % b);
  7715. }
  7716. /**
  7717. * Get the least common multiple.
  7718. *
  7719. * @param {number} a one number
  7720. * @param {number} b the other number
  7721. */
  7722. function getLeastCommonMultiple(a, b) {
  7723. if (a == null) {
  7724. return b;
  7725. }
  7726. if (b == null) {
  7727. return a;
  7728. }
  7729. return a * b / getGreatestCommonDividor(a, b);
  7730. }
  7731. var ECHARTS_PREFIX = '[ECharts] ';
  7732. var storedLogs = {};
  7733. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  7734. && console.warn && console.log;
  7735. function outputLog(type, str, onlyOnce) {
  7736. if (hasConsole) {
  7737. if (onlyOnce) {
  7738. if (storedLogs[str]) {
  7739. return;
  7740. }
  7741. storedLogs[str] = true;
  7742. } // eslint-disable-next-line
  7743. console[type](ECHARTS_PREFIX + str);
  7744. }
  7745. }
  7746. function log(str, onlyOnce) {
  7747. outputLog('log', str, onlyOnce);
  7748. }
  7749. function warn(str, onlyOnce) {
  7750. outputLog('warn', str, onlyOnce);
  7751. }
  7752. function error(str, onlyOnce) {
  7753. outputLog('error', str, onlyOnce);
  7754. }
  7755. function deprecateLog(str) {
  7756. if ("development" !== 'production') {
  7757. // Not display duplicate message.
  7758. outputLog('warn', 'DEPRECATED: ' + str, true);
  7759. }
  7760. }
  7761. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7762. if ("development" !== 'production') {
  7763. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7764. }
  7765. }
  7766. /**
  7767. * If in __DEV__ environment, get console printable message for users hint.
  7768. * Parameters are separated by ' '.
  7769. * @usage
  7770. * makePrintable('This is an error on', someVar, someObj);
  7771. *
  7772. * @param hintInfo anything about the current execution context to hint users.
  7773. * @throws Error
  7774. */
  7775. function makePrintable() {
  7776. var hintInfo = [];
  7777. for (var _i = 0; _i < arguments.length; _i++) {
  7778. hintInfo[_i] = arguments[_i];
  7779. }
  7780. var msg = '';
  7781. if ("development" !== 'production') {
  7782. // Fuzzy stringify for print.
  7783. // This code only exist in dev environment.
  7784. var makePrintableStringIfPossible_1 = function (val) {
  7785. 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;
  7786. };
  7787. msg = map(hintInfo, function (arg) {
  7788. if (isString(arg)) {
  7789. // Print without quotation mark for some statement.
  7790. return arg;
  7791. } else {
  7792. var printableStr = makePrintableStringIfPossible_1(arg);
  7793. if (printableStr != null) {
  7794. return printableStr;
  7795. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7796. try {
  7797. return JSON.stringify(arg, function (n, val) {
  7798. var printableStr = makePrintableStringIfPossible_1(val);
  7799. return printableStr == null ? val : printableStr;
  7800. }); // In most cases the info object is small, so do not line break.
  7801. } catch (err) {
  7802. return '?';
  7803. }
  7804. } else {
  7805. return '?';
  7806. }
  7807. }
  7808. }).join(' ');
  7809. }
  7810. return msg;
  7811. }
  7812. /**
  7813. * @throws Error
  7814. */
  7815. function throwError(msg) {
  7816. throw new Error(msg);
  7817. }
  7818. function interpolateNumber$1(p0, p1, percent) {
  7819. return (p1 - p0) * percent + p0;
  7820. }
  7821. /**
  7822. * Make the name displayable. But we should
  7823. * make sure it is not duplicated with user
  7824. * specified name, so use '\0';
  7825. */
  7826. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7827. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7828. /**
  7829. * If value is not array, then translate it to array.
  7830. * @param {*} value
  7831. * @return {Array} [value] or value
  7832. */
  7833. function normalizeToArray(value) {
  7834. return value instanceof Array ? value : value == null ? [] : [value];
  7835. }
  7836. /**
  7837. * Sync default option between normal and emphasis like `position` and `show`
  7838. * In case some one will write code like
  7839. * label: {
  7840. * show: false,
  7841. * position: 'outside',
  7842. * fontSize: 18
  7843. * },
  7844. * emphasis: {
  7845. * label: { show: true }
  7846. * }
  7847. */
  7848. function defaultEmphasis(opt, key, subOpts) {
  7849. // Caution: performance sensitive.
  7850. if (opt) {
  7851. opt[key] = opt[key] || {};
  7852. opt.emphasis = opt.emphasis || {};
  7853. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7854. for (var i = 0, len = subOpts.length; i < len; i++) {
  7855. var subOptName = subOpts[i];
  7856. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7857. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7858. }
  7859. }
  7860. }
  7861. }
  7862. 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([
  7863. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7864. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7865. // // FIXME: deprecated, check and remove it.
  7866. // 'textStyle'
  7867. // ]);
  7868. /**
  7869. * The method does not ensure performance.
  7870. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7871. * This helper method retrieves value from data.
  7872. */
  7873. function getDataItemValue(dataItem) {
  7874. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7875. }
  7876. /**
  7877. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7878. * This helper method determine if dataItem has extra option besides value
  7879. */
  7880. function isDataItemOption(dataItem) {
  7881. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7882. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7883. }
  7884. /**
  7885. * Mapping to existings for merge.
  7886. *
  7887. * Mode "normalMege":
  7888. * The mapping result (merge result) will keep the order of the existing
  7889. * component, rather than the order of new option. Because we should ensure
  7890. * some specified index reference (like xAxisIndex) keep work.
  7891. * And in most cases, "merge option" is used to update partial option but not
  7892. * be expected to change the order.
  7893. *
  7894. * Mode "replaceMege":
  7895. * (1) Only the id mapped components will be merged.
  7896. * (2) Other existing components (except internal components) will be removed.
  7897. * (3) Other new options will be used to create new component.
  7898. * (4) The index of the existing components will not be modified.
  7899. * That means their might be "hole" after the removal.
  7900. * The new components are created first at those available index.
  7901. *
  7902. * Mode "replaceAll":
  7903. * This mode try to support that reproduce an echarts instance from another
  7904. * echarts instance (via `getOption`) in some simple cases.
  7905. * In this scenario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7906. * which ensures the component index referring (like `xAxisIndex: ?`) corrent. That is,
  7907. * the "hole" in `newCmptOptions` will also be kept.
  7908. * On the contrary, other modes try best to eliminate holes.
  7909. * PENDING: This is an experimental mode yet.
  7910. *
  7911. * @return See the comment of <MappingResult>.
  7912. */
  7913. function mappingToExists(existings, newCmptOptions, mode) {
  7914. var isNormalMergeMode = mode === 'normalMerge';
  7915. var isReplaceMergeMode = mode === 'replaceMerge';
  7916. var isReplaceAllMode = mode === 'replaceAll';
  7917. existings = existings || [];
  7918. newCmptOptions = (newCmptOptions || []).slice();
  7919. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7920. each(newCmptOptions, function (cmptOption, index) {
  7921. if (!isObject(cmptOption)) {
  7922. newCmptOptions[index] = null;
  7923. return;
  7924. }
  7925. if ("development" !== 'production') {
  7926. // There is some legacy case that name is set as `false`.
  7927. // But should work normally rather than throw error.
  7928. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7929. warnInvalidateIdOrName(cmptOption.id);
  7930. }
  7931. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7932. warnInvalidateIdOrName(cmptOption.name);
  7933. }
  7934. }
  7935. });
  7936. var result = prepareResult(existings, existingIdIdxMap, mode);
  7937. if (isNormalMergeMode || isReplaceMergeMode) {
  7938. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7939. }
  7940. if (isNormalMergeMode) {
  7941. mappingByName(result, newCmptOptions);
  7942. }
  7943. if (isNormalMergeMode || isReplaceMergeMode) {
  7944. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7945. } else if (isReplaceAllMode) {
  7946. mappingInReplaceAllMode(result, newCmptOptions);
  7947. }
  7948. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7949. // forEach will omit those items and result in incorrect result.
  7950. return result;
  7951. }
  7952. function prepareResult(existings, existingIdIdxMap, mode) {
  7953. var result = [];
  7954. if (mode === 'replaceAll') {
  7955. return result;
  7956. } // Do not use native `map` to in case that the array `existings`
  7957. // contains elided items, which will be omitted.
  7958. for (var index = 0; index < existings.length; index++) {
  7959. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7960. if (existing && existing.id != null) {
  7961. existingIdIdxMap.set(existing.id, index);
  7962. } // For non-internal-componnets:
  7963. // Mode "normalMerge": all existings kept.
  7964. // Mode "replaceMerge": all existing removed unless mapped by id.
  7965. // For internal-components:
  7966. // go with "replaceMerge" approach in both mode.
  7967. result.push({
  7968. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7969. newOption: null,
  7970. keyInfo: null,
  7971. brandNew: null
  7972. });
  7973. }
  7974. return result;
  7975. }
  7976. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7977. // Mapping by id if specified.
  7978. each(newCmptOptions, function (cmptOption, index) {
  7979. if (!cmptOption || cmptOption.id == null) {
  7980. return;
  7981. }
  7982. var optionId = makeComparableKey(cmptOption.id);
  7983. var existingIdx = existingIdIdxMap.get(optionId);
  7984. if (existingIdx != null) {
  7985. var resultItem = result[existingIdx];
  7986. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7987. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7988. // the existings rather than creating new component model.
  7989. resultItem.existing = existings[existingIdx];
  7990. newCmptOptions[index] = null;
  7991. }
  7992. });
  7993. }
  7994. function mappingByName(result, newCmptOptions) {
  7995. // Mapping by name if specified.
  7996. each(newCmptOptions, function (cmptOption, index) {
  7997. if (!cmptOption || cmptOption.name == null) {
  7998. return;
  7999. }
  8000. for (var i = 0; i < result.length; i++) {
  8001. var existing = result[i].existing;
  8002. if (!result[i].newOption // Consider name: two map to one.
  8003. // Can not match when both ids existing but different.
  8004. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  8005. result[i].newOption = cmptOption;
  8006. newCmptOptions[index] = null;
  8007. return;
  8008. }
  8009. }
  8010. });
  8011. }
  8012. function mappingByIndex(result, newCmptOptions, brandNew) {
  8013. each(newCmptOptions, function (cmptOption) {
  8014. if (!cmptOption) {
  8015. return;
  8016. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  8017. var resultItem;
  8018. var nextIdx = 0;
  8019. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  8020. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  8021. // after mapping performed, model will always be assigned with an id if user not given.
  8022. // After that all models have id.
  8023. // (2) If new option has id, it can only set to a hole or append to the last. It should
  8024. // not be merged to the existings with different id. Because id should not be overwritten.
  8025. // (3) Name can be overwritten, because axis use name as 'show label text'.
  8026. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  8027. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  8028. nextIdx++;
  8029. }
  8030. if (resultItem) {
  8031. resultItem.newOption = cmptOption;
  8032. resultItem.brandNew = brandNew;
  8033. } else {
  8034. result.push({
  8035. newOption: cmptOption,
  8036. brandNew: brandNew,
  8037. existing: null,
  8038. keyInfo: null
  8039. });
  8040. }
  8041. nextIdx++;
  8042. });
  8043. }
  8044. function mappingInReplaceAllMode(result, newCmptOptions) {
  8045. each(newCmptOptions, function (cmptOption) {
  8046. // The feature "reproduce" requires "hole" will also reproduced
  8047. // in case that component index referring are broken.
  8048. result.push({
  8049. newOption: cmptOption,
  8050. brandNew: true,
  8051. existing: null,
  8052. keyInfo: null
  8053. });
  8054. });
  8055. }
  8056. /**
  8057. * Make id and name for mapping result (result of mappingToExists)
  8058. * into `keyInfo` field.
  8059. */
  8060. function makeIdAndName(mapResult) {
  8061. // We use this id to hash component models and view instances
  8062. // in echarts. id can be specified by user, or auto generated.
  8063. // The id generation rule ensures new view instance are able
  8064. // to mapped to old instance when setOption are called in
  8065. // no-merge mode. So we generate model id by name and plus
  8066. // type in view id.
  8067. // name can be duplicated among components, which is convenient
  8068. // to specify multi components (like series) by one name.
  8069. // Ensure that each id is distinct.
  8070. var idMap = createHashMap();
  8071. each(mapResult, function (item) {
  8072. var existing = item.existing;
  8073. existing && idMap.set(existing.id, item);
  8074. });
  8075. each(mapResult, function (item) {
  8076. var opt = item.newOption; // Force ensure id not duplicated.
  8077. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  8078. opt && opt.id != null && idMap.set(opt.id, item);
  8079. !item.keyInfo && (item.keyInfo = {});
  8080. }); // Make name and id.
  8081. each(mapResult, function (item, index) {
  8082. var existing = item.existing;
  8083. var opt = item.newOption;
  8084. var keyInfo = item.keyInfo;
  8085. if (!isObject(opt)) {
  8086. return;
  8087. } // Name can be overwritten. Consider case: axis.name = '20km'.
  8088. // But id generated by name will not be changed, which affect
  8089. // only in that case: setOption with 'not merge mode' and view
  8090. // instance will be recreated, which can be accepted.
  8091. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid that different series has the same name,
  8092. // because name may be used like in color pallet.
  8093. : DUMMY_COMPONENT_NAME_PREFIX + index;
  8094. if (existing) {
  8095. keyInfo.id = makeComparableKey(existing.id);
  8096. } else if (opt.id != null) {
  8097. keyInfo.id = makeComparableKey(opt.id);
  8098. } else {
  8099. // Consider this situatoin:
  8100. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  8101. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  8102. // Series with the same name between optionA and optionB
  8103. // should be mapped.
  8104. var idNum = 0;
  8105. do {
  8106. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  8107. } while (idMap.get(keyInfo.id));
  8108. }
  8109. idMap.set(keyInfo.id, item);
  8110. });
  8111. }
  8112. function keyExistAndEqual(attr, obj1, obj2) {
  8113. var key1 = convertOptionIdName(obj1[attr], null);
  8114. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  8115. return key1 != null && key2 != null && key1 === key2;
  8116. }
  8117. /**
  8118. * @return return null if not exist.
  8119. */
  8120. function makeComparableKey(val) {
  8121. if ("development" !== 'production') {
  8122. if (val == null) {
  8123. throw new Error();
  8124. }
  8125. }
  8126. return convertOptionIdName(val, '');
  8127. }
  8128. function convertOptionIdName(idOrName, defaultValue) {
  8129. if (idOrName == null) {
  8130. return defaultValue;
  8131. }
  8132. return isString(idOrName) ? idOrName : isNumber(idOrName) || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  8133. }
  8134. function warnInvalidateIdOrName(idOrName) {
  8135. if ("development" !== 'production') {
  8136. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  8137. }
  8138. }
  8139. function isValidIdOrName(idOrName) {
  8140. return isStringSafe(idOrName) || isNumeric(idOrName);
  8141. }
  8142. function isNameSpecified(componentModel) {
  8143. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  8144. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  8145. }
  8146. /**
  8147. * @public
  8148. * @param {Object} cmptOption
  8149. * @return {boolean}
  8150. */
  8151. function isComponentIdInternal(cmptOption) {
  8152. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  8153. }
  8154. function makeInternalComponentId(idSuffix) {
  8155. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  8156. }
  8157. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  8158. // Set mainType and complete subType.
  8159. each(mappingResult, function (item) {
  8160. var newOption = item.newOption;
  8161. if (isObject(newOption)) {
  8162. item.keyInfo.mainType = mainType;
  8163. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  8164. }
  8165. });
  8166. }
  8167. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  8168. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  8169. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  8170. return subType;
  8171. }
  8172. /**
  8173. * A helper for removing duplicate items between batchA and batchB,
  8174. * and in themselves, and categorize by series.
  8175. *
  8176. * @param batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8177. * @param batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  8178. * @return result: [resultBatchA, resultBatchB]
  8179. */
  8180. function compressBatches(batchA, batchB) {
  8181. var mapA = {};
  8182. var mapB = {};
  8183. makeMap(batchA || [], mapA);
  8184. makeMap(batchB || [], mapB, mapA);
  8185. return [mapToArray(mapA), mapToArray(mapB)];
  8186. function makeMap(sourceBatch, map, otherMap) {
  8187. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  8188. var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null);
  8189. if (seriesId == null) {
  8190. return;
  8191. }
  8192. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  8193. var otherDataIndices = otherMap && otherMap[seriesId];
  8194. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  8195. var dataIndex = dataIndices[j];
  8196. if (otherDataIndices && otherDataIndices[dataIndex]) {
  8197. otherDataIndices[dataIndex] = null;
  8198. } else {
  8199. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  8200. }
  8201. }
  8202. }
  8203. }
  8204. function mapToArray(map, isData) {
  8205. var result = [];
  8206. for (var i in map) {
  8207. if (map.hasOwnProperty(i) && map[i] != null) {
  8208. if (isData) {
  8209. result.push(+i);
  8210. } else {
  8211. var dataIndices = mapToArray(map[i], true);
  8212. dataIndices.length && result.push({
  8213. seriesId: i,
  8214. dataIndex: dataIndices
  8215. });
  8216. }
  8217. }
  8218. }
  8219. return result;
  8220. }
  8221. }
  8222. /**
  8223. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  8224. * each of which can be Array or primary type.
  8225. * @return dataIndex If not found, return undefined/null.
  8226. */
  8227. function queryDataIndex(data, payload) {
  8228. if (payload.dataIndexInside != null) {
  8229. return payload.dataIndexInside;
  8230. } else if (payload.dataIndex != null) {
  8231. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  8232. return data.indexOfRawIndex(value);
  8233. }) : data.indexOfRawIndex(payload.dataIndex);
  8234. } else if (payload.name != null) {
  8235. return isArray(payload.name) ? map(payload.name, function (value) {
  8236. return data.indexOfName(value);
  8237. }) : data.indexOfName(payload.name);
  8238. }
  8239. }
  8240. /**
  8241. * Enable property storage to any host object.
  8242. * Notice: Serialization is not supported.
  8243. *
  8244. * For example:
  8245. * let inner = zrUitl.makeInner();
  8246. *
  8247. * function some1(hostObj) {
  8248. * inner(hostObj).someProperty = 1212;
  8249. * ...
  8250. * }
  8251. * function some2() {
  8252. * let fields = inner(this);
  8253. * fields.someProperty1 = 1212;
  8254. * fields.someProperty2 = 'xx';
  8255. * ...
  8256. * }
  8257. *
  8258. * @return {Function}
  8259. */
  8260. function makeInner() {
  8261. var key = '__ec_inner_' + innerUniqueIndex++;
  8262. return function (hostObj) {
  8263. return hostObj[key] || (hostObj[key] = {});
  8264. };
  8265. }
  8266. var innerUniqueIndex = getRandomIdBase();
  8267. /**
  8268. * The same behavior as `component.getReferringComponents`.
  8269. */
  8270. function parseFinder(ecModel, finderInput, opt) {
  8271. var _a = preParseFinder(finderInput, opt),
  8272. mainTypeSpecified = _a.mainTypeSpecified,
  8273. queryOptionMap = _a.queryOptionMap,
  8274. others = _a.others;
  8275. var result = others;
  8276. var defaultMainType = opt ? opt.defaultMainType : null;
  8277. if (!mainTypeSpecified && defaultMainType) {
  8278. queryOptionMap.set(defaultMainType, {});
  8279. }
  8280. queryOptionMap.each(function (queryOption, mainType) {
  8281. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  8282. useDefault: defaultMainType === mainType,
  8283. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  8284. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  8285. });
  8286. result[mainType + 'Models'] = queryResult.models;
  8287. result[mainType + 'Model'] = queryResult.models[0];
  8288. });
  8289. return result;
  8290. }
  8291. function preParseFinder(finderInput, opt) {
  8292. var finder;
  8293. if (isString(finderInput)) {
  8294. var obj = {};
  8295. obj[finderInput + 'Index'] = 0;
  8296. finder = obj;
  8297. } else {
  8298. finder = finderInput;
  8299. }
  8300. var queryOptionMap = createHashMap();
  8301. var others = {};
  8302. var mainTypeSpecified = false;
  8303. each(finder, function (value, key) {
  8304. // Exclude 'dataIndex' and other illgal keys.
  8305. if (key === 'dataIndex' || key === 'dataIndexInside') {
  8306. others[key] = value;
  8307. return;
  8308. }
  8309. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  8310. var mainType = parsedKey[1];
  8311. var queryType = (parsedKey[2] || '').toLowerCase();
  8312. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  8313. return;
  8314. }
  8315. mainTypeSpecified = mainTypeSpecified || !!mainType;
  8316. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  8317. queryOption[queryType] = value;
  8318. });
  8319. return {
  8320. mainTypeSpecified: mainTypeSpecified,
  8321. queryOptionMap: queryOptionMap,
  8322. others: others
  8323. };
  8324. }
  8325. var SINGLE_REFERRING = {
  8326. useDefault: true,
  8327. enableAll: false,
  8328. enableNone: false
  8329. };
  8330. var MULTIPLE_REFERRING = {
  8331. useDefault: false,
  8332. enableAll: true,
  8333. enableNone: true
  8334. };
  8335. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  8336. opt = opt || SINGLE_REFERRING;
  8337. var indexOption = userOption.index;
  8338. var idOption = userOption.id;
  8339. var nameOption = userOption.name;
  8340. var result = {
  8341. models: null,
  8342. specified: indexOption != null || idOption != null || nameOption != null
  8343. };
  8344. if (!result.specified) {
  8345. // Use the first as default if `useDefault`.
  8346. var firstCmpt = void 0;
  8347. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  8348. return result;
  8349. }
  8350. if (indexOption === 'none' || indexOption === false) {
  8351. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  8352. result.models = [];
  8353. return result;
  8354. } // `queryComponents` will return all components if
  8355. // both all of index/id/name are null/undefined.
  8356. if (indexOption === 'all') {
  8357. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  8358. indexOption = idOption = nameOption = null;
  8359. }
  8360. result.models = ecModel.queryComponents({
  8361. mainType: mainType,
  8362. index: indexOption,
  8363. id: idOption,
  8364. name: nameOption
  8365. });
  8366. return result;
  8367. }
  8368. function setAttribute(dom, key, value) {
  8369. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  8370. }
  8371. function getAttribute(dom, key) {
  8372. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  8373. }
  8374. function getTooltipRenderMode(renderModeOption) {
  8375. if (renderModeOption === 'auto') {
  8376. // Using html when `document` exists, use richText otherwise
  8377. return env.domSupported ? 'html' : 'richText';
  8378. } else {
  8379. return renderModeOption || 'html';
  8380. }
  8381. }
  8382. /**
  8383. * Group a list by key.
  8384. */
  8385. function groupData(array, getKey // return key
  8386. ) {
  8387. var buckets = createHashMap();
  8388. var keys = [];
  8389. each(array, function (item) {
  8390. var key = getKey(item);
  8391. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  8392. });
  8393. return {
  8394. keys: keys,
  8395. buckets: buckets
  8396. };
  8397. }
  8398. /**
  8399. * Interpolate raw values of a series with percent
  8400. *
  8401. * @param data data
  8402. * @param labelModel label model of the text element
  8403. * @param sourceValue start value. May be null/undefined when init.
  8404. * @param targetValue end value
  8405. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  8406. * @return interpolated values
  8407. * If `sourceValue` and `targetValue` are `number`, return `number`.
  8408. * If `sourceValue` and `targetValue` are `string`, return `string`.
  8409. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  8410. * Other cases do not supported.
  8411. */
  8412. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  8413. var isAutoPrecision = precision == null || precision === 'auto';
  8414. if (targetValue == null) {
  8415. return targetValue;
  8416. }
  8417. if (isNumber(targetValue)) {
  8418. var value = interpolateNumber$1(sourceValue || 0, targetValue, percent);
  8419. return round(value, isAutoPrecision ? Math.max(getPrecision(sourceValue || 0), getPrecision(targetValue)) : precision);
  8420. } else if (isString(targetValue)) {
  8421. return percent < 1 ? sourceValue : targetValue;
  8422. } else {
  8423. var interpolated = [];
  8424. var leftArr = sourceValue;
  8425. var rightArr = targetValue;
  8426. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  8427. for (var i = 0; i < length_1; ++i) {
  8428. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  8429. if (info && info.type === 'ordinal') {
  8430. // In init, there is no `sourceValue`, but should better not to get undefined result.
  8431. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  8432. } else {
  8433. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  8434. var rightVal = rightArr[i];
  8435. var value = interpolateNumber$1(leftVal, rightVal, percent);
  8436. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecision(leftVal), getPrecision(rightVal)) : precision);
  8437. }
  8438. }
  8439. return interpolated;
  8440. }
  8441. }
  8442. var TYPE_DELIMITER = '.';
  8443. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  8444. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  8445. /**
  8446. * Notice, parseClassType('') should returns {main: '', sub: ''}
  8447. * @public
  8448. */
  8449. function parseClassType(componentType) {
  8450. var ret = {
  8451. main: '',
  8452. sub: ''
  8453. };
  8454. if (componentType) {
  8455. var typeArr = componentType.split(TYPE_DELIMITER);
  8456. ret.main = typeArr[0] || '';
  8457. ret.sub = typeArr[1] || '';
  8458. }
  8459. return ret;
  8460. }
  8461. /**
  8462. * @public
  8463. */
  8464. function checkClassType(componentType) {
  8465. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  8466. }
  8467. function isExtendedClass(clz) {
  8468. return !!(clz && clz[IS_EXTENDED_CLASS]);
  8469. }
  8470. /**
  8471. * Implements `ExtendableConstructor` for `rootClz`.
  8472. *
  8473. * @usage
  8474. * ```ts
  8475. * class Xxx {}
  8476. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  8477. * enableClassExtend(Xxx as XxxConstructor);
  8478. * ```
  8479. */
  8480. function enableClassExtend(rootClz, mandatoryMethods) {
  8481. rootClz.$constructor = rootClz; // FIXME: not necessary?
  8482. rootClz.extend = function (proto) {
  8483. if ("development" !== 'production') {
  8484. each(mandatoryMethods, function (method) {
  8485. if (!proto[method]) {
  8486. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  8487. }
  8488. });
  8489. }
  8490. var superClass = this;
  8491. var ExtendedClass;
  8492. if (isESClass(superClass)) {
  8493. ExtendedClass =
  8494. /** @class */
  8495. function (_super) {
  8496. __extends(class_1, _super);
  8497. function class_1() {
  8498. return _super.apply(this, arguments) || this;
  8499. }
  8500. return class_1;
  8501. }(superClass);
  8502. } else {
  8503. // For backward compat, we both support ts class inheritance and this
  8504. // "extend" approach.
  8505. // The constructor should keep the same behavior as ts class inheritance:
  8506. // If this constructor/$constructor is not declared, auto invoke the super
  8507. // constructor.
  8508. // If this constructor/$constructor is declared, it is responsible for
  8509. // calling the super constructor.
  8510. ExtendedClass = function () {
  8511. (proto.$constructor || superClass).apply(this, arguments);
  8512. };
  8513. inherits(ExtendedClass, this);
  8514. }
  8515. extend(ExtendedClass.prototype, proto);
  8516. ExtendedClass[IS_EXTENDED_CLASS] = true;
  8517. ExtendedClass.extend = this.extend;
  8518. ExtendedClass.superCall = superCall;
  8519. ExtendedClass.superApply = superApply;
  8520. ExtendedClass.superClass = superClass;
  8521. return ExtendedClass;
  8522. };
  8523. }
  8524. function isESClass(fn) {
  8525. return isFunction(fn) && /^class\s/.test(Function.prototype.toString.call(fn));
  8526. }
  8527. /**
  8528. * A work around to both support ts extend and this extend mechanism.
  8529. * on sub-class.
  8530. * @usage
  8531. * ```ts
  8532. * class Component { ... }
  8533. * classUtil.enableClassExtend(Component);
  8534. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  8535. *
  8536. * class Series extends Component { ... }
  8537. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  8538. * Component.markExtend(Series);
  8539. * ```
  8540. */
  8541. function mountExtend(SubClz, SupperClz) {
  8542. SubClz.extend = SupperClz.extend;
  8543. } // A random offset.
  8544. var classBase = Math.round(Math.random() * 10);
  8545. /**
  8546. * Implements `CheckableConstructor` for `target`.
  8547. * Can not use instanceof, consider different scope by
  8548. * cross domain or es module import in ec extensions.
  8549. * Mount a method "isInstance()" to Clz.
  8550. *
  8551. * @usage
  8552. * ```ts
  8553. * class Xxx {}
  8554. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  8555. * enableClassCheck(Xxx as XxxConstructor)
  8556. * ```
  8557. */
  8558. function enableClassCheck(target) {
  8559. var classAttr = ['__\0is_clz', classBase++].join('_');
  8560. target.prototype[classAttr] = true;
  8561. if ("development" !== 'production') {
  8562. assert(!target.isInstance, 'The method "is" can not be defined.');
  8563. }
  8564. target.isInstance = function (obj) {
  8565. return !!(obj && obj[classAttr]);
  8566. };
  8567. } // superCall should have class info, which can not be fetched from 'this'.
  8568. // Consider this case:
  8569. // class A has method f,
  8570. // class B inherits class A, overrides method f, f call superApply('f'),
  8571. // class C inherits class B, does not override method f,
  8572. // then when method of class C is called, dead loop occurred.
  8573. function superCall(context, methodName) {
  8574. var args = [];
  8575. for (var _i = 2; _i < arguments.length; _i++) {
  8576. args[_i - 2] = arguments[_i];
  8577. }
  8578. return this.superClass.prototype[methodName].apply(context, args);
  8579. }
  8580. function superApply(context, methodName, args) {
  8581. return this.superClass.prototype[methodName].apply(context, args);
  8582. }
  8583. /**
  8584. * Implements `ClassManager` for `target`
  8585. *
  8586. * @usage
  8587. * ```ts
  8588. * class Xxx {}
  8589. * type XxxConstructor = typeof Xxx & ClassManager
  8590. * enableClassManagement(Xxx as XxxConstructor);
  8591. * ```
  8592. */
  8593. function enableClassManagement(target) {
  8594. /**
  8595. * Component model classes
  8596. * key: componentType,
  8597. * value:
  8598. * componentClass, when componentType is 'a'
  8599. * or Object.<subKey, componentClass>, when componentType is 'a.b'
  8600. */
  8601. var storage = {};
  8602. target.registerClass = function (clz) {
  8603. // `type` should not be a "instance member".
  8604. // If using TS class, should better declared as `static type = 'series.pie'`.
  8605. // otherwise users have to mount `type` on prototype manually.
  8606. // For backward compat and enable instance visit type via `this.type`,
  8607. // we still support fetch `type` from prototype.
  8608. var componentFullType = clz.type || clz.prototype.type;
  8609. if (componentFullType) {
  8610. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  8611. clz.prototype.type = componentFullType;
  8612. var componentTypeInfo = parseClassType(componentFullType);
  8613. if (!componentTypeInfo.sub) {
  8614. if ("development" !== 'production') {
  8615. if (storage[componentTypeInfo.main]) {
  8616. console.warn(componentTypeInfo.main + ' exists.');
  8617. }
  8618. }
  8619. storage[componentTypeInfo.main] = clz;
  8620. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  8621. var container = makeContainer(componentTypeInfo);
  8622. container[componentTypeInfo.sub] = clz;
  8623. }
  8624. }
  8625. return clz;
  8626. };
  8627. target.getClass = function (mainType, subType, throwWhenNotFound) {
  8628. var clz = storage[mainType];
  8629. if (clz && clz[IS_CONTAINER]) {
  8630. clz = subType ? clz[subType] : null;
  8631. }
  8632. if (throwWhenNotFound && !clz) {
  8633. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' is used but not imported.');
  8634. }
  8635. return clz;
  8636. };
  8637. target.getClassesByMainType = function (componentType) {
  8638. var componentTypeInfo = parseClassType(componentType);
  8639. var result = [];
  8640. var obj = storage[componentTypeInfo.main];
  8641. if (obj && obj[IS_CONTAINER]) {
  8642. each(obj, function (o, type) {
  8643. type !== IS_CONTAINER && result.push(o);
  8644. });
  8645. } else {
  8646. result.push(obj);
  8647. }
  8648. return result;
  8649. };
  8650. target.hasClass = function (componentType) {
  8651. // Just consider componentType.main.
  8652. var componentTypeInfo = parseClassType(componentType);
  8653. return !!storage[componentTypeInfo.main];
  8654. };
  8655. /**
  8656. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  8657. */
  8658. target.getAllClassMainTypes = function () {
  8659. var types = [];
  8660. each(storage, function (obj, type) {
  8661. types.push(type);
  8662. });
  8663. return types;
  8664. };
  8665. /**
  8666. * If a main type is container and has sub types
  8667. */
  8668. target.hasSubTypes = function (componentType) {
  8669. var componentTypeInfo = parseClassType(componentType);
  8670. var obj = storage[componentTypeInfo.main];
  8671. return obj && obj[IS_CONTAINER];
  8672. };
  8673. function makeContainer(componentTypeInfo) {
  8674. var container = storage[componentTypeInfo.main];
  8675. if (!container || !container[IS_CONTAINER]) {
  8676. container = storage[componentTypeInfo.main] = {};
  8677. container[IS_CONTAINER] = true;
  8678. }
  8679. return container;
  8680. }
  8681. } // /**
  8682. // * @param {string|Array.<string>} properties
  8683. // */
  8684. // export function setReadOnly(obj, properties) {
  8685. // FIXME It seems broken in IE8 simulation of IE11
  8686. // if (!zrUtil.isArray(properties)) {
  8687. // properties = properties != null ? [properties] : [];
  8688. // }
  8689. // zrUtil.each(properties, function (prop) {
  8690. // let value = obj[prop];
  8691. // Object.defineProperty
  8692. // && Object.defineProperty(obj, prop, {
  8693. // value: value, writable: false
  8694. // });
  8695. // zrUtil.isArray(obj[prop])
  8696. // && Object.freeze
  8697. // && Object.freeze(obj[prop]);
  8698. // });
  8699. // }
  8700. function makeStyleMapper(properties, ignoreParent) {
  8701. // Normalize
  8702. for (var i = 0; i < properties.length; i++) {
  8703. if (!properties[i][1]) {
  8704. properties[i][1] = properties[i][0];
  8705. }
  8706. }
  8707. ignoreParent = ignoreParent || false;
  8708. return function (model, excludes, includes) {
  8709. var style = {};
  8710. for (var i = 0; i < properties.length; i++) {
  8711. var propName = properties[i][1];
  8712. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  8713. continue;
  8714. }
  8715. var val = model.getShallow(propName, ignoreParent);
  8716. if (val != null) {
  8717. style[properties[i][0]] = val;
  8718. }
  8719. } // TODO Text or image?
  8720. return style;
  8721. };
  8722. }
  8723. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  8724. // So do not transfer decal directly.
  8725. ];
  8726. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  8727. var AreaStyleMixin =
  8728. /** @class */
  8729. function () {
  8730. function AreaStyleMixin() {}
  8731. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  8732. return getAreaStyle(this, excludes, includes);
  8733. };
  8734. return AreaStyleMixin;
  8735. }();
  8736. var globalImageCache = new LRU(50);
  8737. function findExistImage(newImageOrSrc) {
  8738. if (typeof newImageOrSrc === 'string') {
  8739. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8740. return cachedImgObj && cachedImgObj.image;
  8741. }
  8742. else {
  8743. return newImageOrSrc;
  8744. }
  8745. }
  8746. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  8747. if (!newImageOrSrc) {
  8748. return image;
  8749. }
  8750. else if (typeof newImageOrSrc === 'string') {
  8751. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  8752. return image;
  8753. }
  8754. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  8755. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  8756. if (cachedImgObj) {
  8757. image = cachedImgObj.image;
  8758. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8759. }
  8760. else {
  8761. image = platformApi.loadImage(newImageOrSrc, imageOnLoad, imageOnLoad);
  8762. image.__zrImageSrc = newImageOrSrc;
  8763. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8764. image: image,
  8765. pending: [pendingWrap]
  8766. });
  8767. }
  8768. return image;
  8769. }
  8770. else {
  8771. return newImageOrSrc;
  8772. }
  8773. }
  8774. function imageOnLoad() {
  8775. var cachedImgObj = this.__cachedImgObj;
  8776. this.onload = this.onerror = this.__cachedImgObj = null;
  8777. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8778. var pendingWrap = cachedImgObj.pending[i];
  8779. var cb = pendingWrap.cb;
  8780. cb && cb(this, pendingWrap.cbPayload);
  8781. pendingWrap.hostEl.dirty();
  8782. }
  8783. cachedImgObj.pending.length = 0;
  8784. }
  8785. function isImageReady(image) {
  8786. return image && image.width && image.height;
  8787. }
  8788. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8789. function truncateText(text, containerWidth, font, ellipsis, options) {
  8790. if (!containerWidth) {
  8791. return '';
  8792. }
  8793. var textLines = (text + '').split('\n');
  8794. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8795. for (var i = 0, len = textLines.length; i < len; i++) {
  8796. textLines[i] = truncateSingleLine(textLines[i], options);
  8797. }
  8798. return textLines.join('\n');
  8799. }
  8800. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8801. options = options || {};
  8802. var preparedOpts = extend({}, options);
  8803. preparedOpts.font = font;
  8804. ellipsis = retrieve2(ellipsis, '...');
  8805. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8806. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8807. preparedOpts.cnCharWidth = getWidth('国', font);
  8808. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8809. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8810. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8811. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8812. contentWidth -= ascCharWidth;
  8813. }
  8814. var ellipsisWidth = getWidth(ellipsis, font);
  8815. if (ellipsisWidth > contentWidth) {
  8816. ellipsis = '';
  8817. ellipsisWidth = 0;
  8818. }
  8819. contentWidth = containerWidth - ellipsisWidth;
  8820. preparedOpts.ellipsis = ellipsis;
  8821. preparedOpts.ellipsisWidth = ellipsisWidth;
  8822. preparedOpts.contentWidth = contentWidth;
  8823. preparedOpts.containerWidth = containerWidth;
  8824. return preparedOpts;
  8825. }
  8826. function truncateSingleLine(textLine, options) {
  8827. var containerWidth = options.containerWidth;
  8828. var font = options.font;
  8829. var contentWidth = options.contentWidth;
  8830. if (!containerWidth) {
  8831. return '';
  8832. }
  8833. var lineWidth = getWidth(textLine, font);
  8834. if (lineWidth <= containerWidth) {
  8835. return textLine;
  8836. }
  8837. for (var j = 0;; j++) {
  8838. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8839. textLine += options.ellipsis;
  8840. break;
  8841. }
  8842. var subLength = j === 0
  8843. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8844. : lineWidth > 0
  8845. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8846. : 0;
  8847. textLine = textLine.substr(0, subLength);
  8848. lineWidth = getWidth(textLine, font);
  8849. }
  8850. if (textLine === '') {
  8851. textLine = options.placeholder;
  8852. }
  8853. return textLine;
  8854. }
  8855. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8856. var width = 0;
  8857. var i = 0;
  8858. for (var len = text.length; i < len && width < contentWidth; i++) {
  8859. var charCode = text.charCodeAt(i);
  8860. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8861. }
  8862. return i;
  8863. }
  8864. function parsePlainText(text, style) {
  8865. text != null && (text += '');
  8866. var overflow = style.overflow;
  8867. var padding = style.padding;
  8868. var font = style.font;
  8869. var truncate = overflow === 'truncate';
  8870. var calculatedLineHeight = getLineHeight(font);
  8871. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8872. var bgColorDrawn = !!(style.backgroundColor);
  8873. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8874. var width = style.width;
  8875. var lines;
  8876. if (width != null && (overflow === 'break' || overflow === 'breakAll')) {
  8877. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8878. }
  8879. else {
  8880. lines = text ? text.split('\n') : [];
  8881. }
  8882. var contentHeight = lines.length * lineHeight;
  8883. var height = retrieve2(style.height, contentHeight);
  8884. if (contentHeight > height && truncateLineOverflow) {
  8885. var lineCount = Math.floor(height / lineHeight);
  8886. lines = lines.slice(0, lineCount);
  8887. }
  8888. if (text && truncate && width != null) {
  8889. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8890. minChar: style.truncateMinChar,
  8891. placeholder: style.placeholder
  8892. });
  8893. for (var i = 0; i < lines.length; i++) {
  8894. lines[i] = truncateSingleLine(lines[i], options);
  8895. }
  8896. }
  8897. var outerHeight = height;
  8898. var contentWidth = 0;
  8899. for (var i = 0; i < lines.length; i++) {
  8900. contentWidth = Math.max(getWidth(lines[i], font), contentWidth);
  8901. }
  8902. if (width == null) {
  8903. width = contentWidth;
  8904. }
  8905. var outerWidth = contentWidth;
  8906. if (padding) {
  8907. outerHeight += padding[0] + padding[2];
  8908. outerWidth += padding[1] + padding[3];
  8909. width += padding[1] + padding[3];
  8910. }
  8911. if (bgColorDrawn) {
  8912. outerWidth = width;
  8913. }
  8914. return {
  8915. lines: lines,
  8916. height: height,
  8917. outerWidth: outerWidth,
  8918. outerHeight: outerHeight,
  8919. lineHeight: lineHeight,
  8920. calculatedLineHeight: calculatedLineHeight,
  8921. contentWidth: contentWidth,
  8922. contentHeight: contentHeight,
  8923. width: width
  8924. };
  8925. }
  8926. var RichTextToken = (function () {
  8927. function RichTextToken() {
  8928. }
  8929. return RichTextToken;
  8930. }());
  8931. var RichTextLine = (function () {
  8932. function RichTextLine(tokens) {
  8933. this.tokens = [];
  8934. if (tokens) {
  8935. this.tokens = tokens;
  8936. }
  8937. }
  8938. return RichTextLine;
  8939. }());
  8940. var RichTextContentBlock = (function () {
  8941. function RichTextContentBlock() {
  8942. this.width = 0;
  8943. this.height = 0;
  8944. this.contentWidth = 0;
  8945. this.contentHeight = 0;
  8946. this.outerWidth = 0;
  8947. this.outerHeight = 0;
  8948. this.lines = [];
  8949. }
  8950. return RichTextContentBlock;
  8951. }());
  8952. function parseRichText(text, style) {
  8953. var contentBlock = new RichTextContentBlock();
  8954. text != null && (text += '');
  8955. if (!text) {
  8956. return contentBlock;
  8957. }
  8958. var topWidth = style.width;
  8959. var topHeight = style.height;
  8960. var overflow = style.overflow;
  8961. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8962. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8963. : null;
  8964. var lastIndex = STYLE_REG.lastIndex = 0;
  8965. var result;
  8966. while ((result = STYLE_REG.exec(text)) != null) {
  8967. var matchedIndex = result.index;
  8968. if (matchedIndex > lastIndex) {
  8969. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8970. }
  8971. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8972. lastIndex = STYLE_REG.lastIndex;
  8973. }
  8974. if (lastIndex < text.length) {
  8975. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8976. }
  8977. var pendingList = [];
  8978. var calculatedHeight = 0;
  8979. var calculatedWidth = 0;
  8980. var stlPadding = style.padding;
  8981. var truncate = overflow === 'truncate';
  8982. var truncateLine = style.lineOverflow === 'truncate';
  8983. function finishLine(line, lineWidth, lineHeight) {
  8984. line.width = lineWidth;
  8985. line.lineHeight = lineHeight;
  8986. calculatedHeight += lineHeight;
  8987. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8988. }
  8989. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8990. var line = contentBlock.lines[i];
  8991. var lineHeight = 0;
  8992. var lineWidth = 0;
  8993. for (var j = 0; j < line.tokens.length; j++) {
  8994. var token = line.tokens[j];
  8995. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8996. var textPadding = token.textPadding = tokenStyle.padding;
  8997. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8998. var font = token.font = tokenStyle.font || style.font;
  8999. token.contentHeight = getLineHeight(font);
  9000. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  9001. token.innerHeight = tokenHeight;
  9002. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  9003. token.height = tokenHeight;
  9004. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  9005. token.align = tokenStyle && tokenStyle.align || style.align;
  9006. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  9007. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  9008. if (j > 0) {
  9009. line.tokens = line.tokens.slice(0, j);
  9010. finishLine(line, lineWidth, lineHeight);
  9011. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  9012. }
  9013. else {
  9014. contentBlock.lines = contentBlock.lines.slice(0, i);
  9015. }
  9016. break outer;
  9017. }
  9018. var styleTokenWidth = tokenStyle.width;
  9019. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  9020. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  9021. token.percentWidth = styleTokenWidth;
  9022. pendingList.push(token);
  9023. token.contentWidth = getWidth(token.text, font);
  9024. }
  9025. else {
  9026. if (tokenWidthNotSpecified) {
  9027. var textBackgroundColor = tokenStyle.backgroundColor;
  9028. var bgImg = textBackgroundColor && textBackgroundColor.image;
  9029. if (bgImg) {
  9030. bgImg = findExistImage(bgImg);
  9031. if (isImageReady(bgImg)) {
  9032. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  9033. }
  9034. }
  9035. }
  9036. var remainTruncWidth = truncate && topWidth != null
  9037. ? topWidth - lineWidth : null;
  9038. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  9039. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  9040. token.text = '';
  9041. token.width = token.contentWidth = 0;
  9042. }
  9043. else {
  9044. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  9045. token.width = token.contentWidth = getWidth(token.text, font);
  9046. }
  9047. }
  9048. else {
  9049. token.contentWidth = getWidth(token.text, font);
  9050. }
  9051. }
  9052. token.width += paddingH;
  9053. lineWidth += token.width;
  9054. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  9055. }
  9056. finishLine(line, lineWidth, lineHeight);
  9057. }
  9058. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  9059. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  9060. contentBlock.contentHeight = calculatedHeight;
  9061. contentBlock.contentWidth = calculatedWidth;
  9062. if (stlPadding) {
  9063. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  9064. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  9065. }
  9066. for (var i = 0; i < pendingList.length; i++) {
  9067. var token = pendingList[i];
  9068. var percentWidth = token.percentWidth;
  9069. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  9070. }
  9071. return contentBlock;
  9072. }
  9073. function pushTokens(block, str, style, wrapInfo, styleName) {
  9074. var isEmptyStr = str === '';
  9075. var tokenStyle = styleName && style.rich[styleName] || {};
  9076. var lines = block.lines;
  9077. var font = tokenStyle.font || style.font;
  9078. var newLine = false;
  9079. var strLines;
  9080. var linesWidths;
  9081. if (wrapInfo) {
  9082. var tokenPadding = tokenStyle.padding;
  9083. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  9084. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  9085. var outerWidth_1 = parsePercent(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  9086. if (lines.length > 0) {
  9087. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  9088. strLines = str.split('\n');
  9089. newLine = true;
  9090. }
  9091. }
  9092. wrapInfo.accumWidth = outerWidth_1;
  9093. }
  9094. else {
  9095. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  9096. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  9097. linesWidths = res.linesWidths;
  9098. strLines = res.lines;
  9099. }
  9100. }
  9101. else {
  9102. strLines = str.split('\n');
  9103. }
  9104. for (var i = 0; i < strLines.length; i++) {
  9105. var text = strLines[i];
  9106. var token = new RichTextToken();
  9107. token.styleName = styleName;
  9108. token.text = text;
  9109. token.isLineHolder = !text && !isEmptyStr;
  9110. if (typeof tokenStyle.width === 'number') {
  9111. token.width = tokenStyle.width;
  9112. }
  9113. else {
  9114. token.width = linesWidths
  9115. ? linesWidths[i]
  9116. : getWidth(text, font);
  9117. }
  9118. if (!i && !newLine) {
  9119. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  9120. var tokensLen = tokens.length;
  9121. (tokensLen === 1 && tokens[0].isLineHolder)
  9122. ? (tokens[0] = token)
  9123. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  9124. }
  9125. else {
  9126. lines.push(new RichTextLine([token]));
  9127. }
  9128. }
  9129. }
  9130. function isAlphabeticLetter(ch) {
  9131. var code = ch.charCodeAt(0);
  9132. return code >= 0x20 && code <= 0x24F
  9133. || code >= 0x370 && code <= 0x10FF
  9134. || code >= 0x1200 && code <= 0x13FF
  9135. || code >= 0x1E00 && code <= 0x206F;
  9136. }
  9137. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  9138. obj[ch] = true;
  9139. return obj;
  9140. }, {});
  9141. function isWordBreakChar(ch) {
  9142. if (isAlphabeticLetter(ch)) {
  9143. if (breakCharMap[ch]) {
  9144. return true;
  9145. }
  9146. return false;
  9147. }
  9148. return true;
  9149. }
  9150. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  9151. var lines = [];
  9152. var linesWidths = [];
  9153. var line = '';
  9154. var currentWord = '';
  9155. var currentWordWidth = 0;
  9156. var accumWidth = 0;
  9157. for (var i = 0; i < text.length; i++) {
  9158. var ch = text.charAt(i);
  9159. if (ch === '\n') {
  9160. if (currentWord) {
  9161. line += currentWord;
  9162. accumWidth += currentWordWidth;
  9163. }
  9164. lines.push(line);
  9165. linesWidths.push(accumWidth);
  9166. line = '';
  9167. currentWord = '';
  9168. currentWordWidth = 0;
  9169. accumWidth = 0;
  9170. continue;
  9171. }
  9172. var chWidth = getWidth(ch, font);
  9173. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  9174. if (!lines.length
  9175. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  9176. : accumWidth + chWidth > lineWidth) {
  9177. if (!accumWidth) {
  9178. if (inWord) {
  9179. lines.push(currentWord);
  9180. linesWidths.push(currentWordWidth);
  9181. currentWord = ch;
  9182. currentWordWidth = chWidth;
  9183. }
  9184. else {
  9185. lines.push(ch);
  9186. linesWidths.push(chWidth);
  9187. }
  9188. }
  9189. else if (line || currentWord) {
  9190. if (inWord) {
  9191. if (!line) {
  9192. line = currentWord;
  9193. currentWord = '';
  9194. currentWordWidth = 0;
  9195. accumWidth = currentWordWidth;
  9196. }
  9197. lines.push(line);
  9198. linesWidths.push(accumWidth - currentWordWidth);
  9199. currentWord += ch;
  9200. currentWordWidth += chWidth;
  9201. line = '';
  9202. accumWidth = currentWordWidth;
  9203. }
  9204. else {
  9205. if (currentWord) {
  9206. line += currentWord;
  9207. currentWord = '';
  9208. currentWordWidth = 0;
  9209. }
  9210. lines.push(line);
  9211. linesWidths.push(accumWidth);
  9212. line = ch;
  9213. accumWidth = chWidth;
  9214. }
  9215. }
  9216. continue;
  9217. }
  9218. accumWidth += chWidth;
  9219. if (inWord) {
  9220. currentWord += ch;
  9221. currentWordWidth += chWidth;
  9222. }
  9223. else {
  9224. if (currentWord) {
  9225. line += currentWord;
  9226. currentWord = '';
  9227. currentWordWidth = 0;
  9228. }
  9229. line += ch;
  9230. }
  9231. }
  9232. if (!lines.length && !line) {
  9233. line = text;
  9234. currentWord = '';
  9235. currentWordWidth = 0;
  9236. }
  9237. if (currentWord) {
  9238. line += currentWord;
  9239. }
  9240. if (line) {
  9241. lines.push(line);
  9242. linesWidths.push(accumWidth);
  9243. }
  9244. if (lines.length === 1) {
  9245. accumWidth += lastAccumWidth;
  9246. }
  9247. return {
  9248. accumWidth: accumWidth,
  9249. lines: lines,
  9250. linesWidths: linesWidths
  9251. };
  9252. }
  9253. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  9254. var DEFAULT_COMMON_STYLE = {
  9255. shadowBlur: 0,
  9256. shadowOffsetX: 0,
  9257. shadowOffsetY: 0,
  9258. shadowColor: '#000',
  9259. opacity: 1,
  9260. blend: 'source-over'
  9261. };
  9262. var DEFAULT_COMMON_ANIMATION_PROPS = {
  9263. style: {
  9264. shadowBlur: true,
  9265. shadowOffsetX: true,
  9266. shadowOffsetY: true,
  9267. shadowColor: true,
  9268. opacity: true
  9269. }
  9270. };
  9271. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  9272. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  9273. var PRIMARY_STATES_KEYS_IN_HOVER_LAYER = ['invisible'];
  9274. var Displayable = (function (_super) {
  9275. __extends(Displayable, _super);
  9276. function Displayable(props) {
  9277. return _super.call(this, props) || this;
  9278. }
  9279. Displayable.prototype._init = function (props) {
  9280. var keysArr = keys(props);
  9281. for (var i = 0; i < keysArr.length; i++) {
  9282. var key = keysArr[i];
  9283. if (key === 'style') {
  9284. this.useStyle(props[key]);
  9285. }
  9286. else {
  9287. _super.prototype.attrKV.call(this, key, props[key]);
  9288. }
  9289. }
  9290. if (!this.style) {
  9291. this.useStyle({});
  9292. }
  9293. };
  9294. Displayable.prototype.beforeBrush = function () { };
  9295. Displayable.prototype.afterBrush = function () { };
  9296. Displayable.prototype.innerBeforeBrush = function () { };
  9297. Displayable.prototype.innerAfterBrush = function () { };
  9298. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  9299. var m = this.transform;
  9300. if (this.ignore
  9301. || this.invisible
  9302. || this.style.opacity === 0
  9303. || (this.culling
  9304. && isDisplayableCulled(this, viewWidth, viewHeight))
  9305. || (m && !m[0] && !m[3])) {
  9306. return false;
  9307. }
  9308. if (considerClipPath && this.__clipPaths) {
  9309. for (var i = 0; i < this.__clipPaths.length; ++i) {
  9310. if (this.__clipPaths[i].isZeroArea()) {
  9311. return false;
  9312. }
  9313. }
  9314. }
  9315. if (considerAncestors && this.parent) {
  9316. var parent_1 = this.parent;
  9317. while (parent_1) {
  9318. if (parent_1.ignore) {
  9319. return false;
  9320. }
  9321. parent_1 = parent_1.parent;
  9322. }
  9323. }
  9324. return true;
  9325. };
  9326. Displayable.prototype.contain = function (x, y) {
  9327. return this.rectContain(x, y);
  9328. };
  9329. Displayable.prototype.traverse = function (cb, context) {
  9330. cb.call(context, this);
  9331. };
  9332. Displayable.prototype.rectContain = function (x, y) {
  9333. var coord = this.transformCoordToLocal(x, y);
  9334. var rect = this.getBoundingRect();
  9335. return rect.contain(coord[0], coord[1]);
  9336. };
  9337. Displayable.prototype.getPaintRect = function () {
  9338. var rect = this._paintRect;
  9339. if (!this._paintRect || this.__dirty) {
  9340. var transform = this.transform;
  9341. var elRect = this.getBoundingRect();
  9342. var style = this.style;
  9343. var shadowSize = style.shadowBlur || 0;
  9344. var shadowOffsetX = style.shadowOffsetX || 0;
  9345. var shadowOffsetY = style.shadowOffsetY || 0;
  9346. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  9347. if (transform) {
  9348. BoundingRect.applyTransform(rect, elRect, transform);
  9349. }
  9350. else {
  9351. rect.copy(elRect);
  9352. }
  9353. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  9354. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  9355. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  9356. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  9357. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  9358. }
  9359. var tolerance = this.dirtyRectTolerance;
  9360. if (!rect.isZero()) {
  9361. rect.x = Math.floor(rect.x - tolerance);
  9362. rect.y = Math.floor(rect.y - tolerance);
  9363. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  9364. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  9365. }
  9366. }
  9367. return rect;
  9368. };
  9369. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  9370. if (paintRect) {
  9371. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  9372. this._prevPaintRect.copy(paintRect);
  9373. }
  9374. else {
  9375. this._prevPaintRect = null;
  9376. }
  9377. };
  9378. Displayable.prototype.getPrevPaintRect = function () {
  9379. return this._prevPaintRect;
  9380. };
  9381. Displayable.prototype.animateStyle = function (loop) {
  9382. return this.animate('style', loop);
  9383. };
  9384. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  9385. if (targetKey === 'style') {
  9386. this.dirtyStyle();
  9387. }
  9388. else {
  9389. this.markRedraw();
  9390. }
  9391. };
  9392. Displayable.prototype.attrKV = function (key, value) {
  9393. if (key !== 'style') {
  9394. _super.prototype.attrKV.call(this, key, value);
  9395. }
  9396. else {
  9397. if (!this.style) {
  9398. this.useStyle(value);
  9399. }
  9400. else {
  9401. this.setStyle(value);
  9402. }
  9403. }
  9404. };
  9405. Displayable.prototype.setStyle = function (keyOrObj, value) {
  9406. if (typeof keyOrObj === 'string') {
  9407. this.style[keyOrObj] = value;
  9408. }
  9409. else {
  9410. extend(this.style, keyOrObj);
  9411. }
  9412. this.dirtyStyle();
  9413. return this;
  9414. };
  9415. Displayable.prototype.dirtyStyle = function (notRedraw) {
  9416. if (!notRedraw) {
  9417. this.markRedraw();
  9418. }
  9419. this.__dirty |= STYLE_CHANGED_BIT;
  9420. if (this._rect) {
  9421. this._rect = null;
  9422. }
  9423. };
  9424. Displayable.prototype.dirty = function () {
  9425. this.dirtyStyle();
  9426. };
  9427. Displayable.prototype.styleChanged = function () {
  9428. return !!(this.__dirty & STYLE_CHANGED_BIT);
  9429. };
  9430. Displayable.prototype.styleUpdated = function () {
  9431. this.__dirty &= ~STYLE_CHANGED_BIT;
  9432. };
  9433. Displayable.prototype.createStyle = function (obj) {
  9434. return createObject(DEFAULT_COMMON_STYLE, obj);
  9435. };
  9436. Displayable.prototype.useStyle = function (obj) {
  9437. if (!obj[STYLE_MAGIC_KEY]) {
  9438. obj = this.createStyle(obj);
  9439. }
  9440. if (this.__inHover) {
  9441. this.__hoverStyle = obj;
  9442. }
  9443. else {
  9444. this.style = obj;
  9445. }
  9446. this.dirtyStyle();
  9447. };
  9448. Displayable.prototype.isStyleObject = function (obj) {
  9449. return obj[STYLE_MAGIC_KEY];
  9450. };
  9451. Displayable.prototype._innerSaveToNormal = function (toState) {
  9452. _super.prototype._innerSaveToNormal.call(this, toState);
  9453. var normalState = this._normalState;
  9454. if (toState.style && !normalState.style) {
  9455. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  9456. }
  9457. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  9458. };
  9459. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  9460. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  9461. var needsRestoreToNormal = !(state && keepCurrentStates);
  9462. var targetStyle;
  9463. if (state && state.style) {
  9464. if (transition) {
  9465. if (keepCurrentStates) {
  9466. targetStyle = state.style;
  9467. }
  9468. else {
  9469. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  9470. this._mergeStyle(targetStyle, state.style);
  9471. }
  9472. }
  9473. else {
  9474. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  9475. this._mergeStyle(targetStyle, state.style);
  9476. }
  9477. }
  9478. else if (needsRestoreToNormal) {
  9479. targetStyle = normalState.style;
  9480. }
  9481. if (targetStyle) {
  9482. if (transition) {
  9483. var sourceStyle = this.style;
  9484. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  9485. if (needsRestoreToNormal) {
  9486. var changedKeys = keys(sourceStyle);
  9487. for (var i = 0; i < changedKeys.length; i++) {
  9488. var key = changedKeys[i];
  9489. if (key in targetStyle) {
  9490. targetStyle[key] = targetStyle[key];
  9491. this.style[key] = sourceStyle[key];
  9492. }
  9493. }
  9494. }
  9495. var targetKeys = keys(targetStyle);
  9496. for (var i = 0; i < targetKeys.length; i++) {
  9497. var key = targetKeys[i];
  9498. this.style[key] = this.style[key];
  9499. }
  9500. this._transitionState(stateName, {
  9501. style: targetStyle
  9502. }, animationCfg, this.getAnimationStyleProps());
  9503. }
  9504. else {
  9505. this.useStyle(targetStyle);
  9506. }
  9507. }
  9508. var statesKeys = this.__inHover ? PRIMARY_STATES_KEYS_IN_HOVER_LAYER : PRIMARY_STATES_KEYS$1;
  9509. for (var i = 0; i < statesKeys.length; i++) {
  9510. var key = statesKeys[i];
  9511. if (state && state[key] != null) {
  9512. this[key] = state[key];
  9513. }
  9514. else if (needsRestoreToNormal) {
  9515. if (normalState[key] != null) {
  9516. this[key] = normalState[key];
  9517. }
  9518. }
  9519. }
  9520. };
  9521. Displayable.prototype._mergeStates = function (states) {
  9522. var mergedState = _super.prototype._mergeStates.call(this, states);
  9523. var mergedStyle;
  9524. for (var i = 0; i < states.length; i++) {
  9525. var state = states[i];
  9526. if (state.style) {
  9527. mergedStyle = mergedStyle || {};
  9528. this._mergeStyle(mergedStyle, state.style);
  9529. }
  9530. }
  9531. if (mergedStyle) {
  9532. mergedState.style = mergedStyle;
  9533. }
  9534. return mergedState;
  9535. };
  9536. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  9537. extend(targetStyle, sourceStyle);
  9538. return targetStyle;
  9539. };
  9540. Displayable.prototype.getAnimationStyleProps = function () {
  9541. return DEFAULT_COMMON_ANIMATION_PROPS;
  9542. };
  9543. Displayable.initDefaultProps = (function () {
  9544. var dispProto = Displayable.prototype;
  9545. dispProto.type = 'displayable';
  9546. dispProto.invisible = false;
  9547. dispProto.z = 0;
  9548. dispProto.z2 = 0;
  9549. dispProto.zlevel = 0;
  9550. dispProto.culling = false;
  9551. dispProto.cursor = 'pointer';
  9552. dispProto.rectHover = false;
  9553. dispProto.incremental = false;
  9554. dispProto._rect = null;
  9555. dispProto.dirtyRectTolerance = 0;
  9556. dispProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT;
  9557. })();
  9558. return Displayable;
  9559. }(Element));
  9560. var tmpRect$1 = new BoundingRect(0, 0, 0, 0);
  9561. var viewRect = new BoundingRect(0, 0, 0, 0);
  9562. function isDisplayableCulled(el, width, height) {
  9563. tmpRect$1.copy(el.getBoundingRect());
  9564. if (el.transform) {
  9565. tmpRect$1.applyTransform(el.transform);
  9566. }
  9567. viewRect.width = width;
  9568. viewRect.height = height;
  9569. return !tmpRect$1.intersect(viewRect);
  9570. }
  9571. var mathMin$1 = Math.min;
  9572. var mathMax$1 = Math.max;
  9573. var mathSin = Math.sin;
  9574. var mathCos = Math.cos;
  9575. var PI2 = Math.PI * 2;
  9576. var start = create();
  9577. var end = create();
  9578. var extremity = create();
  9579. function fromPoints(points, min, max) {
  9580. if (points.length === 0) {
  9581. return;
  9582. }
  9583. var p = points[0];
  9584. var left = p[0];
  9585. var right = p[0];
  9586. var top = p[1];
  9587. var bottom = p[1];
  9588. for (var i = 1; i < points.length; i++) {
  9589. p = points[i];
  9590. left = mathMin$1(left, p[0]);
  9591. right = mathMax$1(right, p[0]);
  9592. top = mathMin$1(top, p[1]);
  9593. bottom = mathMax$1(bottom, p[1]);
  9594. }
  9595. min[0] = left;
  9596. min[1] = top;
  9597. max[0] = right;
  9598. max[1] = bottom;
  9599. }
  9600. function fromLine(x0, y0, x1, y1, min, max) {
  9601. min[0] = mathMin$1(x0, x1);
  9602. min[1] = mathMin$1(y0, y1);
  9603. max[0] = mathMax$1(x0, x1);
  9604. max[1] = mathMax$1(y0, y1);
  9605. }
  9606. var xDim = [];
  9607. var yDim = [];
  9608. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9609. var cubicExtrema$1 = cubicExtrema;
  9610. var cubicAt$1 = cubicAt;
  9611. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9612. min[0] = Infinity;
  9613. min[1] = Infinity;
  9614. max[0] = -Infinity;
  9615. max[1] = -Infinity;
  9616. for (var i = 0; i < n; i++) {
  9617. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9618. min[0] = mathMin$1(x, min[0]);
  9619. max[0] = mathMax$1(x, max[0]);
  9620. }
  9621. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9622. for (var i = 0; i < n; i++) {
  9623. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9624. min[1] = mathMin$1(y, min[1]);
  9625. max[1] = mathMax$1(y, max[1]);
  9626. }
  9627. min[0] = mathMin$1(x0, min[0]);
  9628. max[0] = mathMax$1(x0, max[0]);
  9629. min[0] = mathMin$1(x3, min[0]);
  9630. max[0] = mathMax$1(x3, max[0]);
  9631. min[1] = mathMin$1(y0, min[1]);
  9632. max[1] = mathMax$1(y0, max[1]);
  9633. min[1] = mathMin$1(y3, min[1]);
  9634. max[1] = mathMax$1(y3, max[1]);
  9635. }
  9636. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9637. var quadraticExtremum$1 = quadraticExtremum;
  9638. var quadraticAt$1 = quadraticAt;
  9639. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9640. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9641. var x = quadraticAt$1(x0, x1, x2, tx);
  9642. var y = quadraticAt$1(y0, y1, y2, ty);
  9643. min[0] = mathMin$1(x0, x2, x);
  9644. min[1] = mathMin$1(y0, y2, y);
  9645. max[0] = mathMax$1(x0, x2, x);
  9646. max[1] = mathMax$1(y0, y2, y);
  9647. }
  9648. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9649. var vec2Min = min;
  9650. var vec2Max = max;
  9651. var diff = Math.abs(startAngle - endAngle);
  9652. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9653. min$1[0] = x - rx;
  9654. min$1[1] = y - ry;
  9655. max$1[0] = x + rx;
  9656. max$1[1] = y + ry;
  9657. return;
  9658. }
  9659. start[0] = mathCos(startAngle) * rx + x;
  9660. start[1] = mathSin(startAngle) * ry + y;
  9661. end[0] = mathCos(endAngle) * rx + x;
  9662. end[1] = mathSin(endAngle) * ry + y;
  9663. vec2Min(min$1, start, end);
  9664. vec2Max(max$1, start, end);
  9665. startAngle = startAngle % (PI2);
  9666. if (startAngle < 0) {
  9667. startAngle = startAngle + PI2;
  9668. }
  9669. endAngle = endAngle % (PI2);
  9670. if (endAngle < 0) {
  9671. endAngle = endAngle + PI2;
  9672. }
  9673. if (startAngle > endAngle && !anticlockwise) {
  9674. endAngle += PI2;
  9675. }
  9676. else if (startAngle < endAngle && anticlockwise) {
  9677. startAngle += PI2;
  9678. }
  9679. if (anticlockwise) {
  9680. var tmp = endAngle;
  9681. endAngle = startAngle;
  9682. startAngle = tmp;
  9683. }
  9684. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9685. if (angle > startAngle) {
  9686. extremity[0] = mathCos(angle) * rx + x;
  9687. extremity[1] = mathSin(angle) * ry + y;
  9688. vec2Min(min$1, extremity, min$1);
  9689. vec2Max(max$1, extremity, max$1);
  9690. }
  9691. }
  9692. }
  9693. var CMD = {
  9694. M: 1,
  9695. L: 2,
  9696. C: 3,
  9697. Q: 4,
  9698. A: 5,
  9699. Z: 6,
  9700. R: 7
  9701. };
  9702. var tmpOutX = [];
  9703. var tmpOutY = [];
  9704. var min$1 = [];
  9705. var max$1 = [];
  9706. var min2 = [];
  9707. var max2 = [];
  9708. var mathMin$2 = Math.min;
  9709. var mathMax$2 = Math.max;
  9710. var mathCos$1 = Math.cos;
  9711. var mathSin$1 = Math.sin;
  9712. var mathAbs = Math.abs;
  9713. var PI = Math.PI;
  9714. var PI2$1 = PI * 2;
  9715. var hasTypedArray = typeof Float32Array !== 'undefined';
  9716. var tmpAngles = [];
  9717. function modPI2(radian) {
  9718. var n = Math.round(radian / PI * 1e8) / 1e8;
  9719. return (n % 2) * PI;
  9720. }
  9721. function normalizeArcAngles(angles, anticlockwise) {
  9722. var newStartAngle = modPI2(angles[0]);
  9723. if (newStartAngle < 0) {
  9724. newStartAngle += PI2$1;
  9725. }
  9726. var delta = newStartAngle - angles[0];
  9727. var newEndAngle = angles[1];
  9728. newEndAngle += delta;
  9729. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9730. newEndAngle = newStartAngle + PI2$1;
  9731. }
  9732. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9733. newEndAngle = newStartAngle - PI2$1;
  9734. }
  9735. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9736. newEndAngle = newStartAngle + (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9737. }
  9738. else if (anticlockwise && newStartAngle < newEndAngle) {
  9739. newEndAngle = newStartAngle - (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9740. }
  9741. angles[0] = newStartAngle;
  9742. angles[1] = newEndAngle;
  9743. }
  9744. var PathProxy = (function () {
  9745. function PathProxy(notSaveData) {
  9746. this.dpr = 1;
  9747. this._xi = 0;
  9748. this._yi = 0;
  9749. this._x0 = 0;
  9750. this._y0 = 0;
  9751. this._len = 0;
  9752. if (notSaveData) {
  9753. this._saveData = false;
  9754. }
  9755. if (this._saveData) {
  9756. this.data = [];
  9757. }
  9758. }
  9759. PathProxy.prototype.increaseVersion = function () {
  9760. this._version++;
  9761. };
  9762. PathProxy.prototype.getVersion = function () {
  9763. return this._version;
  9764. };
  9765. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9766. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9767. if (segmentIgnoreThreshold > 0) {
  9768. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9769. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9770. }
  9771. };
  9772. PathProxy.prototype.setDPR = function (dpr) {
  9773. this.dpr = dpr;
  9774. };
  9775. PathProxy.prototype.setContext = function (ctx) {
  9776. this._ctx = ctx;
  9777. };
  9778. PathProxy.prototype.getContext = function () {
  9779. return this._ctx;
  9780. };
  9781. PathProxy.prototype.beginPath = function () {
  9782. this._ctx && this._ctx.beginPath();
  9783. this.reset();
  9784. return this;
  9785. };
  9786. PathProxy.prototype.reset = function () {
  9787. if (this._saveData) {
  9788. this._len = 0;
  9789. }
  9790. if (this._pathSegLen) {
  9791. this._pathSegLen = null;
  9792. this._pathLen = 0;
  9793. }
  9794. this._version++;
  9795. };
  9796. PathProxy.prototype.moveTo = function (x, y) {
  9797. this._drawPendingPt();
  9798. this.addData(CMD.M, x, y);
  9799. this._ctx && this._ctx.moveTo(x, y);
  9800. this._x0 = x;
  9801. this._y0 = y;
  9802. this._xi = x;
  9803. this._yi = y;
  9804. return this;
  9805. };
  9806. PathProxy.prototype.lineTo = function (x, y) {
  9807. var dx = mathAbs(x - this._xi);
  9808. var dy = mathAbs(y - this._yi);
  9809. var exceedUnit = dx > this._ux || dy > this._uy;
  9810. this.addData(CMD.L, x, y);
  9811. if (this._ctx && exceedUnit) {
  9812. this._ctx.lineTo(x, y);
  9813. }
  9814. if (exceedUnit) {
  9815. this._xi = x;
  9816. this._yi = y;
  9817. this._pendingPtDist = 0;
  9818. }
  9819. else {
  9820. var d2 = dx * dx + dy * dy;
  9821. if (d2 > this._pendingPtDist) {
  9822. this._pendingPtX = x;
  9823. this._pendingPtY = y;
  9824. this._pendingPtDist = d2;
  9825. }
  9826. }
  9827. return this;
  9828. };
  9829. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9830. this._drawPendingPt();
  9831. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9832. if (this._ctx) {
  9833. this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9834. }
  9835. this._xi = x3;
  9836. this._yi = y3;
  9837. return this;
  9838. };
  9839. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9840. this._drawPendingPt();
  9841. this.addData(CMD.Q, x1, y1, x2, y2);
  9842. if (this._ctx) {
  9843. this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9844. }
  9845. this._xi = x2;
  9846. this._yi = y2;
  9847. return this;
  9848. };
  9849. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9850. this._drawPendingPt();
  9851. tmpAngles[0] = startAngle;
  9852. tmpAngles[1] = endAngle;
  9853. normalizeArcAngles(tmpAngles, anticlockwise);
  9854. startAngle = tmpAngles[0];
  9855. endAngle = tmpAngles[1];
  9856. var delta = endAngle - startAngle;
  9857. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9858. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9859. this._xi = mathCos$1(endAngle) * r + cx;
  9860. this._yi = mathSin$1(endAngle) * r + cy;
  9861. return this;
  9862. };
  9863. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9864. this._drawPendingPt();
  9865. if (this._ctx) {
  9866. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9867. }
  9868. return this;
  9869. };
  9870. PathProxy.prototype.rect = function (x, y, w, h) {
  9871. this._drawPendingPt();
  9872. this._ctx && this._ctx.rect(x, y, w, h);
  9873. this.addData(CMD.R, x, y, w, h);
  9874. return this;
  9875. };
  9876. PathProxy.prototype.closePath = function () {
  9877. this._drawPendingPt();
  9878. this.addData(CMD.Z);
  9879. var ctx = this._ctx;
  9880. var x0 = this._x0;
  9881. var y0 = this._y0;
  9882. if (ctx) {
  9883. ctx.closePath();
  9884. }
  9885. this._xi = x0;
  9886. this._yi = y0;
  9887. return this;
  9888. };
  9889. PathProxy.prototype.fill = function (ctx) {
  9890. ctx && ctx.fill();
  9891. this.toStatic();
  9892. };
  9893. PathProxy.prototype.stroke = function (ctx) {
  9894. ctx && ctx.stroke();
  9895. this.toStatic();
  9896. };
  9897. PathProxy.prototype.len = function () {
  9898. return this._len;
  9899. };
  9900. PathProxy.prototype.setData = function (data) {
  9901. var len = data.length;
  9902. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9903. this.data = new Float32Array(len);
  9904. }
  9905. for (var i = 0; i < len; i++) {
  9906. this.data[i] = data[i];
  9907. }
  9908. this._len = len;
  9909. };
  9910. PathProxy.prototype.appendPath = function (path) {
  9911. if (!(path instanceof Array)) {
  9912. path = [path];
  9913. }
  9914. var len = path.length;
  9915. var appendSize = 0;
  9916. var offset = this._len;
  9917. for (var i = 0; i < len; i++) {
  9918. appendSize += path[i].len();
  9919. }
  9920. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9921. this.data = new Float32Array(offset + appendSize);
  9922. }
  9923. for (var i = 0; i < len; i++) {
  9924. var appendPathData = path[i].data;
  9925. for (var k = 0; k < appendPathData.length; k++) {
  9926. this.data[offset++] = appendPathData[k];
  9927. }
  9928. }
  9929. this._len = offset;
  9930. };
  9931. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9932. if (!this._saveData) {
  9933. return;
  9934. }
  9935. var data = this.data;
  9936. if (this._len + arguments.length > data.length) {
  9937. this._expandData();
  9938. data = this.data;
  9939. }
  9940. for (var i = 0; i < arguments.length; i++) {
  9941. data[this._len++] = arguments[i];
  9942. }
  9943. };
  9944. PathProxy.prototype._drawPendingPt = function () {
  9945. if (this._pendingPtDist > 0) {
  9946. this._ctx && this._ctx.lineTo(this._pendingPtX, this._pendingPtY);
  9947. this._pendingPtDist = 0;
  9948. }
  9949. };
  9950. PathProxy.prototype._expandData = function () {
  9951. if (!(this.data instanceof Array)) {
  9952. var newData = [];
  9953. for (var i = 0; i < this._len; i++) {
  9954. newData[i] = this.data[i];
  9955. }
  9956. this.data = newData;
  9957. }
  9958. };
  9959. PathProxy.prototype.toStatic = function () {
  9960. if (!this._saveData) {
  9961. return;
  9962. }
  9963. this._drawPendingPt();
  9964. var data = this.data;
  9965. if (data instanceof Array) {
  9966. data.length = this._len;
  9967. if (hasTypedArray && this._len > 11) {
  9968. this.data = new Float32Array(data);
  9969. }
  9970. }
  9971. };
  9972. PathProxy.prototype.getBoundingRect = function () {
  9973. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9974. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9975. var data = this.data;
  9976. var xi = 0;
  9977. var yi = 0;
  9978. var x0 = 0;
  9979. var y0 = 0;
  9980. var i;
  9981. for (i = 0; i < this._len;) {
  9982. var cmd = data[i++];
  9983. var isFirst = i === 1;
  9984. if (isFirst) {
  9985. xi = data[i];
  9986. yi = data[i + 1];
  9987. x0 = xi;
  9988. y0 = yi;
  9989. }
  9990. switch (cmd) {
  9991. case CMD.M:
  9992. xi = x0 = data[i++];
  9993. yi = y0 = data[i++];
  9994. min2[0] = x0;
  9995. min2[1] = y0;
  9996. max2[0] = x0;
  9997. max2[1] = y0;
  9998. break;
  9999. case CMD.L:
  10000. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  10001. xi = data[i++];
  10002. yi = data[i++];
  10003. break;
  10004. case CMD.C:
  10005. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10006. xi = data[i++];
  10007. yi = data[i++];
  10008. break;
  10009. case CMD.Q:
  10010. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  10011. xi = data[i++];
  10012. yi = data[i++];
  10013. break;
  10014. case CMD.A:
  10015. var cx = data[i++];
  10016. var cy = data[i++];
  10017. var rx = data[i++];
  10018. var ry = data[i++];
  10019. var startAngle = data[i++];
  10020. var endAngle = data[i++] + startAngle;
  10021. i += 1;
  10022. var anticlockwise = !data[i++];
  10023. if (isFirst) {
  10024. x0 = mathCos$1(startAngle) * rx + cx;
  10025. y0 = mathSin$1(startAngle) * ry + cy;
  10026. }
  10027. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  10028. xi = mathCos$1(endAngle) * rx + cx;
  10029. yi = mathSin$1(endAngle) * ry + cy;
  10030. break;
  10031. case CMD.R:
  10032. x0 = xi = data[i++];
  10033. y0 = yi = data[i++];
  10034. var width = data[i++];
  10035. var height = data[i++];
  10036. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  10037. break;
  10038. case CMD.Z:
  10039. xi = x0;
  10040. yi = y0;
  10041. break;
  10042. }
  10043. min(min$1, min$1, min2);
  10044. max(max$1, max$1, max2);
  10045. }
  10046. if (i === 0) {
  10047. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  10048. }
  10049. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  10050. };
  10051. PathProxy.prototype._calculateLength = function () {
  10052. var data = this.data;
  10053. var len = this._len;
  10054. var ux = this._ux;
  10055. var uy = this._uy;
  10056. var xi = 0;
  10057. var yi = 0;
  10058. var x0 = 0;
  10059. var y0 = 0;
  10060. if (!this._pathSegLen) {
  10061. this._pathSegLen = [];
  10062. }
  10063. var pathSegLen = this._pathSegLen;
  10064. var pathTotalLen = 0;
  10065. var segCount = 0;
  10066. for (var i = 0; i < len;) {
  10067. var cmd = data[i++];
  10068. var isFirst = i === 1;
  10069. if (isFirst) {
  10070. xi = data[i];
  10071. yi = data[i + 1];
  10072. x0 = xi;
  10073. y0 = yi;
  10074. }
  10075. var l = -1;
  10076. switch (cmd) {
  10077. case CMD.M:
  10078. xi = x0 = data[i++];
  10079. yi = y0 = data[i++];
  10080. break;
  10081. case CMD.L: {
  10082. var x2 = data[i++];
  10083. var y2 = data[i++];
  10084. var dx = x2 - xi;
  10085. var dy = y2 - yi;
  10086. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  10087. l = Math.sqrt(dx * dx + dy * dy);
  10088. xi = x2;
  10089. yi = y2;
  10090. }
  10091. break;
  10092. }
  10093. case CMD.C: {
  10094. var x1 = data[i++];
  10095. var y1 = data[i++];
  10096. var x2 = data[i++];
  10097. var y2 = data[i++];
  10098. var x3 = data[i++];
  10099. var y3 = data[i++];
  10100. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  10101. xi = x3;
  10102. yi = y3;
  10103. break;
  10104. }
  10105. case CMD.Q: {
  10106. var x1 = data[i++];
  10107. var y1 = data[i++];
  10108. var x2 = data[i++];
  10109. var y2 = data[i++];
  10110. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  10111. xi = x2;
  10112. yi = y2;
  10113. break;
  10114. }
  10115. case CMD.A:
  10116. var cx = data[i++];
  10117. var cy = data[i++];
  10118. var rx = data[i++];
  10119. var ry = data[i++];
  10120. var startAngle = data[i++];
  10121. var delta = data[i++];
  10122. var endAngle = delta + startAngle;
  10123. i += 1;
  10124. var anticlockwise = !data[i++];
  10125. if (isFirst) {
  10126. x0 = mathCos$1(startAngle) * rx + cx;
  10127. y0 = mathSin$1(startAngle) * ry + cy;
  10128. }
  10129. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  10130. xi = mathCos$1(endAngle) * rx + cx;
  10131. yi = mathSin$1(endAngle) * ry + cy;
  10132. break;
  10133. case CMD.R: {
  10134. x0 = xi = data[i++];
  10135. y0 = yi = data[i++];
  10136. var width = data[i++];
  10137. var height = data[i++];
  10138. l = width * 2 + height * 2;
  10139. break;
  10140. }
  10141. case CMD.Z: {
  10142. var dx = x0 - xi;
  10143. var dy = y0 - yi;
  10144. l = Math.sqrt(dx * dx + dy * dy);
  10145. xi = x0;
  10146. yi = y0;
  10147. break;
  10148. }
  10149. }
  10150. if (l >= 0) {
  10151. pathSegLen[segCount++] = l;
  10152. pathTotalLen += l;
  10153. }
  10154. }
  10155. this._pathLen = pathTotalLen;
  10156. return pathTotalLen;
  10157. };
  10158. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  10159. var d = this.data;
  10160. var ux = this._ux;
  10161. var uy = this._uy;
  10162. var len = this._len;
  10163. var x0;
  10164. var y0;
  10165. var xi;
  10166. var yi;
  10167. var x;
  10168. var y;
  10169. var drawPart = percent < 1;
  10170. var pathSegLen;
  10171. var pathTotalLen;
  10172. var accumLength = 0;
  10173. var segCount = 0;
  10174. var displayedLength;
  10175. var pendingPtDist = 0;
  10176. var pendingPtX;
  10177. var pendingPtY;
  10178. if (drawPart) {
  10179. if (!this._pathSegLen) {
  10180. this._calculateLength();
  10181. }
  10182. pathSegLen = this._pathSegLen;
  10183. pathTotalLen = this._pathLen;
  10184. displayedLength = percent * pathTotalLen;
  10185. if (!displayedLength) {
  10186. return;
  10187. }
  10188. }
  10189. lo: for (var i = 0; i < len;) {
  10190. var cmd = d[i++];
  10191. var isFirst = i === 1;
  10192. if (isFirst) {
  10193. xi = d[i];
  10194. yi = d[i + 1];
  10195. x0 = xi;
  10196. y0 = yi;
  10197. }
  10198. if (cmd !== CMD.L && pendingPtDist > 0) {
  10199. ctx.lineTo(pendingPtX, pendingPtY);
  10200. pendingPtDist = 0;
  10201. }
  10202. switch (cmd) {
  10203. case CMD.M:
  10204. x0 = xi = d[i++];
  10205. y0 = yi = d[i++];
  10206. ctx.moveTo(xi, yi);
  10207. break;
  10208. case CMD.L: {
  10209. x = d[i++];
  10210. y = d[i++];
  10211. var dx = mathAbs(x - xi);
  10212. var dy = mathAbs(y - yi);
  10213. if (dx > ux || dy > uy) {
  10214. if (drawPart) {
  10215. var l = pathSegLen[segCount++];
  10216. if (accumLength + l > displayedLength) {
  10217. var t = (displayedLength - accumLength) / l;
  10218. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  10219. break lo;
  10220. }
  10221. accumLength += l;
  10222. }
  10223. ctx.lineTo(x, y);
  10224. xi = x;
  10225. yi = y;
  10226. pendingPtDist = 0;
  10227. }
  10228. else {
  10229. var d2 = dx * dx + dy * dy;
  10230. if (d2 > pendingPtDist) {
  10231. pendingPtX = x;
  10232. pendingPtY = y;
  10233. pendingPtDist = d2;
  10234. }
  10235. }
  10236. break;
  10237. }
  10238. case CMD.C: {
  10239. var x1 = d[i++];
  10240. var y1 = d[i++];
  10241. var x2 = d[i++];
  10242. var y2 = d[i++];
  10243. var x3 = d[i++];
  10244. var y3 = d[i++];
  10245. if (drawPart) {
  10246. var l = pathSegLen[segCount++];
  10247. if (accumLength + l > displayedLength) {
  10248. var t = (displayedLength - accumLength) / l;
  10249. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  10250. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  10251. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  10252. break lo;
  10253. }
  10254. accumLength += l;
  10255. }
  10256. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  10257. xi = x3;
  10258. yi = y3;
  10259. break;
  10260. }
  10261. case CMD.Q: {
  10262. var x1 = d[i++];
  10263. var y1 = d[i++];
  10264. var x2 = d[i++];
  10265. var y2 = d[i++];
  10266. if (drawPart) {
  10267. var l = pathSegLen[segCount++];
  10268. if (accumLength + l > displayedLength) {
  10269. var t = (displayedLength - accumLength) / l;
  10270. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  10271. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  10272. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  10273. break lo;
  10274. }
  10275. accumLength += l;
  10276. }
  10277. ctx.quadraticCurveTo(x1, y1, x2, y2);
  10278. xi = x2;
  10279. yi = y2;
  10280. break;
  10281. }
  10282. case CMD.A:
  10283. var cx = d[i++];
  10284. var cy = d[i++];
  10285. var rx = d[i++];
  10286. var ry = d[i++];
  10287. var startAngle = d[i++];
  10288. var delta = d[i++];
  10289. var psi = d[i++];
  10290. var anticlockwise = !d[i++];
  10291. var r = (rx > ry) ? rx : ry;
  10292. var isEllipse = mathAbs(rx - ry) > 1e-3;
  10293. var endAngle = startAngle + delta;
  10294. var breakBuild = false;
  10295. if (drawPart) {
  10296. var l = pathSegLen[segCount++];
  10297. if (accumLength + l > displayedLength) {
  10298. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  10299. breakBuild = true;
  10300. }
  10301. accumLength += l;
  10302. }
  10303. if (isEllipse && ctx.ellipse) {
  10304. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  10305. }
  10306. else {
  10307. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  10308. }
  10309. if (breakBuild) {
  10310. break lo;
  10311. }
  10312. if (isFirst) {
  10313. x0 = mathCos$1(startAngle) * rx + cx;
  10314. y0 = mathSin$1(startAngle) * ry + cy;
  10315. }
  10316. xi = mathCos$1(endAngle) * rx + cx;
  10317. yi = mathSin$1(endAngle) * ry + cy;
  10318. break;
  10319. case CMD.R:
  10320. x0 = xi = d[i];
  10321. y0 = yi = d[i + 1];
  10322. x = d[i++];
  10323. y = d[i++];
  10324. var width = d[i++];
  10325. var height = d[i++];
  10326. if (drawPart) {
  10327. var l = pathSegLen[segCount++];
  10328. if (accumLength + l > displayedLength) {
  10329. var d_1 = displayedLength - accumLength;
  10330. ctx.moveTo(x, y);
  10331. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10332. d_1 -= width;
  10333. if (d_1 > 0) {
  10334. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10335. }
  10336. d_1 -= height;
  10337. if (d_1 > 0) {
  10338. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10339. }
  10340. d_1 -= width;
  10341. if (d_1 > 0) {
  10342. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10343. }
  10344. break lo;
  10345. }
  10346. accumLength += l;
  10347. }
  10348. ctx.rect(x, y, width, height);
  10349. break;
  10350. case CMD.Z:
  10351. if (drawPart) {
  10352. var l = pathSegLen[segCount++];
  10353. if (accumLength + l > displayedLength) {
  10354. var t = (displayedLength - accumLength) / l;
  10355. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10356. break lo;
  10357. }
  10358. accumLength += l;
  10359. }
  10360. ctx.closePath();
  10361. xi = x0;
  10362. yi = y0;
  10363. }
  10364. }
  10365. };
  10366. PathProxy.prototype.clone = function () {
  10367. var newProxy = new PathProxy();
  10368. var data = this.data;
  10369. newProxy.data = data.slice ? data.slice()
  10370. : Array.prototype.slice.call(data);
  10371. newProxy._len = this._len;
  10372. return newProxy;
  10373. };
  10374. PathProxy.CMD = CMD;
  10375. PathProxy.initDefaultProps = (function () {
  10376. var proto = PathProxy.prototype;
  10377. proto._saveData = true;
  10378. proto._ux = 0;
  10379. proto._uy = 0;
  10380. proto._pendingPtDist = 0;
  10381. proto._version = 0;
  10382. })();
  10383. return PathProxy;
  10384. }());
  10385. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10386. if (lineWidth === 0) {
  10387. return false;
  10388. }
  10389. var _l = lineWidth;
  10390. var _a = 0;
  10391. var _b = x0;
  10392. if ((y > y0 + _l && y > y1 + _l)
  10393. || (y < y0 - _l && y < y1 - _l)
  10394. || (x > x0 + _l && x > x1 + _l)
  10395. || (x < x0 - _l && x < x1 - _l)) {
  10396. return false;
  10397. }
  10398. if (x0 !== x1) {
  10399. _a = (y0 - y1) / (x0 - x1);
  10400. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10401. }
  10402. else {
  10403. return Math.abs(x - x0) <= _l / 2;
  10404. }
  10405. var tmp = _a * x - y + _b;
  10406. var _s = tmp * tmp / (_a * _a + 1);
  10407. return _s <= _l / 2 * _l / 2;
  10408. }
  10409. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10410. if (lineWidth === 0) {
  10411. return false;
  10412. }
  10413. var _l = lineWidth;
  10414. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10415. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10416. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10417. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10418. return false;
  10419. }
  10420. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10421. return d <= _l / 2;
  10422. }
  10423. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10424. if (lineWidth === 0) {
  10425. return false;
  10426. }
  10427. var _l = lineWidth;
  10428. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10429. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10430. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10431. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10432. return false;
  10433. }
  10434. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10435. return d <= _l / 2;
  10436. }
  10437. var PI2$2 = Math.PI * 2;
  10438. function normalizeRadian(angle) {
  10439. angle %= PI2$2;
  10440. if (angle < 0) {
  10441. angle += PI2$2;
  10442. }
  10443. return angle;
  10444. }
  10445. var PI2$3 = Math.PI * 2;
  10446. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10447. if (lineWidth === 0) {
  10448. return false;
  10449. }
  10450. var _l = lineWidth;
  10451. x -= cx;
  10452. y -= cy;
  10453. var d = Math.sqrt(x * x + y * y);
  10454. if ((d - _l > r) || (d + _l < r)) {
  10455. return false;
  10456. }
  10457. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10458. return true;
  10459. }
  10460. if (anticlockwise) {
  10461. var tmp = startAngle;
  10462. startAngle = normalizeRadian(endAngle);
  10463. endAngle = normalizeRadian(tmp);
  10464. }
  10465. else {
  10466. startAngle = normalizeRadian(startAngle);
  10467. endAngle = normalizeRadian(endAngle);
  10468. }
  10469. if (startAngle > endAngle) {
  10470. endAngle += PI2$3;
  10471. }
  10472. var angle = Math.atan2(y, x);
  10473. if (angle < 0) {
  10474. angle += PI2$3;
  10475. }
  10476. return (angle >= startAngle && angle <= endAngle)
  10477. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10478. }
  10479. function windingLine(x0, y0, x1, y1, x, y) {
  10480. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10481. return 0;
  10482. }
  10483. if (y1 === y0) {
  10484. return 0;
  10485. }
  10486. var t = (y - y0) / (y1 - y0);
  10487. var dir = y1 < y0 ? 1 : -1;
  10488. if (t === 1 || t === 0) {
  10489. dir = y1 < y0 ? 0.5 : -0.5;
  10490. }
  10491. var x_ = t * (x1 - x0) + x0;
  10492. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10493. }
  10494. var CMD$1 = PathProxy.CMD;
  10495. var PI2$4 = Math.PI * 2;
  10496. var EPSILON$3 = 1e-4;
  10497. function isAroundEqual(a, b) {
  10498. return Math.abs(a - b) < EPSILON$3;
  10499. }
  10500. var roots = [-1, -1, -1];
  10501. var extrema = [-1, -1];
  10502. function swapExtrema() {
  10503. var tmp = extrema[0];
  10504. extrema[0] = extrema[1];
  10505. extrema[1] = tmp;
  10506. }
  10507. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10508. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10509. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10510. return 0;
  10511. }
  10512. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10513. if (nRoots === 0) {
  10514. return 0;
  10515. }
  10516. else {
  10517. var w = 0;
  10518. var nExtrema = -1;
  10519. var y0_ = void 0;
  10520. var y1_ = void 0;
  10521. for (var i = 0; i < nRoots; i++) {
  10522. var t = roots[i];
  10523. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10524. var x_ = cubicAt(x0, x1, x2, x3, t);
  10525. if (x_ < x) {
  10526. continue;
  10527. }
  10528. if (nExtrema < 0) {
  10529. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10530. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10531. swapExtrema();
  10532. }
  10533. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10534. if (nExtrema > 1) {
  10535. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10536. }
  10537. }
  10538. if (nExtrema === 2) {
  10539. if (t < extrema[0]) {
  10540. w += y0_ < y0 ? unit : -unit;
  10541. }
  10542. else if (t < extrema[1]) {
  10543. w += y1_ < y0_ ? unit : -unit;
  10544. }
  10545. else {
  10546. w += y3 < y1_ ? unit : -unit;
  10547. }
  10548. }
  10549. else {
  10550. if (t < extrema[0]) {
  10551. w += y0_ < y0 ? unit : -unit;
  10552. }
  10553. else {
  10554. w += y3 < y0_ ? unit : -unit;
  10555. }
  10556. }
  10557. }
  10558. return w;
  10559. }
  10560. }
  10561. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10562. if ((y > y0 && y > y1 && y > y2)
  10563. || (y < y0 && y < y1 && y < y2)) {
  10564. return 0;
  10565. }
  10566. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10567. if (nRoots === 0) {
  10568. return 0;
  10569. }
  10570. else {
  10571. var t = quadraticExtremum(y0, y1, y2);
  10572. if (t >= 0 && t <= 1) {
  10573. var w = 0;
  10574. var y_ = quadraticAt(y0, y1, y2, t);
  10575. for (var i = 0; i < nRoots; i++) {
  10576. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10577. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10578. if (x_ < x) {
  10579. continue;
  10580. }
  10581. if (roots[i] < t) {
  10582. w += y_ < y0 ? unit : -unit;
  10583. }
  10584. else {
  10585. w += y2 < y_ ? unit : -unit;
  10586. }
  10587. }
  10588. return w;
  10589. }
  10590. else {
  10591. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10592. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10593. if (x_ < x) {
  10594. return 0;
  10595. }
  10596. return y2 < y0 ? unit : -unit;
  10597. }
  10598. }
  10599. }
  10600. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10601. y -= cy;
  10602. if (y > r || y < -r) {
  10603. return 0;
  10604. }
  10605. var tmp = Math.sqrt(r * r - y * y);
  10606. roots[0] = -tmp;
  10607. roots[1] = tmp;
  10608. var dTheta = Math.abs(startAngle - endAngle);
  10609. if (dTheta < 1e-4) {
  10610. return 0;
  10611. }
  10612. if (dTheta >= PI2$4 - 1e-4) {
  10613. startAngle = 0;
  10614. endAngle = PI2$4;
  10615. var dir = anticlockwise ? 1 : -1;
  10616. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10617. return dir;
  10618. }
  10619. else {
  10620. return 0;
  10621. }
  10622. }
  10623. if (startAngle > endAngle) {
  10624. var tmp_1 = startAngle;
  10625. startAngle = endAngle;
  10626. endAngle = tmp_1;
  10627. }
  10628. if (startAngle < 0) {
  10629. startAngle += PI2$4;
  10630. endAngle += PI2$4;
  10631. }
  10632. var w = 0;
  10633. for (var i = 0; i < 2; i++) {
  10634. var x_ = roots[i];
  10635. if (x_ + cx > x) {
  10636. var angle = Math.atan2(y, x_);
  10637. var dir = anticlockwise ? 1 : -1;
  10638. if (angle < 0) {
  10639. angle = PI2$4 + angle;
  10640. }
  10641. if ((angle >= startAngle && angle <= endAngle)
  10642. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10643. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10644. dir = -dir;
  10645. }
  10646. w += dir;
  10647. }
  10648. }
  10649. }
  10650. return w;
  10651. }
  10652. function containPath(path, lineWidth, isStroke, x, y) {
  10653. var data = path.data;
  10654. var len = path.len();
  10655. var w = 0;
  10656. var xi = 0;
  10657. var yi = 0;
  10658. var x0 = 0;
  10659. var y0 = 0;
  10660. var x1;
  10661. var y1;
  10662. for (var i = 0; i < len;) {
  10663. var cmd = data[i++];
  10664. var isFirst = i === 1;
  10665. if (cmd === CMD$1.M && i > 1) {
  10666. if (!isStroke) {
  10667. w += windingLine(xi, yi, x0, y0, x, y);
  10668. }
  10669. }
  10670. if (isFirst) {
  10671. xi = data[i];
  10672. yi = data[i + 1];
  10673. x0 = xi;
  10674. y0 = yi;
  10675. }
  10676. switch (cmd) {
  10677. case CMD$1.M:
  10678. x0 = data[i++];
  10679. y0 = data[i++];
  10680. xi = x0;
  10681. yi = y0;
  10682. break;
  10683. case CMD$1.L:
  10684. if (isStroke) {
  10685. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10686. return true;
  10687. }
  10688. }
  10689. else {
  10690. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10691. }
  10692. xi = data[i++];
  10693. yi = data[i++];
  10694. break;
  10695. case CMD$1.C:
  10696. if (isStroke) {
  10697. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10698. return true;
  10699. }
  10700. }
  10701. else {
  10702. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10703. }
  10704. xi = data[i++];
  10705. yi = data[i++];
  10706. break;
  10707. case CMD$1.Q:
  10708. if (isStroke) {
  10709. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10710. return true;
  10711. }
  10712. }
  10713. else {
  10714. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10715. }
  10716. xi = data[i++];
  10717. yi = data[i++];
  10718. break;
  10719. case CMD$1.A:
  10720. var cx = data[i++];
  10721. var cy = data[i++];
  10722. var rx = data[i++];
  10723. var ry = data[i++];
  10724. var theta = data[i++];
  10725. var dTheta = data[i++];
  10726. i += 1;
  10727. var anticlockwise = !!(1 - data[i++]);
  10728. x1 = Math.cos(theta) * rx + cx;
  10729. y1 = Math.sin(theta) * ry + cy;
  10730. if (!isFirst) {
  10731. w += windingLine(xi, yi, x1, y1, x, y);
  10732. }
  10733. else {
  10734. x0 = x1;
  10735. y0 = y1;
  10736. }
  10737. var _x = (x - cx) * ry / rx + cx;
  10738. if (isStroke) {
  10739. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10740. return true;
  10741. }
  10742. }
  10743. else {
  10744. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10745. }
  10746. xi = Math.cos(theta + dTheta) * rx + cx;
  10747. yi = Math.sin(theta + dTheta) * ry + cy;
  10748. break;
  10749. case CMD$1.R:
  10750. x0 = xi = data[i++];
  10751. y0 = yi = data[i++];
  10752. var width = data[i++];
  10753. var height = data[i++];
  10754. x1 = x0 + width;
  10755. y1 = y0 + height;
  10756. if (isStroke) {
  10757. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10758. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10759. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10760. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10761. return true;
  10762. }
  10763. }
  10764. else {
  10765. w += windingLine(x1, y0, x1, y1, x, y);
  10766. w += windingLine(x0, y1, x0, y0, x, y);
  10767. }
  10768. break;
  10769. case CMD$1.Z:
  10770. if (isStroke) {
  10771. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10772. return true;
  10773. }
  10774. }
  10775. else {
  10776. w += windingLine(xi, yi, x0, y0, x, y);
  10777. }
  10778. xi = x0;
  10779. yi = y0;
  10780. break;
  10781. }
  10782. }
  10783. if (!isStroke && !isAroundEqual(yi, y0)) {
  10784. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10785. }
  10786. return w !== 0;
  10787. }
  10788. function contain(pathProxy, x, y) {
  10789. return containPath(pathProxy, 0, false, x, y);
  10790. }
  10791. function containStroke$4(pathProxy, lineWidth, x, y) {
  10792. return containPath(pathProxy, lineWidth, true, x, y);
  10793. }
  10794. var DEFAULT_PATH_STYLE = defaults({
  10795. fill: '#000',
  10796. stroke: null,
  10797. strokePercent: 1,
  10798. fillOpacity: 1,
  10799. strokeOpacity: 1,
  10800. lineDashOffset: 0,
  10801. lineWidth: 1,
  10802. lineCap: 'butt',
  10803. miterLimit: 10,
  10804. strokeNoScale: false,
  10805. strokeFirst: false
  10806. }, DEFAULT_COMMON_STYLE);
  10807. var DEFAULT_PATH_ANIMATION_PROPS = {
  10808. style: defaults({
  10809. fill: true,
  10810. stroke: true,
  10811. strokePercent: true,
  10812. fillOpacity: true,
  10813. strokeOpacity: true,
  10814. lineDashOffset: true,
  10815. lineWidth: true,
  10816. miterLimit: true
  10817. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10818. };
  10819. var pathCopyParams = TRANSFORMABLE_PROPS.concat(['invisible',
  10820. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10821. ]);
  10822. var Path = (function (_super) {
  10823. __extends(Path, _super);
  10824. function Path(opts) {
  10825. return _super.call(this, opts) || this;
  10826. }
  10827. Path.prototype.update = function () {
  10828. var _this = this;
  10829. _super.prototype.update.call(this);
  10830. var style = this.style;
  10831. if (style.decal) {
  10832. var decalEl = this._decalEl = this._decalEl || new Path();
  10833. if (decalEl.buildPath === Path.prototype.buildPath) {
  10834. decalEl.buildPath = function (ctx) {
  10835. _this.buildPath(ctx, _this.shape);
  10836. };
  10837. }
  10838. decalEl.silent = true;
  10839. var decalElStyle = decalEl.style;
  10840. for (var key in style) {
  10841. if (decalElStyle[key] !== style[key]) {
  10842. decalElStyle[key] = style[key];
  10843. }
  10844. }
  10845. decalElStyle.fill = style.fill ? style.decal : null;
  10846. decalElStyle.decal = null;
  10847. decalElStyle.shadowColor = null;
  10848. style.strokeFirst && (decalElStyle.stroke = null);
  10849. for (var i = 0; i < pathCopyParams.length; ++i) {
  10850. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10851. }
  10852. decalEl.__dirty |= REDRAW_BIT;
  10853. }
  10854. else if (this._decalEl) {
  10855. this._decalEl = null;
  10856. }
  10857. };
  10858. Path.prototype.getDecalElement = function () {
  10859. return this._decalEl;
  10860. };
  10861. Path.prototype._init = function (props) {
  10862. var keysArr = keys(props);
  10863. this.shape = this.getDefaultShape();
  10864. var defaultStyle = this.getDefaultStyle();
  10865. if (defaultStyle) {
  10866. this.useStyle(defaultStyle);
  10867. }
  10868. for (var i = 0; i < keysArr.length; i++) {
  10869. var key = keysArr[i];
  10870. var value = props[key];
  10871. if (key === 'style') {
  10872. if (!this.style) {
  10873. this.useStyle(value);
  10874. }
  10875. else {
  10876. extend(this.style, value);
  10877. }
  10878. }
  10879. else if (key === 'shape') {
  10880. extend(this.shape, value);
  10881. }
  10882. else {
  10883. _super.prototype.attrKV.call(this, key, value);
  10884. }
  10885. }
  10886. if (!this.style) {
  10887. this.useStyle({});
  10888. }
  10889. };
  10890. Path.prototype.getDefaultStyle = function () {
  10891. return null;
  10892. };
  10893. Path.prototype.getDefaultShape = function () {
  10894. return {};
  10895. };
  10896. Path.prototype.canBeInsideText = function () {
  10897. return this.hasFill();
  10898. };
  10899. Path.prototype.getInsideTextFill = function () {
  10900. var pathFill = this.style.fill;
  10901. if (pathFill !== 'none') {
  10902. if (isString(pathFill)) {
  10903. var fillLum = lum(pathFill, 0);
  10904. if (fillLum > 0.5) {
  10905. return DARK_LABEL_COLOR;
  10906. }
  10907. else if (fillLum > 0.2) {
  10908. return LIGHTER_LABEL_COLOR;
  10909. }
  10910. return LIGHT_LABEL_COLOR;
  10911. }
  10912. else if (pathFill) {
  10913. return LIGHT_LABEL_COLOR;
  10914. }
  10915. }
  10916. return DARK_LABEL_COLOR;
  10917. };
  10918. Path.prototype.getInsideTextStroke = function (textFill) {
  10919. var pathFill = this.style.fill;
  10920. if (isString(pathFill)) {
  10921. var zr = this.__zr;
  10922. var isDarkMode = !!(zr && zr.isDarkMode());
  10923. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10924. if (isDarkMode === isDarkLabel) {
  10925. return pathFill;
  10926. }
  10927. }
  10928. };
  10929. Path.prototype.buildPath = function (ctx, shapeCfg, inBatch) { };
  10930. Path.prototype.pathUpdated = function () {
  10931. this.__dirty &= ~SHAPE_CHANGED_BIT;
  10932. };
  10933. Path.prototype.getUpdatedPathProxy = function (inBatch) {
  10934. !this.path && this.createPathProxy();
  10935. this.path.beginPath();
  10936. this.buildPath(this.path, this.shape, inBatch);
  10937. return this.path;
  10938. };
  10939. Path.prototype.createPathProxy = function () {
  10940. this.path = new PathProxy(false);
  10941. };
  10942. Path.prototype.hasStroke = function () {
  10943. var style = this.style;
  10944. var stroke = style.stroke;
  10945. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10946. };
  10947. Path.prototype.hasFill = function () {
  10948. var style = this.style;
  10949. var fill = style.fill;
  10950. return fill != null && fill !== 'none';
  10951. };
  10952. Path.prototype.getBoundingRect = function () {
  10953. var rect = this._rect;
  10954. var style = this.style;
  10955. var needsUpdateRect = !rect;
  10956. if (needsUpdateRect) {
  10957. var firstInvoke = false;
  10958. if (!this.path) {
  10959. firstInvoke = true;
  10960. this.createPathProxy();
  10961. }
  10962. var path = this.path;
  10963. if (firstInvoke || (this.__dirty & SHAPE_CHANGED_BIT)) {
  10964. path.beginPath();
  10965. this.buildPath(path, this.shape, false);
  10966. this.pathUpdated();
  10967. }
  10968. rect = path.getBoundingRect();
  10969. }
  10970. this._rect = rect;
  10971. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10972. var rectStroke = this._rectStroke || (this._rectStroke = rect.clone());
  10973. if (this.__dirty || needsUpdateRect) {
  10974. rectStroke.copy(rect);
  10975. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10976. var w = style.lineWidth;
  10977. if (!this.hasFill()) {
  10978. var strokeContainThreshold = this.strokeContainThreshold;
  10979. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10980. }
  10981. if (lineScale > 1e-10) {
  10982. rectStroke.width += w / lineScale;
  10983. rectStroke.height += w / lineScale;
  10984. rectStroke.x -= w / lineScale / 2;
  10985. rectStroke.y -= w / lineScale / 2;
  10986. }
  10987. }
  10988. return rectStroke;
  10989. }
  10990. return rect;
  10991. };
  10992. Path.prototype.contain = function (x, y) {
  10993. var localPos = this.transformCoordToLocal(x, y);
  10994. var rect = this.getBoundingRect();
  10995. var style = this.style;
  10996. x = localPos[0];
  10997. y = localPos[1];
  10998. if (rect.contain(x, y)) {
  10999. var pathProxy = this.path;
  11000. if (this.hasStroke()) {
  11001. var lineWidth = style.lineWidth;
  11002. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  11003. if (lineScale > 1e-10) {
  11004. if (!this.hasFill()) {
  11005. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  11006. }
  11007. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  11008. return true;
  11009. }
  11010. }
  11011. }
  11012. if (this.hasFill()) {
  11013. return contain(pathProxy, x, y);
  11014. }
  11015. }
  11016. return false;
  11017. };
  11018. Path.prototype.dirtyShape = function () {
  11019. this.__dirty |= SHAPE_CHANGED_BIT;
  11020. if (this._rect) {
  11021. this._rect = null;
  11022. }
  11023. if (this._decalEl) {
  11024. this._decalEl.dirtyShape();
  11025. }
  11026. this.markRedraw();
  11027. };
  11028. Path.prototype.dirty = function () {
  11029. this.dirtyStyle();
  11030. this.dirtyShape();
  11031. };
  11032. Path.prototype.animateShape = function (loop) {
  11033. return this.animate('shape', loop);
  11034. };
  11035. Path.prototype.updateDuringAnimation = function (targetKey) {
  11036. if (targetKey === 'style') {
  11037. this.dirtyStyle();
  11038. }
  11039. else if (targetKey === 'shape') {
  11040. this.dirtyShape();
  11041. }
  11042. else {
  11043. this.markRedraw();
  11044. }
  11045. };
  11046. Path.prototype.attrKV = function (key, value) {
  11047. if (key === 'shape') {
  11048. this.setShape(value);
  11049. }
  11050. else {
  11051. _super.prototype.attrKV.call(this, key, value);
  11052. }
  11053. };
  11054. Path.prototype.setShape = function (keyOrObj, value) {
  11055. var shape = this.shape;
  11056. if (!shape) {
  11057. shape = this.shape = {};
  11058. }
  11059. if (typeof keyOrObj === 'string') {
  11060. shape[keyOrObj] = value;
  11061. }
  11062. else {
  11063. extend(shape, keyOrObj);
  11064. }
  11065. this.dirtyShape();
  11066. return this;
  11067. };
  11068. Path.prototype.shapeChanged = function () {
  11069. return !!(this.__dirty & SHAPE_CHANGED_BIT);
  11070. };
  11071. Path.prototype.createStyle = function (obj) {
  11072. return createObject(DEFAULT_PATH_STYLE, obj);
  11073. };
  11074. Path.prototype._innerSaveToNormal = function (toState) {
  11075. _super.prototype._innerSaveToNormal.call(this, toState);
  11076. var normalState = this._normalState;
  11077. if (toState.shape && !normalState.shape) {
  11078. normalState.shape = extend({}, this.shape);
  11079. }
  11080. };
  11081. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  11082. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  11083. var needsRestoreToNormal = !(state && keepCurrentStates);
  11084. var targetShape;
  11085. if (state && state.shape) {
  11086. if (transition) {
  11087. if (keepCurrentStates) {
  11088. targetShape = state.shape;
  11089. }
  11090. else {
  11091. targetShape = extend({}, normalState.shape);
  11092. extend(targetShape, state.shape);
  11093. }
  11094. }
  11095. else {
  11096. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  11097. extend(targetShape, state.shape);
  11098. }
  11099. }
  11100. else if (needsRestoreToNormal) {
  11101. targetShape = normalState.shape;
  11102. }
  11103. if (targetShape) {
  11104. if (transition) {
  11105. this.shape = extend({}, this.shape);
  11106. var targetShapePrimaryProps = {};
  11107. var shapeKeys = keys(targetShape);
  11108. for (var i = 0; i < shapeKeys.length; i++) {
  11109. var key = shapeKeys[i];
  11110. if (typeof targetShape[key] === 'object') {
  11111. this.shape[key] = targetShape[key];
  11112. }
  11113. else {
  11114. targetShapePrimaryProps[key] = targetShape[key];
  11115. }
  11116. }
  11117. this._transitionState(stateName, {
  11118. shape: targetShapePrimaryProps
  11119. }, animationCfg);
  11120. }
  11121. else {
  11122. this.shape = targetShape;
  11123. this.dirtyShape();
  11124. }
  11125. }
  11126. };
  11127. Path.prototype._mergeStates = function (states) {
  11128. var mergedState = _super.prototype._mergeStates.call(this, states);
  11129. var mergedShape;
  11130. for (var i = 0; i < states.length; i++) {
  11131. var state = states[i];
  11132. if (state.shape) {
  11133. mergedShape = mergedShape || {};
  11134. this._mergeStyle(mergedShape, state.shape);
  11135. }
  11136. }
  11137. if (mergedShape) {
  11138. mergedState.shape = mergedShape;
  11139. }
  11140. return mergedState;
  11141. };
  11142. Path.prototype.getAnimationStyleProps = function () {
  11143. return DEFAULT_PATH_ANIMATION_PROPS;
  11144. };
  11145. Path.prototype.isZeroArea = function () {
  11146. return false;
  11147. };
  11148. Path.extend = function (defaultProps) {
  11149. var Sub = (function (_super) {
  11150. __extends(Sub, _super);
  11151. function Sub(opts) {
  11152. var _this = _super.call(this, opts) || this;
  11153. defaultProps.init && defaultProps.init.call(_this, opts);
  11154. return _this;
  11155. }
  11156. Sub.prototype.getDefaultStyle = function () {
  11157. return clone(defaultProps.style);
  11158. };
  11159. Sub.prototype.getDefaultShape = function () {
  11160. return clone(defaultProps.shape);
  11161. };
  11162. return Sub;
  11163. }(Path));
  11164. for (var key in defaultProps) {
  11165. if (typeof defaultProps[key] === 'function') {
  11166. Sub.prototype[key] = defaultProps[key];
  11167. }
  11168. }
  11169. return Sub;
  11170. };
  11171. Path.initDefaultProps = (function () {
  11172. var pathProto = Path.prototype;
  11173. pathProto.type = 'path';
  11174. pathProto.strokeContainThreshold = 5;
  11175. pathProto.segmentIgnoreThreshold = 0;
  11176. pathProto.subPixelOptimize = false;
  11177. pathProto.autoBatch = false;
  11178. pathProto.__dirty = REDRAW_BIT | STYLE_CHANGED_BIT | SHAPE_CHANGED_BIT;
  11179. })();
  11180. return Path;
  11181. }(Displayable));
  11182. var DEFAULT_TSPAN_STYLE = defaults({
  11183. strokeFirst: true,
  11184. font: DEFAULT_FONT,
  11185. x: 0,
  11186. y: 0,
  11187. textAlign: 'left',
  11188. textBaseline: 'top',
  11189. miterLimit: 2
  11190. }, DEFAULT_PATH_STYLE);
  11191. var TSpan = (function (_super) {
  11192. __extends(TSpan, _super);
  11193. function TSpan() {
  11194. return _super !== null && _super.apply(this, arguments) || this;
  11195. }
  11196. TSpan.prototype.hasStroke = function () {
  11197. var style = this.style;
  11198. var stroke = style.stroke;
  11199. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  11200. };
  11201. TSpan.prototype.hasFill = function () {
  11202. var style = this.style;
  11203. var fill = style.fill;
  11204. return fill != null && fill !== 'none';
  11205. };
  11206. TSpan.prototype.createStyle = function (obj) {
  11207. return createObject(DEFAULT_TSPAN_STYLE, obj);
  11208. };
  11209. TSpan.prototype.setBoundingRect = function (rect) {
  11210. this._rect = rect;
  11211. };
  11212. TSpan.prototype.getBoundingRect = function () {
  11213. var style = this.style;
  11214. if (!this._rect) {
  11215. var text = style.text;
  11216. text != null ? (text += '') : (text = '');
  11217. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  11218. rect.x += style.x || 0;
  11219. rect.y += style.y || 0;
  11220. if (this.hasStroke()) {
  11221. var w = style.lineWidth;
  11222. rect.x -= w / 2;
  11223. rect.y -= w / 2;
  11224. rect.width += w;
  11225. rect.height += w;
  11226. }
  11227. this._rect = rect;
  11228. }
  11229. return this._rect;
  11230. };
  11231. TSpan.initDefaultProps = (function () {
  11232. var tspanProto = TSpan.prototype;
  11233. tspanProto.dirtyRectTolerance = 10;
  11234. })();
  11235. return TSpan;
  11236. }(Displayable));
  11237. TSpan.prototype.type = 'tspan';
  11238. var DEFAULT_IMAGE_STYLE = defaults({
  11239. x: 0,
  11240. y: 0
  11241. }, DEFAULT_COMMON_STYLE);
  11242. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  11243. style: defaults({
  11244. x: true,
  11245. y: true,
  11246. width: true,
  11247. height: true,
  11248. sx: true,
  11249. sy: true,
  11250. sWidth: true,
  11251. sHeight: true
  11252. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11253. };
  11254. function isImageLike(source) {
  11255. return !!(source
  11256. && typeof source !== 'string'
  11257. && source.width && source.height);
  11258. }
  11259. var ZRImage = (function (_super) {
  11260. __extends(ZRImage, _super);
  11261. function ZRImage() {
  11262. return _super !== null && _super.apply(this, arguments) || this;
  11263. }
  11264. ZRImage.prototype.createStyle = function (obj) {
  11265. return createObject(DEFAULT_IMAGE_STYLE, obj);
  11266. };
  11267. ZRImage.prototype._getSize = function (dim) {
  11268. var style = this.style;
  11269. var size = style[dim];
  11270. if (size != null) {
  11271. return size;
  11272. }
  11273. var imageSource = isImageLike(style.image)
  11274. ? style.image : this.__image;
  11275. if (!imageSource) {
  11276. return 0;
  11277. }
  11278. var otherDim = dim === 'width' ? 'height' : 'width';
  11279. var otherDimSize = style[otherDim];
  11280. if (otherDimSize == null) {
  11281. return imageSource[dim];
  11282. }
  11283. else {
  11284. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  11285. }
  11286. };
  11287. ZRImage.prototype.getWidth = function () {
  11288. return this._getSize('width');
  11289. };
  11290. ZRImage.prototype.getHeight = function () {
  11291. return this._getSize('height');
  11292. };
  11293. ZRImage.prototype.getAnimationStyleProps = function () {
  11294. return DEFAULT_IMAGE_ANIMATION_PROPS;
  11295. };
  11296. ZRImage.prototype.getBoundingRect = function () {
  11297. var style = this.style;
  11298. if (!this._rect) {
  11299. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  11300. }
  11301. return this._rect;
  11302. };
  11303. return ZRImage;
  11304. }(Displayable));
  11305. ZRImage.prototype.type = 'image';
  11306. function buildPath(ctx, shape) {
  11307. var x = shape.x;
  11308. var y = shape.y;
  11309. var width = shape.width;
  11310. var height = shape.height;
  11311. var r = shape.r;
  11312. var r1;
  11313. var r2;
  11314. var r3;
  11315. var r4;
  11316. if (width < 0) {
  11317. x = x + width;
  11318. width = -width;
  11319. }
  11320. if (height < 0) {
  11321. y = y + height;
  11322. height = -height;
  11323. }
  11324. if (typeof r === 'number') {
  11325. r1 = r2 = r3 = r4 = r;
  11326. }
  11327. else if (r instanceof Array) {
  11328. if (r.length === 1) {
  11329. r1 = r2 = r3 = r4 = r[0];
  11330. }
  11331. else if (r.length === 2) {
  11332. r1 = r3 = r[0];
  11333. r2 = r4 = r[1];
  11334. }
  11335. else if (r.length === 3) {
  11336. r1 = r[0];
  11337. r2 = r4 = r[1];
  11338. r3 = r[2];
  11339. }
  11340. else {
  11341. r1 = r[0];
  11342. r2 = r[1];
  11343. r3 = r[2];
  11344. r4 = r[3];
  11345. }
  11346. }
  11347. else {
  11348. r1 = r2 = r3 = r4 = 0;
  11349. }
  11350. var total;
  11351. if (r1 + r2 > width) {
  11352. total = r1 + r2;
  11353. r1 *= width / total;
  11354. r2 *= width / total;
  11355. }
  11356. if (r3 + r4 > width) {
  11357. total = r3 + r4;
  11358. r3 *= width / total;
  11359. r4 *= width / total;
  11360. }
  11361. if (r2 + r3 > height) {
  11362. total = r2 + r3;
  11363. r2 *= height / total;
  11364. r3 *= height / total;
  11365. }
  11366. if (r1 + r4 > height) {
  11367. total = r1 + r4;
  11368. r1 *= height / total;
  11369. r4 *= height / total;
  11370. }
  11371. ctx.moveTo(x + r1, y);
  11372. ctx.lineTo(x + width - r2, y);
  11373. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11374. ctx.lineTo(x + width, y + height - r3);
  11375. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11376. ctx.lineTo(x + r4, y + height);
  11377. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11378. ctx.lineTo(x, y + r1);
  11379. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11380. }
  11381. var round$1 = Math.round;
  11382. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11383. if (!inputShape) {
  11384. return;
  11385. }
  11386. var x1 = inputShape.x1;
  11387. var x2 = inputShape.x2;
  11388. var y1 = inputShape.y1;
  11389. var y2 = inputShape.y2;
  11390. outputShape.x1 = x1;
  11391. outputShape.x2 = x2;
  11392. outputShape.y1 = y1;
  11393. outputShape.y2 = y2;
  11394. var lineWidth = style && style.lineWidth;
  11395. if (!lineWidth) {
  11396. return outputShape;
  11397. }
  11398. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11399. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11400. }
  11401. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11402. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11403. }
  11404. return outputShape;
  11405. }
  11406. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11407. if (!inputShape) {
  11408. return;
  11409. }
  11410. var originX = inputShape.x;
  11411. var originY = inputShape.y;
  11412. var originWidth = inputShape.width;
  11413. var originHeight = inputShape.height;
  11414. outputShape.x = originX;
  11415. outputShape.y = originY;
  11416. outputShape.width = originWidth;
  11417. outputShape.height = originHeight;
  11418. var lineWidth = style && style.lineWidth;
  11419. if (!lineWidth) {
  11420. return outputShape;
  11421. }
  11422. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11423. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11424. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11425. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11426. return outputShape;
  11427. }
  11428. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11429. if (!lineWidth) {
  11430. return position;
  11431. }
  11432. var doubledPosition = round$1(position * 2);
  11433. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11434. ? doubledPosition / 2
  11435. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11436. }
  11437. var RectShape = (function () {
  11438. function RectShape() {
  11439. this.x = 0;
  11440. this.y = 0;
  11441. this.width = 0;
  11442. this.height = 0;
  11443. }
  11444. return RectShape;
  11445. }());
  11446. var subPixelOptimizeOutputShape = {};
  11447. var Rect = (function (_super) {
  11448. __extends(Rect, _super);
  11449. function Rect(opts) {
  11450. return _super.call(this, opts) || this;
  11451. }
  11452. Rect.prototype.getDefaultShape = function () {
  11453. return new RectShape();
  11454. };
  11455. Rect.prototype.buildPath = function (ctx, shape) {
  11456. var x;
  11457. var y;
  11458. var width;
  11459. var height;
  11460. if (this.subPixelOptimize) {
  11461. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11462. x = optimizedShape.x;
  11463. y = optimizedShape.y;
  11464. width = optimizedShape.width;
  11465. height = optimizedShape.height;
  11466. optimizedShape.r = shape.r;
  11467. shape = optimizedShape;
  11468. }
  11469. else {
  11470. x = shape.x;
  11471. y = shape.y;
  11472. width = shape.width;
  11473. height = shape.height;
  11474. }
  11475. if (!shape.r) {
  11476. ctx.rect(x, y, width, height);
  11477. }
  11478. else {
  11479. buildPath(ctx, shape);
  11480. }
  11481. };
  11482. Rect.prototype.isZeroArea = function () {
  11483. return !this.shape.width || !this.shape.height;
  11484. };
  11485. return Rect;
  11486. }(Path));
  11487. Rect.prototype.type = 'rect';
  11488. var DEFAULT_RICH_TEXT_COLOR = {
  11489. fill: '#000'
  11490. };
  11491. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11492. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11493. style: defaults({
  11494. fill: true,
  11495. stroke: true,
  11496. fillOpacity: true,
  11497. strokeOpacity: true,
  11498. lineWidth: true,
  11499. fontSize: true,
  11500. lineHeight: true,
  11501. width: true,
  11502. height: true,
  11503. textShadowColor: true,
  11504. textShadowBlur: true,
  11505. textShadowOffsetX: true,
  11506. textShadowOffsetY: true,
  11507. backgroundColor: true,
  11508. padding: true,
  11509. borderColor: true,
  11510. borderWidth: true,
  11511. borderRadius: true
  11512. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11513. };
  11514. var ZRText = (function (_super) {
  11515. __extends(ZRText, _super);
  11516. function ZRText(opts) {
  11517. var _this = _super.call(this) || this;
  11518. _this.type = 'text';
  11519. _this._children = [];
  11520. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11521. _this.attr(opts);
  11522. return _this;
  11523. }
  11524. ZRText.prototype.childrenRef = function () {
  11525. return this._children;
  11526. };
  11527. ZRText.prototype.update = function () {
  11528. _super.prototype.update.call(this);
  11529. if (this.styleChanged()) {
  11530. this._updateSubTexts();
  11531. }
  11532. for (var i = 0; i < this._children.length; i++) {
  11533. var child = this._children[i];
  11534. child.zlevel = this.zlevel;
  11535. child.z = this.z;
  11536. child.z2 = this.z2;
  11537. child.culling = this.culling;
  11538. child.cursor = this.cursor;
  11539. child.invisible = this.invisible;
  11540. }
  11541. };
  11542. ZRText.prototype.updateTransform = function () {
  11543. var innerTransformable = this.innerTransformable;
  11544. if (innerTransformable) {
  11545. innerTransformable.updateTransform();
  11546. if (innerTransformable.transform) {
  11547. this.transform = innerTransformable.transform;
  11548. }
  11549. }
  11550. else {
  11551. _super.prototype.updateTransform.call(this);
  11552. }
  11553. };
  11554. ZRText.prototype.getLocalTransform = function (m) {
  11555. var innerTransformable = this.innerTransformable;
  11556. return innerTransformable
  11557. ? innerTransformable.getLocalTransform(m)
  11558. : _super.prototype.getLocalTransform.call(this, m);
  11559. };
  11560. ZRText.prototype.getComputedTransform = function () {
  11561. if (this.__hostTarget) {
  11562. this.__hostTarget.getComputedTransform();
  11563. this.__hostTarget.updateInnerText(true);
  11564. }
  11565. return _super.prototype.getComputedTransform.call(this);
  11566. };
  11567. ZRText.prototype._updateSubTexts = function () {
  11568. this._childCursor = 0;
  11569. normalizeTextStyle(this.style);
  11570. this.style.rich
  11571. ? this._updateRichTexts()
  11572. : this._updatePlainTexts();
  11573. this._children.length = this._childCursor;
  11574. this.styleUpdated();
  11575. };
  11576. ZRText.prototype.addSelfToZr = function (zr) {
  11577. _super.prototype.addSelfToZr.call(this, zr);
  11578. for (var i = 0; i < this._children.length; i++) {
  11579. this._children[i].__zr = zr;
  11580. }
  11581. };
  11582. ZRText.prototype.removeSelfFromZr = function (zr) {
  11583. _super.prototype.removeSelfFromZr.call(this, zr);
  11584. for (var i = 0; i < this._children.length; i++) {
  11585. this._children[i].__zr = null;
  11586. }
  11587. };
  11588. ZRText.prototype.getBoundingRect = function () {
  11589. if (this.styleChanged()) {
  11590. this._updateSubTexts();
  11591. }
  11592. if (!this._rect) {
  11593. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11594. var children = this._children;
  11595. var tmpMat = [];
  11596. var rect = null;
  11597. for (var i = 0; i < children.length; i++) {
  11598. var child = children[i];
  11599. var childRect = child.getBoundingRect();
  11600. var transform = child.getLocalTransform(tmpMat);
  11601. if (transform) {
  11602. tmpRect.copy(childRect);
  11603. tmpRect.applyTransform(transform);
  11604. rect = rect || tmpRect.clone();
  11605. rect.union(tmpRect);
  11606. }
  11607. else {
  11608. rect = rect || childRect.clone();
  11609. rect.union(childRect);
  11610. }
  11611. }
  11612. this._rect = rect || tmpRect;
  11613. }
  11614. return this._rect;
  11615. };
  11616. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11617. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11618. };
  11619. ZRText.prototype.setTextContent = function (textContent) {
  11620. if ("development" !== 'production') {
  11621. throw new Error('Can\'t attach text on another text');
  11622. }
  11623. };
  11624. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11625. if (!sourceStyle) {
  11626. return targetStyle;
  11627. }
  11628. var sourceRich = sourceStyle.rich;
  11629. var targetRich = targetStyle.rich || (sourceRich && {});
  11630. extend(targetStyle, sourceStyle);
  11631. if (sourceRich && targetRich) {
  11632. this._mergeRich(targetRich, sourceRich);
  11633. targetStyle.rich = targetRich;
  11634. }
  11635. else if (targetRich) {
  11636. targetStyle.rich = targetRich;
  11637. }
  11638. return targetStyle;
  11639. };
  11640. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11641. var richNames = keys(sourceRich);
  11642. for (var i = 0; i < richNames.length; i++) {
  11643. var richName = richNames[i];
  11644. targetRich[richName] = targetRich[richName] || {};
  11645. extend(targetRich[richName], sourceRich[richName]);
  11646. }
  11647. };
  11648. ZRText.prototype.getAnimationStyleProps = function () {
  11649. return DEFAULT_TEXT_ANIMATION_PROPS;
  11650. };
  11651. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11652. var child = this._children[this._childCursor];
  11653. if (!child || !(child instanceof Ctor)) {
  11654. child = new Ctor();
  11655. }
  11656. this._children[this._childCursor++] = child;
  11657. child.__zr = this.__zr;
  11658. child.parent = this;
  11659. return child;
  11660. };
  11661. ZRText.prototype._updatePlainTexts = function () {
  11662. var style = this.style;
  11663. var textFont = style.font || DEFAULT_FONT;
  11664. var textPadding = style.padding;
  11665. var text = getStyleText(style);
  11666. var contentBlock = parsePlainText(text, style);
  11667. var needDrawBg = needDrawBackground(style);
  11668. var bgColorDrawn = !!(style.backgroundColor);
  11669. var outerHeight = contentBlock.outerHeight;
  11670. var outerWidth = contentBlock.outerWidth;
  11671. var contentWidth = contentBlock.contentWidth;
  11672. var textLines = contentBlock.lines;
  11673. var lineHeight = contentBlock.lineHeight;
  11674. var defaultStyle = this._defaultStyle;
  11675. var baseX = style.x || 0;
  11676. var baseY = style.y || 0;
  11677. var textAlign = style.align || defaultStyle.align || 'left';
  11678. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11679. var textX = baseX;
  11680. var textY = adjustTextY$1(baseY, contentBlock.contentHeight, verticalAlign);
  11681. if (needDrawBg || textPadding) {
  11682. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11683. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11684. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11685. }
  11686. textY += lineHeight / 2;
  11687. if (textPadding) {
  11688. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11689. if (verticalAlign === 'top') {
  11690. textY += textPadding[0];
  11691. }
  11692. else if (verticalAlign === 'bottom') {
  11693. textY -= textPadding[2];
  11694. }
  11695. }
  11696. var defaultLineWidth = 0;
  11697. var useDefaultFill = false;
  11698. var textFill = getFill('fill' in style
  11699. ? style.fill
  11700. : (useDefaultFill = true, defaultStyle.fill));
  11701. var textStroke = getStroke('stroke' in style
  11702. ? style.stroke
  11703. : (!bgColorDrawn
  11704. && (!defaultStyle.autoStroke || useDefaultFill))
  11705. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11706. : null);
  11707. var hasShadow = style.textShadowBlur > 0;
  11708. var fixedBoundingRect = style.width != null
  11709. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11710. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11711. for (var i = 0; i < textLines.length; i++) {
  11712. var el = this._getOrCreateChild(TSpan);
  11713. var subElStyle = el.createStyle();
  11714. el.useStyle(subElStyle);
  11715. subElStyle.text = textLines[i];
  11716. subElStyle.x = textX;
  11717. subElStyle.y = textY;
  11718. if (textAlign) {
  11719. subElStyle.textAlign = textAlign;
  11720. }
  11721. subElStyle.textBaseline = 'middle';
  11722. subElStyle.opacity = style.opacity;
  11723. subElStyle.strokeFirst = true;
  11724. if (hasShadow) {
  11725. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11726. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11727. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11728. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11729. }
  11730. subElStyle.stroke = textStroke;
  11731. subElStyle.fill = textFill;
  11732. if (textStroke) {
  11733. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11734. subElStyle.lineDash = style.lineDash;
  11735. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11736. }
  11737. subElStyle.font = textFont;
  11738. setSeparateFont(subElStyle, style);
  11739. textY += lineHeight;
  11740. if (fixedBoundingRect) {
  11741. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY$1(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), contentWidth, calculatedLineHeight));
  11742. }
  11743. }
  11744. };
  11745. ZRText.prototype._updateRichTexts = function () {
  11746. var style = this.style;
  11747. var text = getStyleText(style);
  11748. var contentBlock = parseRichText(text, style);
  11749. var contentWidth = contentBlock.width;
  11750. var outerWidth = contentBlock.outerWidth;
  11751. var outerHeight = contentBlock.outerHeight;
  11752. var textPadding = style.padding;
  11753. var baseX = style.x || 0;
  11754. var baseY = style.y || 0;
  11755. var defaultStyle = this._defaultStyle;
  11756. var textAlign = style.align || defaultStyle.align;
  11757. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11758. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11759. var boxY = adjustTextY$1(baseY, outerHeight, verticalAlign);
  11760. var xLeft = boxX;
  11761. var lineTop = boxY;
  11762. if (textPadding) {
  11763. xLeft += textPadding[3];
  11764. lineTop += textPadding[0];
  11765. }
  11766. var xRight = xLeft + contentWidth;
  11767. if (needDrawBackground(style)) {
  11768. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11769. }
  11770. var bgColorDrawn = !!(style.backgroundColor);
  11771. for (var i = 0; i < contentBlock.lines.length; i++) {
  11772. var line = contentBlock.lines[i];
  11773. var tokens = line.tokens;
  11774. var tokenCount = tokens.length;
  11775. var lineHeight = line.lineHeight;
  11776. var remainedWidth = line.width;
  11777. var leftIndex = 0;
  11778. var lineXLeft = xLeft;
  11779. var lineXRight = xRight;
  11780. var rightIndex = tokenCount - 1;
  11781. var token = void 0;
  11782. while (leftIndex < tokenCount
  11783. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11784. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11785. remainedWidth -= token.width;
  11786. lineXLeft += token.width;
  11787. leftIndex++;
  11788. }
  11789. while (rightIndex >= 0
  11790. && (token = tokens[rightIndex], token.align === 'right')) {
  11791. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11792. remainedWidth -= token.width;
  11793. lineXRight -= token.width;
  11794. rightIndex--;
  11795. }
  11796. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11797. while (leftIndex <= rightIndex) {
  11798. token = tokens[leftIndex];
  11799. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11800. lineXLeft += token.width;
  11801. leftIndex++;
  11802. }
  11803. lineTop += lineHeight;
  11804. }
  11805. };
  11806. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11807. var tokenStyle = style.rich[token.styleName] || {};
  11808. tokenStyle.text = token.text;
  11809. var verticalAlign = token.verticalAlign;
  11810. var y = lineTop + lineHeight / 2;
  11811. if (verticalAlign === 'top') {
  11812. y = lineTop + token.height / 2;
  11813. }
  11814. else if (verticalAlign === 'bottom') {
  11815. y = lineTop + lineHeight - token.height / 2;
  11816. }
  11817. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11818. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11819. ? x - token.width
  11820. : textAlign === 'center'
  11821. ? x - token.width / 2
  11822. : x, y - token.height / 2, token.width, token.height);
  11823. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11824. var textPadding = token.textPadding;
  11825. if (textPadding) {
  11826. x = getTextXForPadding(x, textAlign, textPadding);
  11827. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11828. }
  11829. var el = this._getOrCreateChild(TSpan);
  11830. var subElStyle = el.createStyle();
  11831. el.useStyle(subElStyle);
  11832. var defaultStyle = this._defaultStyle;
  11833. var useDefaultFill = false;
  11834. var defaultLineWidth = 0;
  11835. var textFill = getFill('fill' in tokenStyle ? tokenStyle.fill
  11836. : 'fill' in style ? style.fill
  11837. : (useDefaultFill = true, defaultStyle.fill));
  11838. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11839. : 'stroke' in style ? style.stroke
  11840. : (!bgColorDrawn
  11841. && !parentBgColorDrawn
  11842. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11843. : null);
  11844. var hasShadow = tokenStyle.textShadowBlur > 0
  11845. || style.textShadowBlur > 0;
  11846. subElStyle.text = token.text;
  11847. subElStyle.x = x;
  11848. subElStyle.y = y;
  11849. if (hasShadow) {
  11850. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11851. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11852. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11853. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11854. }
  11855. subElStyle.textAlign = textAlign;
  11856. subElStyle.textBaseline = 'middle';
  11857. subElStyle.font = token.font || DEFAULT_FONT;
  11858. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11859. setSeparateFont(subElStyle, tokenStyle);
  11860. if (textStroke) {
  11861. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11862. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11863. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11864. subElStyle.stroke = textStroke;
  11865. }
  11866. if (textFill) {
  11867. subElStyle.fill = textFill;
  11868. }
  11869. var textWidth = token.contentWidth;
  11870. var textHeight = token.contentHeight;
  11871. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY$1(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11872. };
  11873. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11874. var textBackgroundColor = style.backgroundColor;
  11875. var textBorderWidth = style.borderWidth;
  11876. var textBorderColor = style.borderColor;
  11877. var isImageBg = textBackgroundColor && textBackgroundColor.image;
  11878. var isPlainOrGradientBg = textBackgroundColor && !isImageBg;
  11879. var textBorderRadius = style.borderRadius;
  11880. var self = this;
  11881. var rectEl;
  11882. var imgEl;
  11883. if (isPlainOrGradientBg || style.lineHeight || (textBorderWidth && textBorderColor)) {
  11884. rectEl = this._getOrCreateChild(Rect);
  11885. rectEl.useStyle(rectEl.createStyle());
  11886. rectEl.style.fill = null;
  11887. var rectShape = rectEl.shape;
  11888. rectShape.x = x;
  11889. rectShape.y = y;
  11890. rectShape.width = width;
  11891. rectShape.height = height;
  11892. rectShape.r = textBorderRadius;
  11893. rectEl.dirtyShape();
  11894. }
  11895. if (isPlainOrGradientBg) {
  11896. var rectStyle = rectEl.style;
  11897. rectStyle.fill = textBackgroundColor || null;
  11898. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11899. }
  11900. else if (isImageBg) {
  11901. imgEl = this._getOrCreateChild(ZRImage);
  11902. imgEl.onload = function () {
  11903. self.dirtyStyle();
  11904. };
  11905. var imgStyle = imgEl.style;
  11906. imgStyle.image = textBackgroundColor.image;
  11907. imgStyle.x = x;
  11908. imgStyle.y = y;
  11909. imgStyle.width = width;
  11910. imgStyle.height = height;
  11911. }
  11912. if (textBorderWidth && textBorderColor) {
  11913. var rectStyle = rectEl.style;
  11914. rectStyle.lineWidth = textBorderWidth;
  11915. rectStyle.stroke = textBorderColor;
  11916. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11917. rectStyle.lineDash = style.borderDash;
  11918. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11919. rectEl.strokeContainThreshold = 0;
  11920. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11921. rectStyle.strokeFirst = true;
  11922. rectStyle.lineWidth *= 2;
  11923. }
  11924. }
  11925. var commonStyle = (rectEl || imgEl).style;
  11926. commonStyle.shadowBlur = style.shadowBlur || 0;
  11927. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11928. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11929. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11930. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11931. };
  11932. ZRText.makeFont = function (style) {
  11933. var font = '';
  11934. if (hasSeparateFont(style)) {
  11935. font = [
  11936. style.fontStyle,
  11937. style.fontWeight,
  11938. parseFontSize(style.fontSize),
  11939. style.fontFamily || 'sans-serif'
  11940. ].join(' ');
  11941. }
  11942. return font && trim(font) || style.textFont || style.font;
  11943. };
  11944. return ZRText;
  11945. }(Displayable));
  11946. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11947. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11948. var FONT_PARTS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily'];
  11949. function parseFontSize(fontSize) {
  11950. if (typeof fontSize === 'string'
  11951. && (fontSize.indexOf('px') !== -1
  11952. || fontSize.indexOf('rem') !== -1
  11953. || fontSize.indexOf('em') !== -1)) {
  11954. return fontSize;
  11955. }
  11956. else if (!isNaN(+fontSize)) {
  11957. return fontSize + 'px';
  11958. }
  11959. else {
  11960. return DEFAULT_FONT_SIZE + 'px';
  11961. }
  11962. }
  11963. function setSeparateFont(targetStyle, sourceStyle) {
  11964. for (var i = 0; i < FONT_PARTS.length; i++) {
  11965. var fontProp = FONT_PARTS[i];
  11966. var val = sourceStyle[fontProp];
  11967. if (val != null) {
  11968. targetStyle[fontProp] = val;
  11969. }
  11970. }
  11971. }
  11972. function hasSeparateFont(style) {
  11973. return style.fontSize != null || style.fontFamily || style.fontWeight;
  11974. }
  11975. function normalizeTextStyle(style) {
  11976. normalizeStyle(style);
  11977. each(style.rich, normalizeStyle);
  11978. return style;
  11979. }
  11980. function normalizeStyle(style) {
  11981. if (style) {
  11982. style.font = ZRText.makeFont(style);
  11983. var textAlign = style.align;
  11984. textAlign === 'middle' && (textAlign = 'center');
  11985. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11986. var verticalAlign = style.verticalAlign;
  11987. verticalAlign === 'center' && (verticalAlign = 'middle');
  11988. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11989. var textPadding = style.padding;
  11990. if (textPadding) {
  11991. style.padding = normalizeCssArray(style.padding);
  11992. }
  11993. }
  11994. }
  11995. function getStroke(stroke, lineWidth) {
  11996. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11997. ? null
  11998. : (stroke.image || stroke.colorStops)
  11999. ? '#000'
  12000. : stroke;
  12001. }
  12002. function getFill(fill) {
  12003. return (fill == null || fill === 'none')
  12004. ? null
  12005. : (fill.image || fill.colorStops)
  12006. ? '#000'
  12007. : fill;
  12008. }
  12009. function getTextXForPadding(x, textAlign, textPadding) {
  12010. return textAlign === 'right'
  12011. ? (x - textPadding[1])
  12012. : textAlign === 'center'
  12013. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  12014. : (x + textPadding[3]);
  12015. }
  12016. function getStyleText(style) {
  12017. var text = style.text;
  12018. text != null && (text += '');
  12019. return text;
  12020. }
  12021. function needDrawBackground(style) {
  12022. return !!(style.backgroundColor
  12023. || style.lineHeight
  12024. || (style.borderWidth && style.borderColor));
  12025. }
  12026. var getECData = makeInner();
  12027. var setCommonECData = function (seriesIndex, dataType, dataIdx, el) {
  12028. if (el) {
  12029. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  12030. // Useful in tooltip
  12031. ecData.dataIndex = dataIdx;
  12032. ecData.dataType = dataType;
  12033. ecData.seriesIndex = seriesIndex; // TODO: not store dataIndex on children.
  12034. if (el.type === 'group') {
  12035. el.traverse(function (child) {
  12036. var childECData = getECData(child);
  12037. childECData.seriesIndex = seriesIndex;
  12038. childECData.dataIndex = dataIdx;
  12039. childECData.dataType = dataType;
  12040. });
  12041. }
  12042. }
  12043. };
  12044. var _highlightNextDigit = 1;
  12045. var _highlightKeyMap = {};
  12046. var getSavedStates = makeInner();
  12047. var getComponentStates = makeInner();
  12048. var HOVER_STATE_NORMAL = 0;
  12049. var HOVER_STATE_BLUR = 1;
  12050. var HOVER_STATE_EMPHASIS = 2;
  12051. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  12052. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  12053. var Z2_EMPHASIS_LIFT = 10;
  12054. var Z2_SELECT_LIFT = 9;
  12055. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  12056. var DOWNPLAY_ACTION_TYPE = 'downplay';
  12057. var SELECT_ACTION_TYPE = 'select';
  12058. var UNSELECT_ACTION_TYPE = 'unselect';
  12059. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  12060. function hasFillOrStroke(fillOrStroke) {
  12061. return fillOrStroke != null && fillOrStroke !== 'none';
  12062. } // Most lifted color are duplicated.
  12063. var liftedColorCache = new LRU(100);
  12064. function liftColor(color$1) {
  12065. if (isString(color$1)) {
  12066. var liftedColor = liftedColorCache.get(color$1);
  12067. if (!liftedColor) {
  12068. liftedColor = lift(color$1, -0.1);
  12069. liftedColorCache.put(color$1, liftedColor);
  12070. }
  12071. return liftedColor;
  12072. } else if (isGradientObject(color$1)) {
  12073. var ret = extend({}, color$1);
  12074. ret.colorStops = map(color$1.colorStops, function (stop) {
  12075. return {
  12076. offset: stop.offset,
  12077. color: lift(stop.color, -0.1)
  12078. };
  12079. });
  12080. return ret;
  12081. } // Change nothing.
  12082. return color$1;
  12083. }
  12084. function doChangeHoverState(el, stateName, hoverStateEnum) {
  12085. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  12086. el.onHoverStateChange(stateName);
  12087. }
  12088. el.hoverState = hoverStateEnum;
  12089. }
  12090. function singleEnterEmphasis(el) {
  12091. // Only mark the flag.
  12092. // States will be applied in the echarts.ts in next frame.
  12093. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  12094. }
  12095. function singleLeaveEmphasis(el) {
  12096. // Only mark the flag.
  12097. // States will be applied in the echarts.ts in next frame.
  12098. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  12099. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12100. }
  12101. }
  12102. function singleEnterBlur(el) {
  12103. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  12104. }
  12105. function singleLeaveBlur(el) {
  12106. if (el.hoverState === HOVER_STATE_BLUR) {
  12107. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  12108. }
  12109. }
  12110. function singleEnterSelect(el) {
  12111. el.selected = true;
  12112. }
  12113. function singleLeaveSelect(el) {
  12114. el.selected = false;
  12115. }
  12116. function updateElementState(el, updater, commonParam) {
  12117. updater(el, commonParam);
  12118. }
  12119. function traverseUpdateState(el, updater, commonParam) {
  12120. updateElementState(el, updater, commonParam);
  12121. el.isGroup && el.traverse(function (child) {
  12122. updateElementState(child, updater, commonParam);
  12123. });
  12124. }
  12125. function setStatesFlag(el, stateName) {
  12126. switch (stateName) {
  12127. case 'emphasis':
  12128. el.hoverState = HOVER_STATE_EMPHASIS;
  12129. break;
  12130. case 'normal':
  12131. el.hoverState = HOVER_STATE_NORMAL;
  12132. break;
  12133. case 'blur':
  12134. el.hoverState = HOVER_STATE_BLUR;
  12135. break;
  12136. case 'select':
  12137. el.selected = true;
  12138. }
  12139. }
  12140. function getFromStateStyle(el, props, toStateName, defaultValue) {
  12141. var style = el.style;
  12142. var fromState = {};
  12143. for (var i = 0; i < props.length; i++) {
  12144. var propName = props[i];
  12145. var val = style[propName];
  12146. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  12147. }
  12148. for (var i = 0; i < el.animators.length; i++) {
  12149. var animator = el.animators[i];
  12150. if (animator.__fromStateTransition // Don't consider the animation to emphasis state.
  12151. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  12152. animator.saveTo(fromState, props);
  12153. }
  12154. }
  12155. return fromState;
  12156. }
  12157. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  12158. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  12159. var cloned = false;
  12160. if (el instanceof Path) {
  12161. var store = getSavedStates(el);
  12162. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  12163. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  12164. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  12165. state = state || {};
  12166. var emphasisStyle = state.style || {}; // inherit case
  12167. if (emphasisStyle.fill === 'inherit') {
  12168. cloned = true;
  12169. state = extend({}, state);
  12170. emphasisStyle = extend({}, emphasisStyle);
  12171. emphasisStyle.fill = fromFill;
  12172. } // Apply default color lift
  12173. else if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  12174. cloned = true; // Not modify the original value.
  12175. state = extend({}, state);
  12176. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  12177. emphasisStyle.fill = liftColor(fromFill);
  12178. } // Not highlight stroke if fill has been highlighted.
  12179. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  12180. if (!cloned) {
  12181. state = extend({}, state);
  12182. emphasisStyle = extend({}, emphasisStyle);
  12183. }
  12184. emphasisStyle.stroke = liftColor(fromStroke);
  12185. }
  12186. state.style = emphasisStyle;
  12187. }
  12188. }
  12189. if (state) {
  12190. // TODO Share with textContent?
  12191. if (state.z2 == null) {
  12192. if (!cloned) {
  12193. state = extend({}, state);
  12194. }
  12195. var z2EmphasisLift = el.z2EmphasisLift;
  12196. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  12197. }
  12198. }
  12199. return state;
  12200. }
  12201. function createSelectDefaultState(el, stateName, state) {
  12202. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  12203. if (state) {
  12204. // TODO Share with textContent?
  12205. if (state.z2 == null) {
  12206. state = extend({}, state);
  12207. var z2SelectLift = el.z2SelectLift;
  12208. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  12209. }
  12210. }
  12211. return state;
  12212. }
  12213. function createBlurDefaultState(el, stateName, state) {
  12214. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  12215. var currentOpacity = el.style.opacity;
  12216. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  12217. opacity: 1
  12218. }) : null;
  12219. state = state || {};
  12220. var blurStyle = state.style || {};
  12221. if (blurStyle.opacity == null) {
  12222. // clone state
  12223. state = extend({}, state);
  12224. blurStyle = extend({
  12225. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  12226. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  12227. }, blurStyle);
  12228. state.style = blurStyle;
  12229. }
  12230. return state;
  12231. }
  12232. function elementStateProxy(stateName, targetStates) {
  12233. var state = this.states[stateName];
  12234. if (this.style) {
  12235. if (stateName === 'emphasis') {
  12236. return createEmphasisDefaultState(this, stateName, targetStates, state);
  12237. } else if (stateName === 'blur') {
  12238. return createBlurDefaultState(this, stateName, state);
  12239. } else if (stateName === 'select') {
  12240. return createSelectDefaultState(this, stateName, state);
  12241. }
  12242. }
  12243. return state;
  12244. }
  12245. /**
  12246. * Set hover style (namely "emphasis style") of element.
  12247. * @param el Should not be `zrender/graphic/Group`.
  12248. * @param focus 'self' | 'selfInSeries' | 'series'
  12249. */
  12250. function setDefaultStateProxy(el) {
  12251. el.stateProxy = elementStateProxy;
  12252. var textContent = el.getTextContent();
  12253. var textGuide = el.getTextGuideLine();
  12254. if (textContent) {
  12255. textContent.stateProxy = elementStateProxy;
  12256. }
  12257. if (textGuide) {
  12258. textGuide.stateProxy = elementStateProxy;
  12259. }
  12260. }
  12261. function enterEmphasisWhenMouseOver(el, e) {
  12262. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12263. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  12264. }
  12265. function leaveEmphasisWhenMouseOut(el, e) {
  12266. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  12267. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  12268. }
  12269. function enterEmphasis(el, highlightDigit) {
  12270. el.__highByOuter |= 1 << (highlightDigit || 0);
  12271. traverseUpdateState(el, singleEnterEmphasis);
  12272. }
  12273. function leaveEmphasis(el, highlightDigit) {
  12274. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  12275. }
  12276. function enterBlur(el) {
  12277. traverseUpdateState(el, singleEnterBlur);
  12278. }
  12279. function leaveBlur(el) {
  12280. traverseUpdateState(el, singleLeaveBlur);
  12281. }
  12282. function enterSelect(el) {
  12283. traverseUpdateState(el, singleEnterSelect);
  12284. }
  12285. function leaveSelect(el) {
  12286. traverseUpdateState(el, singleLeaveSelect);
  12287. }
  12288. function shouldSilent(el, e) {
  12289. return el.__highDownSilentOnTouch && e.zrByTouch;
  12290. }
  12291. function allLeaveBlur(api) {
  12292. var model = api.getModel();
  12293. var leaveBlurredSeries = [];
  12294. var allComponentViews = [];
  12295. model.eachComponent(function (componentType, componentModel) {
  12296. var componentStates = getComponentStates(componentModel);
  12297. var isSeries = componentType === 'series';
  12298. var view = isSeries ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel);
  12299. !isSeries && allComponentViews.push(view);
  12300. if (componentStates.isBlured) {
  12301. // Leave blur anyway
  12302. view.group.traverse(function (child) {
  12303. singleLeaveBlur(child);
  12304. });
  12305. isSeries && leaveBlurredSeries.push(componentModel);
  12306. }
  12307. componentStates.isBlured = false;
  12308. });
  12309. each(allComponentViews, function (view) {
  12310. if (view && view.toggleBlurSeries) {
  12311. view.toggleBlurSeries(leaveBlurredSeries, false, model);
  12312. }
  12313. });
  12314. }
  12315. function blurSeries(targetSeriesIndex, focus, blurScope, api) {
  12316. var ecModel = api.getModel();
  12317. blurScope = blurScope || 'coordinateSystem';
  12318. function leaveBlurOfIndices(data, dataIndices) {
  12319. for (var i = 0; i < dataIndices.length; i++) {
  12320. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  12321. itemEl && leaveBlur(itemEl);
  12322. }
  12323. }
  12324. if (targetSeriesIndex == null) {
  12325. return;
  12326. }
  12327. if (!focus || focus === 'none') {
  12328. return;
  12329. }
  12330. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  12331. var targetCoordSys = targetSeriesModel.coordinateSystem;
  12332. if (targetCoordSys && targetCoordSys.master) {
  12333. targetCoordSys = targetCoordSys.master;
  12334. }
  12335. var blurredSeries = [];
  12336. ecModel.eachSeries(function (seriesModel) {
  12337. var sameSeries = targetSeriesModel === seriesModel;
  12338. var coordSys = seriesModel.coordinateSystem;
  12339. if (coordSys && coordSys.master) {
  12340. coordSys = coordSys.master;
  12341. }
  12342. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  12343. if (!( // Not blur other series if blurScope series
  12344. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  12345. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  12346. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  12347. )) {
  12348. var view = api.getViewOfSeriesModel(seriesModel);
  12349. view.group.traverse(function (child) {
  12350. // For the elements that have been triggered by other components,
  12351. // and are still required to be highlighted,
  12352. // because the current is directly forced to blur the element,
  12353. // it will cause the focus self to be unable to highlight, so skip the blur of this element.
  12354. if (child.__highByOuter && sameSeries && focus === 'self') {
  12355. return;
  12356. }
  12357. singleEnterBlur(child);
  12358. });
  12359. if (isArrayLike(focus)) {
  12360. leaveBlurOfIndices(seriesModel.getData(), focus);
  12361. } else if (isObject(focus)) {
  12362. var dataTypes = keys(focus);
  12363. for (var d = 0; d < dataTypes.length; d++) {
  12364. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  12365. }
  12366. }
  12367. blurredSeries.push(seriesModel);
  12368. getComponentStates(seriesModel).isBlured = true;
  12369. }
  12370. });
  12371. ecModel.eachComponent(function (componentType, componentModel) {
  12372. if (componentType === 'series') {
  12373. return;
  12374. }
  12375. var view = api.getViewOfComponentModel(componentModel);
  12376. if (view && view.toggleBlurSeries) {
  12377. view.toggleBlurSeries(blurredSeries, true, ecModel);
  12378. }
  12379. });
  12380. }
  12381. function blurComponent(componentMainType, componentIndex, api) {
  12382. if (componentMainType == null || componentIndex == null) {
  12383. return;
  12384. }
  12385. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12386. if (!componentModel) {
  12387. return;
  12388. }
  12389. getComponentStates(componentModel).isBlured = true;
  12390. var view = api.getViewOfComponentModel(componentModel);
  12391. if (!view || !view.focusBlurEnabled) {
  12392. return;
  12393. }
  12394. view.group.traverse(function (child) {
  12395. singleEnterBlur(child);
  12396. });
  12397. }
  12398. function blurSeriesFromHighlightPayload(seriesModel, payload, api) {
  12399. var seriesIndex = seriesModel.seriesIndex;
  12400. var data = seriesModel.getData(payload.dataType);
  12401. if (!data) {
  12402. if ("development" !== 'production') {
  12403. error("Unknown dataType " + payload.dataType);
  12404. }
  12405. return;
  12406. }
  12407. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  12408. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  12409. var el = data.getItemGraphicEl(dataIndex);
  12410. if (!el) {
  12411. var count = data.count();
  12412. var current = 0; // If data on dataIndex is NaN.
  12413. while (!el && current < count) {
  12414. el = data.getItemGraphicEl(current++);
  12415. }
  12416. }
  12417. if (el) {
  12418. var ecData = getECData(el);
  12419. blurSeries(seriesIndex, ecData.focus, ecData.blurScope, api);
  12420. } else {
  12421. // If there is no element put on the data. Try getting it from raw option
  12422. // TODO Should put it on seriesModel?
  12423. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  12424. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  12425. if (focus_1 != null) {
  12426. blurSeries(seriesIndex, focus_1, blurScope, api);
  12427. }
  12428. }
  12429. }
  12430. function findComponentHighDownDispatchers(componentMainType, componentIndex, name, api) {
  12431. var ret = {
  12432. focusSelf: false,
  12433. dispatchers: null
  12434. };
  12435. if (componentMainType == null || componentMainType === 'series' || componentIndex == null || name == null) {
  12436. return ret;
  12437. }
  12438. var componentModel = api.getModel().getComponent(componentMainType, componentIndex);
  12439. if (!componentModel) {
  12440. return ret;
  12441. }
  12442. var view = api.getViewOfComponentModel(componentModel);
  12443. if (!view || !view.findHighDownDispatchers) {
  12444. return ret;
  12445. }
  12446. var dispatchers = view.findHighDownDispatchers(name); // At presnet, the component (like Geo) only blur inside itself.
  12447. // So we do not use `blurScope` in component.
  12448. var focusSelf;
  12449. for (var i = 0; i < dispatchers.length; i++) {
  12450. if ("development" !== 'production' && !isHighDownDispatcher(dispatchers[i])) {
  12451. error('param should be highDownDispatcher');
  12452. }
  12453. if (getECData(dispatchers[i]).focus === 'self') {
  12454. focusSelf = true;
  12455. break;
  12456. }
  12457. }
  12458. return {
  12459. focusSelf: focusSelf,
  12460. dispatchers: dispatchers
  12461. };
  12462. }
  12463. function handleGlobalMouseOverForHighDown(dispatcher, e, api) {
  12464. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12465. error('param should be highDownDispatcher');
  12466. }
  12467. var ecData = getECData(dispatcher);
  12468. var _a = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api),
  12469. dispatchers = _a.dispatchers,
  12470. focusSelf = _a.focusSelf; // If `findHighDownDispatchers` is supported on the component,
  12471. // highlight/downplay elements with the same name.
  12472. if (dispatchers) {
  12473. if (focusSelf) {
  12474. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12475. }
  12476. each(dispatchers, function (dispatcher) {
  12477. return enterEmphasisWhenMouseOver(dispatcher, e);
  12478. });
  12479. } else {
  12480. // Try blur all in the related series. Then emphasis the hoverred.
  12481. // TODO. progressive mode.
  12482. blurSeries(ecData.seriesIndex, ecData.focus, ecData.blurScope, api);
  12483. if (ecData.focus === 'self') {
  12484. blurComponent(ecData.componentMainType, ecData.componentIndex, api);
  12485. } // Other than series, component that not support `findHighDownDispatcher` will
  12486. // also use it. But in this case, highlight/downplay are only supported in
  12487. // mouse hover but not in dispatchAction.
  12488. enterEmphasisWhenMouseOver(dispatcher, e);
  12489. }
  12490. }
  12491. function handleGlobalMouseOutForHighDown(dispatcher, e, api) {
  12492. if ("development" !== 'production' && !isHighDownDispatcher(dispatcher)) {
  12493. error('param should be highDownDispatcher');
  12494. }
  12495. allLeaveBlur(api);
  12496. var ecData = getECData(dispatcher);
  12497. var dispatchers = findComponentHighDownDispatchers(ecData.componentMainType, ecData.componentIndex, ecData.componentHighDownName, api).dispatchers;
  12498. if (dispatchers) {
  12499. each(dispatchers, function (dispatcher) {
  12500. return leaveEmphasisWhenMouseOut(dispatcher, e);
  12501. });
  12502. } else {
  12503. leaveEmphasisWhenMouseOut(dispatcher, e);
  12504. }
  12505. }
  12506. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12507. if (!isSelectChangePayload(payload)) {
  12508. return;
  12509. }
  12510. var dataType = payload.dataType;
  12511. var data = seriesModel.getData(dataType);
  12512. var dataIndex = queryDataIndex(data, payload);
  12513. if (!isArray(dataIndex)) {
  12514. dataIndex = [dataIndex];
  12515. }
  12516. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12517. }
  12518. function updateSeriesElementSelection(seriesModel) {
  12519. var allData = seriesModel.getAllData();
  12520. each(allData, function (_a) {
  12521. var data = _a.data,
  12522. type = _a.type;
  12523. data.eachItemGraphicEl(function (el, idx) {
  12524. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12525. });
  12526. });
  12527. }
  12528. function getAllSelectedIndices(ecModel) {
  12529. var ret = [];
  12530. ecModel.eachSeries(function (seriesModel) {
  12531. var allData = seriesModel.getAllData();
  12532. each(allData, function (_a) {
  12533. var data = _a.data,
  12534. type = _a.type;
  12535. var dataIndices = seriesModel.getSelectedDataIndices();
  12536. if (dataIndices.length > 0) {
  12537. var item = {
  12538. dataIndex: dataIndices,
  12539. seriesIndex: seriesModel.seriesIndex
  12540. };
  12541. if (type != null) {
  12542. item.dataType = type;
  12543. }
  12544. ret.push(item);
  12545. }
  12546. });
  12547. });
  12548. return ret;
  12549. }
  12550. /**
  12551. * Enable the function that mouseover will trigger the emphasis state.
  12552. *
  12553. * NOTE:
  12554. * This function should be used on the element with dataIndex, seriesIndex.
  12555. *
  12556. */
  12557. function enableHoverEmphasis(el, focus, blurScope) {
  12558. setAsHighDownDispatcher(el, true);
  12559. traverseUpdateState(el, setDefaultStateProxy);
  12560. enableHoverFocus(el, focus, blurScope);
  12561. }
  12562. function disableHoverEmphasis(el) {
  12563. setAsHighDownDispatcher(el, false);
  12564. }
  12565. function toggleHoverEmphasis(el, focus, blurScope, isDisabled) {
  12566. isDisabled ? disableHoverEmphasis(el) : enableHoverEmphasis(el, focus, blurScope);
  12567. }
  12568. function enableHoverFocus(el, focus, blurScope) {
  12569. var ecData = getECData(el);
  12570. if (focus != null) {
  12571. // TODO dataIndex may be set after this function. This check is not useful.
  12572. // if (ecData.dataIndex == null) {
  12573. // if (__DEV__) {
  12574. // console.warn('focus can only been set on element with dataIndex');
  12575. // }
  12576. // }
  12577. // else {
  12578. ecData.focus = focus;
  12579. ecData.blurScope = blurScope; // }
  12580. } else if (ecData.focus) {
  12581. ecData.focus = null;
  12582. }
  12583. }
  12584. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12585. var defaultStyleGetterMap = {
  12586. itemStyle: 'getItemStyle',
  12587. lineStyle: 'getLineStyle',
  12588. areaStyle: 'getAreaStyle'
  12589. };
  12590. /**
  12591. * Set emphasis/blur/selected states of element.
  12592. */
  12593. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12594. getter) {
  12595. styleType = styleType || 'itemStyle';
  12596. for (var i = 0; i < OTHER_STATES.length; i++) {
  12597. var stateName = OTHER_STATES[i];
  12598. var model = itemModel.getModel([stateName, styleType]);
  12599. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12600. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12601. }
  12602. }
  12603. /**
  12604. *
  12605. * Set element as highlight / downplay dispatcher.
  12606. * It will be checked when element received mouseover event or from highlight action.
  12607. * It's in change of all highlight/downplay behavior of it's children.
  12608. *
  12609. * @param el
  12610. * @param el.highDownSilentOnTouch
  12611. * In touch device, mouseover event will be trigger on touchstart event
  12612. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12613. * conveniently use hoverStyle when tap on touch screen without additional
  12614. * code for compatibility.
  12615. * But if the chart/component has select feature, which usually also use
  12616. * hoverStyle, there might be conflict between 'select-highlight' and
  12617. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12618. * In this case, `highDownSilentOnTouch` should be used to disable
  12619. * hover-highlight on touch device.
  12620. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12621. */
  12622. function setAsHighDownDispatcher(el, asDispatcher) {
  12623. var disable = asDispatcher === false;
  12624. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12625. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12626. if (el.highDownSilentOnTouch) {
  12627. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12628. } // Simple optimize, since this method might be
  12629. // called for each elements of a group in some cases.
  12630. if (!disable || extendedEl.__highDownDispatcher) {
  12631. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12632. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12633. // Also keep previous record.
  12634. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12635. extendedEl.__highDownDispatcher = !disable;
  12636. }
  12637. }
  12638. function isHighDownDispatcher(el) {
  12639. return !!(el && el.__highDownDispatcher);
  12640. }
  12641. /**
  12642. * Enable component highlight/downplay features:
  12643. * + hover link (within the same name)
  12644. * + focus blur in component
  12645. */
  12646. function enableComponentHighDownFeatures(el, componentModel, componentHighDownName) {
  12647. var ecData = getECData(el);
  12648. ecData.componentMainType = componentModel.mainType;
  12649. ecData.componentIndex = componentModel.componentIndex;
  12650. ecData.componentHighDownName = componentHighDownName;
  12651. }
  12652. /**
  12653. * Support highlight/downplay record on each elements.
  12654. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12655. * user triggered highlight/downplay should not conflict.
  12656. * Only all of the highlightDigit cleared, return to normal.
  12657. * @param {string} highlightKey
  12658. * @return {number} highlightDigit
  12659. */
  12660. function getHighlightDigit(highlightKey) {
  12661. var highlightDigit = _highlightKeyMap[highlightKey];
  12662. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12663. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12664. }
  12665. return highlightDigit;
  12666. }
  12667. function isSelectChangePayload(payload) {
  12668. var payloadType = payload.type;
  12669. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12670. }
  12671. function isHighDownPayload(payload) {
  12672. var payloadType = payload.type;
  12673. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12674. }
  12675. function savePathStates(el) {
  12676. var store = getSavedStates(el);
  12677. store.normalFill = el.style.fill;
  12678. store.normalStroke = el.style.stroke;
  12679. var selectState = el.states.select || {};
  12680. store.selectFill = selectState.style && selectState.style.fill || null;
  12681. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12682. }
  12683. var CMD$2 = PathProxy.CMD;
  12684. var points = [[], [], []];
  12685. var mathSqrt$1 = Math.sqrt;
  12686. var mathAtan2 = Math.atan2;
  12687. function transformPath(path, m) {
  12688. if (!m) {
  12689. return;
  12690. }
  12691. var data = path.data;
  12692. var len = path.len();
  12693. var cmd;
  12694. var nPoint;
  12695. var i;
  12696. var j;
  12697. var k;
  12698. var p;
  12699. var M = CMD$2.M;
  12700. var C = CMD$2.C;
  12701. var L = CMD$2.L;
  12702. var R = CMD$2.R;
  12703. var A = CMD$2.A;
  12704. var Q = CMD$2.Q;
  12705. for (i = 0, j = 0; i < len;) {
  12706. cmd = data[i++];
  12707. j = i;
  12708. nPoint = 0;
  12709. switch (cmd) {
  12710. case M:
  12711. nPoint = 1;
  12712. break;
  12713. case L:
  12714. nPoint = 1;
  12715. break;
  12716. case C:
  12717. nPoint = 3;
  12718. break;
  12719. case Q:
  12720. nPoint = 2;
  12721. break;
  12722. case A:
  12723. var x = m[4];
  12724. var y = m[5];
  12725. var sx = mathSqrt$1(m[0] * m[0] + m[1] * m[1]);
  12726. var sy = mathSqrt$1(m[2] * m[2] + m[3] * m[3]);
  12727. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12728. data[i] *= sx;
  12729. data[i++] += x;
  12730. data[i] *= sy;
  12731. data[i++] += y;
  12732. data[i++] *= sx;
  12733. data[i++] *= sy;
  12734. data[i++] += angle;
  12735. data[i++] += angle;
  12736. i += 2;
  12737. j = i;
  12738. break;
  12739. case R:
  12740. p[0] = data[i++];
  12741. p[1] = data[i++];
  12742. applyTransform(p, p, m);
  12743. data[j++] = p[0];
  12744. data[j++] = p[1];
  12745. p[0] += data[i++];
  12746. p[1] += data[i++];
  12747. applyTransform(p, p, m);
  12748. data[j++] = p[0];
  12749. data[j++] = p[1];
  12750. }
  12751. for (k = 0; k < nPoint; k++) {
  12752. var p_1 = points[k];
  12753. p_1[0] = data[i++];
  12754. p_1[1] = data[i++];
  12755. applyTransform(p_1, p_1, m);
  12756. data[j++] = p_1[0];
  12757. data[j++] = p_1[1];
  12758. }
  12759. }
  12760. path.increaseVersion();
  12761. }
  12762. var mathSqrt$2 = Math.sqrt;
  12763. var mathSin$2 = Math.sin;
  12764. var mathCos$2 = Math.cos;
  12765. var PI$1 = Math.PI;
  12766. function vMag(v) {
  12767. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12768. }
  12769. function vRatio(u, v) {
  12770. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12771. }
  12772. function vAngle(u, v) {
  12773. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12774. * Math.acos(vRatio(u, v));
  12775. }
  12776. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12777. var psi = psiDeg * (PI$1 / 180.0);
  12778. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12779. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12780. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12781. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12782. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12783. if (lambda > 1) {
  12784. rx *= mathSqrt$2(lambda);
  12785. ry *= mathSqrt$2(lambda);
  12786. }
  12787. var f = (fa === fs ? -1 : 1)
  12788. * mathSqrt$2((((rx * rx) * (ry * ry))
  12789. - ((rx * rx) * (yp * yp))
  12790. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12791. + (ry * ry) * (xp * xp))) || 0;
  12792. var cxp = f * rx * yp / ry;
  12793. var cyp = f * -ry * xp / rx;
  12794. var cx = (x1 + x2) / 2.0
  12795. + mathCos$2(psi) * cxp
  12796. - mathSin$2(psi) * cyp;
  12797. var cy = (y1 + y2) / 2.0
  12798. + mathSin$2(psi) * cxp
  12799. + mathCos$2(psi) * cyp;
  12800. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12801. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12802. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12803. var dTheta = vAngle(u, v);
  12804. if (vRatio(u, v) <= -1) {
  12805. dTheta = PI$1;
  12806. }
  12807. if (vRatio(u, v) >= 1) {
  12808. dTheta = 0;
  12809. }
  12810. if (dTheta < 0) {
  12811. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12812. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12813. }
  12814. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12815. }
  12816. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12817. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12818. function createPathProxyFromString(data) {
  12819. var path = new PathProxy();
  12820. if (!data) {
  12821. return path;
  12822. }
  12823. var cpx = 0;
  12824. var cpy = 0;
  12825. var subpathX = cpx;
  12826. var subpathY = cpy;
  12827. var prevCmd;
  12828. var CMD = PathProxy.CMD;
  12829. var cmdList = data.match(commandReg);
  12830. if (!cmdList) {
  12831. return path;
  12832. }
  12833. for (var l = 0; l < cmdList.length; l++) {
  12834. var cmdText = cmdList[l];
  12835. var cmdStr = cmdText.charAt(0);
  12836. var cmd = void 0;
  12837. var p = cmdText.match(numberReg) || [];
  12838. var pLen = p.length;
  12839. for (var i = 0; i < pLen; i++) {
  12840. p[i] = parseFloat(p[i]);
  12841. }
  12842. var off = 0;
  12843. while (off < pLen) {
  12844. var ctlPtx = void 0;
  12845. var ctlPty = void 0;
  12846. var rx = void 0;
  12847. var ry = void 0;
  12848. var psi = void 0;
  12849. var fa = void 0;
  12850. var fs = void 0;
  12851. var x1 = cpx;
  12852. var y1 = cpy;
  12853. var len = void 0;
  12854. var pathData = void 0;
  12855. switch (cmdStr) {
  12856. case 'l':
  12857. cpx += p[off++];
  12858. cpy += p[off++];
  12859. cmd = CMD.L;
  12860. path.addData(cmd, cpx, cpy);
  12861. break;
  12862. case 'L':
  12863. cpx = p[off++];
  12864. cpy = p[off++];
  12865. cmd = CMD.L;
  12866. path.addData(cmd, cpx, cpy);
  12867. break;
  12868. case 'm':
  12869. cpx += p[off++];
  12870. cpy += p[off++];
  12871. cmd = CMD.M;
  12872. path.addData(cmd, cpx, cpy);
  12873. subpathX = cpx;
  12874. subpathY = cpy;
  12875. cmdStr = 'l';
  12876. break;
  12877. case 'M':
  12878. cpx = p[off++];
  12879. cpy = p[off++];
  12880. cmd = CMD.M;
  12881. path.addData(cmd, cpx, cpy);
  12882. subpathX = cpx;
  12883. subpathY = cpy;
  12884. cmdStr = 'L';
  12885. break;
  12886. case 'h':
  12887. cpx += p[off++];
  12888. cmd = CMD.L;
  12889. path.addData(cmd, cpx, cpy);
  12890. break;
  12891. case 'H':
  12892. cpx = p[off++];
  12893. cmd = CMD.L;
  12894. path.addData(cmd, cpx, cpy);
  12895. break;
  12896. case 'v':
  12897. cpy += p[off++];
  12898. cmd = CMD.L;
  12899. path.addData(cmd, cpx, cpy);
  12900. break;
  12901. case 'V':
  12902. cpy = p[off++];
  12903. cmd = CMD.L;
  12904. path.addData(cmd, cpx, cpy);
  12905. break;
  12906. case 'C':
  12907. cmd = CMD.C;
  12908. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12909. cpx = p[off - 2];
  12910. cpy = p[off - 1];
  12911. break;
  12912. case 'c':
  12913. cmd = CMD.C;
  12914. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12915. cpx += p[off - 2];
  12916. cpy += p[off - 1];
  12917. break;
  12918. case 'S':
  12919. ctlPtx = cpx;
  12920. ctlPty = cpy;
  12921. len = path.len();
  12922. pathData = path.data;
  12923. if (prevCmd === CMD.C) {
  12924. ctlPtx += cpx - pathData[len - 4];
  12925. ctlPty += cpy - pathData[len - 3];
  12926. }
  12927. cmd = CMD.C;
  12928. x1 = p[off++];
  12929. y1 = p[off++];
  12930. cpx = p[off++];
  12931. cpy = p[off++];
  12932. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12933. break;
  12934. case 's':
  12935. ctlPtx = cpx;
  12936. ctlPty = cpy;
  12937. len = path.len();
  12938. pathData = path.data;
  12939. if (prevCmd === CMD.C) {
  12940. ctlPtx += cpx - pathData[len - 4];
  12941. ctlPty += cpy - pathData[len - 3];
  12942. }
  12943. cmd = CMD.C;
  12944. x1 = cpx + p[off++];
  12945. y1 = cpy + p[off++];
  12946. cpx += p[off++];
  12947. cpy += p[off++];
  12948. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12949. break;
  12950. case 'Q':
  12951. x1 = p[off++];
  12952. y1 = p[off++];
  12953. cpx = p[off++];
  12954. cpy = p[off++];
  12955. cmd = CMD.Q;
  12956. path.addData(cmd, x1, y1, cpx, cpy);
  12957. break;
  12958. case 'q':
  12959. x1 = p[off++] + cpx;
  12960. y1 = p[off++] + cpy;
  12961. cpx += p[off++];
  12962. cpy += p[off++];
  12963. cmd = CMD.Q;
  12964. path.addData(cmd, x1, y1, cpx, cpy);
  12965. break;
  12966. case 'T':
  12967. ctlPtx = cpx;
  12968. ctlPty = cpy;
  12969. len = path.len();
  12970. pathData = path.data;
  12971. if (prevCmd === CMD.Q) {
  12972. ctlPtx += cpx - pathData[len - 4];
  12973. ctlPty += cpy - pathData[len - 3];
  12974. }
  12975. cpx = p[off++];
  12976. cpy = p[off++];
  12977. cmd = CMD.Q;
  12978. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12979. break;
  12980. case 't':
  12981. ctlPtx = cpx;
  12982. ctlPty = cpy;
  12983. len = path.len();
  12984. pathData = path.data;
  12985. if (prevCmd === CMD.Q) {
  12986. ctlPtx += cpx - pathData[len - 4];
  12987. ctlPty += cpy - pathData[len - 3];
  12988. }
  12989. cpx += p[off++];
  12990. cpy += p[off++];
  12991. cmd = CMD.Q;
  12992. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12993. break;
  12994. case 'A':
  12995. rx = p[off++];
  12996. ry = p[off++];
  12997. psi = p[off++];
  12998. fa = p[off++];
  12999. fs = p[off++];
  13000. x1 = cpx, y1 = cpy;
  13001. cpx = p[off++];
  13002. cpy = p[off++];
  13003. cmd = CMD.A;
  13004. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13005. break;
  13006. case 'a':
  13007. rx = p[off++];
  13008. ry = p[off++];
  13009. psi = p[off++];
  13010. fa = p[off++];
  13011. fs = p[off++];
  13012. x1 = cpx, y1 = cpy;
  13013. cpx += p[off++];
  13014. cpy += p[off++];
  13015. cmd = CMD.A;
  13016. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  13017. break;
  13018. }
  13019. }
  13020. if (cmdStr === 'z' || cmdStr === 'Z') {
  13021. cmd = CMD.Z;
  13022. path.addData(cmd);
  13023. cpx = subpathX;
  13024. cpy = subpathY;
  13025. }
  13026. prevCmd = cmd;
  13027. }
  13028. path.toStatic();
  13029. return path;
  13030. }
  13031. var SVGPath = (function (_super) {
  13032. __extends(SVGPath, _super);
  13033. function SVGPath() {
  13034. return _super !== null && _super.apply(this, arguments) || this;
  13035. }
  13036. SVGPath.prototype.applyTransform = function (m) { };
  13037. return SVGPath;
  13038. }(Path));
  13039. function isPathProxy(path) {
  13040. return path.setData != null;
  13041. }
  13042. function createPathOptions(str, opts) {
  13043. var pathProxy = createPathProxyFromString(str);
  13044. var innerOpts = extend({}, opts);
  13045. innerOpts.buildPath = function (path) {
  13046. if (isPathProxy(path)) {
  13047. path.setData(pathProxy.data);
  13048. var ctx = path.getContext();
  13049. if (ctx) {
  13050. path.rebuildPath(ctx, 1);
  13051. }
  13052. }
  13053. else {
  13054. var ctx = path;
  13055. pathProxy.rebuildPath(ctx, 1);
  13056. }
  13057. };
  13058. innerOpts.applyTransform = function (m) {
  13059. transformPath(pathProxy, m);
  13060. this.dirtyShape();
  13061. };
  13062. return innerOpts;
  13063. }
  13064. function createFromString(str, opts) {
  13065. return new SVGPath(createPathOptions(str, opts));
  13066. }
  13067. function extendFromString(str, defaultOpts) {
  13068. var innerOpts = createPathOptions(str, defaultOpts);
  13069. var Sub = (function (_super) {
  13070. __extends(Sub, _super);
  13071. function Sub(opts) {
  13072. var _this = _super.call(this, opts) || this;
  13073. _this.applyTransform = innerOpts.applyTransform;
  13074. _this.buildPath = innerOpts.buildPath;
  13075. return _this;
  13076. }
  13077. return Sub;
  13078. }(SVGPath));
  13079. return Sub;
  13080. }
  13081. function mergePath(pathEls, opts) {
  13082. var pathList = [];
  13083. var len = pathEls.length;
  13084. for (var i = 0; i < len; i++) {
  13085. var pathEl = pathEls[i];
  13086. pathList.push(pathEl.getUpdatedPathProxy(true));
  13087. }
  13088. var pathBundle = new Path(opts);
  13089. pathBundle.createPathProxy();
  13090. pathBundle.buildPath = function (path) {
  13091. if (isPathProxy(path)) {
  13092. path.appendPath(pathList);
  13093. var ctx = path.getContext();
  13094. if (ctx) {
  13095. path.rebuildPath(ctx, 1);
  13096. }
  13097. }
  13098. };
  13099. return pathBundle;
  13100. }
  13101. function clonePath(sourcePath, opts) {
  13102. opts = opts || {};
  13103. var path = new Path();
  13104. if (sourcePath.shape) {
  13105. path.setShape(sourcePath.shape);
  13106. }
  13107. path.setStyle(sourcePath.style);
  13108. if (opts.bakeTransform) {
  13109. transformPath(path.path, sourcePath.getComputedTransform());
  13110. }
  13111. else {
  13112. if (opts.toLocal) {
  13113. path.setLocalTransform(sourcePath.getComputedTransform());
  13114. }
  13115. else {
  13116. path.copyTransform(sourcePath);
  13117. }
  13118. }
  13119. path.buildPath = sourcePath.buildPath;
  13120. path.applyTransform = path.applyTransform;
  13121. path.z = sourcePath.z;
  13122. path.z2 = sourcePath.z2;
  13123. path.zlevel = sourcePath.zlevel;
  13124. return path;
  13125. }
  13126. var CircleShape = (function () {
  13127. function CircleShape() {
  13128. this.cx = 0;
  13129. this.cy = 0;
  13130. this.r = 0;
  13131. }
  13132. return CircleShape;
  13133. }());
  13134. var Circle = (function (_super) {
  13135. __extends(Circle, _super);
  13136. function Circle(opts) {
  13137. return _super.call(this, opts) || this;
  13138. }
  13139. Circle.prototype.getDefaultShape = function () {
  13140. return new CircleShape();
  13141. };
  13142. Circle.prototype.buildPath = function (ctx, shape) {
  13143. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13144. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  13145. };
  13146. return Circle;
  13147. }(Path));
  13148. Circle.prototype.type = 'circle';
  13149. var EllipseShape = (function () {
  13150. function EllipseShape() {
  13151. this.cx = 0;
  13152. this.cy = 0;
  13153. this.rx = 0;
  13154. this.ry = 0;
  13155. }
  13156. return EllipseShape;
  13157. }());
  13158. var Ellipse = (function (_super) {
  13159. __extends(Ellipse, _super);
  13160. function Ellipse(opts) {
  13161. return _super.call(this, opts) || this;
  13162. }
  13163. Ellipse.prototype.getDefaultShape = function () {
  13164. return new EllipseShape();
  13165. };
  13166. Ellipse.prototype.buildPath = function (ctx, shape) {
  13167. var k = 0.5522848;
  13168. var x = shape.cx;
  13169. var y = shape.cy;
  13170. var a = shape.rx;
  13171. var b = shape.ry;
  13172. var ox = a * k;
  13173. var oy = b * k;
  13174. ctx.moveTo(x - a, y);
  13175. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  13176. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  13177. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  13178. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  13179. ctx.closePath();
  13180. };
  13181. return Ellipse;
  13182. }(Path));
  13183. Ellipse.prototype.type = 'ellipse';
  13184. var PI$2 = Math.PI;
  13185. var PI2$5 = PI$2 * 2;
  13186. var mathSin$3 = Math.sin;
  13187. var mathCos$3 = Math.cos;
  13188. var mathACos = Math.acos;
  13189. var mathATan2 = Math.atan2;
  13190. var mathAbs$1 = Math.abs;
  13191. var mathSqrt$3 = Math.sqrt;
  13192. var mathMax$3 = Math.max;
  13193. var mathMin$3 = Math.min;
  13194. var e = 1e-4;
  13195. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  13196. var dx10 = x1 - x0;
  13197. var dy10 = y1 - y0;
  13198. var dx32 = x3 - x2;
  13199. var dy32 = y3 - y2;
  13200. var t = dy32 * dx10 - dx32 * dy10;
  13201. if (t * t < e) {
  13202. return;
  13203. }
  13204. t = (dx32 * (y0 - y2) - dy32 * (x0 - x2)) / t;
  13205. return [x0 + t * dx10, y0 + t * dy10];
  13206. }
  13207. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  13208. var x01 = x0 - x1;
  13209. var y01 = y0 - y1;
  13210. var lo = (clockwise ? cr : -cr) / mathSqrt$3(x01 * x01 + y01 * y01);
  13211. var ox = lo * y01;
  13212. var oy = -lo * x01;
  13213. var x11 = x0 + ox;
  13214. var y11 = y0 + oy;
  13215. var x10 = x1 + ox;
  13216. var y10 = y1 + oy;
  13217. var x00 = (x11 + x10) / 2;
  13218. var y00 = (y11 + y10) / 2;
  13219. var dx = x10 - x11;
  13220. var dy = y10 - y11;
  13221. var d2 = dx * dx + dy * dy;
  13222. var r = radius - cr;
  13223. var s = x11 * y10 - x10 * y11;
  13224. var d = (dy < 0 ? -1 : 1) * mathSqrt$3(mathMax$3(0, r * r * d2 - s * s));
  13225. var cx0 = (s * dy - dx * d) / d2;
  13226. var cy0 = (-s * dx - dy * d) / d2;
  13227. var cx1 = (s * dy + dx * d) / d2;
  13228. var cy1 = (-s * dx + dy * d) / d2;
  13229. var dx0 = cx0 - x00;
  13230. var dy0 = cy0 - y00;
  13231. var dx1 = cx1 - x00;
  13232. var dy1 = cy1 - y00;
  13233. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  13234. cx0 = cx1;
  13235. cy0 = cy1;
  13236. }
  13237. return {
  13238. cx: cx0,
  13239. cy: cy0,
  13240. x0: -ox,
  13241. y0: -oy,
  13242. x1: cx0 * (radius / r - 1),
  13243. y1: cy0 * (radius / r - 1)
  13244. };
  13245. }
  13246. function normalizeCornerRadius(cr) {
  13247. var arr;
  13248. if (isArray(cr)) {
  13249. var len = cr.length;
  13250. if (!len) {
  13251. return cr;
  13252. }
  13253. if (len === 1) {
  13254. arr = [cr[0], cr[0], 0, 0];
  13255. }
  13256. else if (len === 2) {
  13257. arr = [cr[0], cr[0], cr[1], cr[1]];
  13258. }
  13259. else if (len === 3) {
  13260. arr = cr.concat(cr[2]);
  13261. }
  13262. else {
  13263. arr = cr;
  13264. }
  13265. }
  13266. else {
  13267. arr = [cr, cr, cr, cr];
  13268. }
  13269. return arr;
  13270. }
  13271. function buildPath$1(ctx, shape) {
  13272. var _a;
  13273. var radius = mathMax$3(shape.r, 0);
  13274. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  13275. var hasRadius = radius > 0;
  13276. var hasInnerRadius = innerRadius > 0;
  13277. if (!hasRadius && !hasInnerRadius) {
  13278. return;
  13279. }
  13280. if (!hasRadius) {
  13281. radius = innerRadius;
  13282. innerRadius = 0;
  13283. }
  13284. if (innerRadius > radius) {
  13285. var tmp = radius;
  13286. radius = innerRadius;
  13287. innerRadius = tmp;
  13288. }
  13289. var startAngle = shape.startAngle, endAngle = shape.endAngle;
  13290. if (isNaN(startAngle) || isNaN(endAngle)) {
  13291. return;
  13292. }
  13293. var cx = shape.cx, cy = shape.cy;
  13294. var clockwise = !!shape.clockwise;
  13295. var arc = mathAbs$1(endAngle - startAngle);
  13296. var mod = arc > PI2$5 && arc % PI2$5;
  13297. mod > e && (arc = mod);
  13298. if (!(radius > e)) {
  13299. ctx.moveTo(cx, cy);
  13300. }
  13301. else if (arc > PI2$5 - e) {
  13302. ctx.moveTo(cx + radius * mathCos$3(startAngle), cy + radius * mathSin$3(startAngle));
  13303. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13304. if (innerRadius > e) {
  13305. ctx.moveTo(cx + innerRadius * mathCos$3(endAngle), cy + innerRadius * mathSin$3(endAngle));
  13306. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13307. }
  13308. }
  13309. else {
  13310. var icrStart = void 0;
  13311. var icrEnd = void 0;
  13312. var ocrStart = void 0;
  13313. var ocrEnd = void 0;
  13314. var ocrs = void 0;
  13315. var ocre = void 0;
  13316. var icrs = void 0;
  13317. var icre = void 0;
  13318. var ocrMax = void 0;
  13319. var icrMax = void 0;
  13320. var limitedOcrMax = void 0;
  13321. var limitedIcrMax = void 0;
  13322. var xre = void 0;
  13323. var yre = void 0;
  13324. var xirs = void 0;
  13325. var yirs = void 0;
  13326. var xrs = radius * mathCos$3(startAngle);
  13327. var yrs = radius * mathSin$3(startAngle);
  13328. var xire = innerRadius * mathCos$3(endAngle);
  13329. var yire = innerRadius * mathSin$3(endAngle);
  13330. var hasArc = arc > e;
  13331. if (hasArc) {
  13332. var cornerRadius = shape.cornerRadius;
  13333. if (cornerRadius) {
  13334. _a = normalizeCornerRadius(cornerRadius), icrStart = _a[0], icrEnd = _a[1], ocrStart = _a[2], ocrEnd = _a[3];
  13335. }
  13336. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  13337. ocrs = mathMin$3(halfRd, ocrStart);
  13338. ocre = mathMin$3(halfRd, ocrEnd);
  13339. icrs = mathMin$3(halfRd, icrStart);
  13340. icre = mathMin$3(halfRd, icrEnd);
  13341. limitedOcrMax = ocrMax = mathMax$3(ocrs, ocre);
  13342. limitedIcrMax = icrMax = mathMax$3(icrs, icre);
  13343. if (ocrMax > e || icrMax > e) {
  13344. xre = radius * mathCos$3(endAngle);
  13345. yre = radius * mathSin$3(endAngle);
  13346. xirs = innerRadius * mathCos$3(startAngle);
  13347. yirs = innerRadius * mathSin$3(startAngle);
  13348. if (arc < PI$2) {
  13349. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  13350. if (it_1) {
  13351. var x0 = xrs - it_1[0];
  13352. var y0 = yrs - it_1[1];
  13353. var x1 = xre - it_1[0];
  13354. var y1 = yre - it_1[1];
  13355. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$3(x0 * x0 + y0 * y0) * mathSqrt$3(x1 * x1 + y1 * y1))) / 2);
  13356. var b = mathSqrt$3(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  13357. limitedOcrMax = mathMin$3(ocrMax, (radius - b) / (a + 1));
  13358. limitedIcrMax = mathMin$3(icrMax, (innerRadius - b) / (a - 1));
  13359. }
  13360. }
  13361. }
  13362. }
  13363. if (!hasArc) {
  13364. ctx.moveTo(cx + xrs, cy + yrs);
  13365. }
  13366. else if (limitedOcrMax > e) {
  13367. var crStart = mathMin$3(ocrStart, limitedOcrMax);
  13368. var crEnd = mathMin$3(ocrEnd, limitedOcrMax);
  13369. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, crStart, clockwise);
  13370. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, crEnd, clockwise);
  13371. ctx.moveTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13372. if (limitedOcrMax < ocrMax && crStart === crEnd) {
  13373. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedOcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13374. }
  13375. else {
  13376. crStart > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crStart, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13377. ctx.arc(cx, cy, radius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), !clockwise);
  13378. crEnd > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crEnd, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13379. }
  13380. }
  13381. else {
  13382. ctx.moveTo(cx + xrs, cy + yrs);
  13383. ctx.arc(cx, cy, radius, startAngle, endAngle, !clockwise);
  13384. }
  13385. if (!(innerRadius > e) || !hasArc) {
  13386. ctx.lineTo(cx + xire, cy + yire);
  13387. }
  13388. else if (limitedIcrMax > e) {
  13389. var crStart = mathMin$3(icrStart, limitedIcrMax);
  13390. var crEnd = mathMin$3(icrEnd, limitedIcrMax);
  13391. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -crEnd, clockwise);
  13392. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -crStart, clockwise);
  13393. ctx.lineTo(cx + ct0.cx + ct0.x0, cy + ct0.cy + ct0.y0);
  13394. if (limitedIcrMax < icrMax && crStart === crEnd) {
  13395. ctx.arc(cx + ct0.cx, cy + ct0.cy, limitedIcrMax, mathATan2(ct0.y0, ct0.x0), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13396. }
  13397. else {
  13398. crEnd > 0 && ctx.arc(cx + ct0.cx, cy + ct0.cy, crEnd, mathATan2(ct0.y0, ct0.x0), mathATan2(ct0.y1, ct0.x1), !clockwise);
  13399. ctx.arc(cx, cy, innerRadius, mathATan2(ct0.cy + ct0.y1, ct0.cx + ct0.x1), mathATan2(ct1.cy + ct1.y1, ct1.cx + ct1.x1), clockwise);
  13400. crStart > 0 && ctx.arc(cx + ct1.cx, cy + ct1.cy, crStart, mathATan2(ct1.y1, ct1.x1), mathATan2(ct1.y0, ct1.x0), !clockwise);
  13401. }
  13402. }
  13403. else {
  13404. ctx.lineTo(cx + xire, cy + yire);
  13405. ctx.arc(cx, cy, innerRadius, endAngle, startAngle, clockwise);
  13406. }
  13407. }
  13408. ctx.closePath();
  13409. }
  13410. var SectorShape = (function () {
  13411. function SectorShape() {
  13412. this.cx = 0;
  13413. this.cy = 0;
  13414. this.r0 = 0;
  13415. this.r = 0;
  13416. this.startAngle = 0;
  13417. this.endAngle = Math.PI * 2;
  13418. this.clockwise = true;
  13419. this.cornerRadius = 0;
  13420. }
  13421. return SectorShape;
  13422. }());
  13423. var Sector = (function (_super) {
  13424. __extends(Sector, _super);
  13425. function Sector(opts) {
  13426. return _super.call(this, opts) || this;
  13427. }
  13428. Sector.prototype.getDefaultShape = function () {
  13429. return new SectorShape();
  13430. };
  13431. Sector.prototype.buildPath = function (ctx, shape) {
  13432. buildPath$1(ctx, shape);
  13433. };
  13434. Sector.prototype.isZeroArea = function () {
  13435. return this.shape.startAngle === this.shape.endAngle
  13436. || this.shape.r === this.shape.r0;
  13437. };
  13438. return Sector;
  13439. }(Path));
  13440. Sector.prototype.type = 'sector';
  13441. var RingShape = (function () {
  13442. function RingShape() {
  13443. this.cx = 0;
  13444. this.cy = 0;
  13445. this.r = 0;
  13446. this.r0 = 0;
  13447. }
  13448. return RingShape;
  13449. }());
  13450. var Ring = (function (_super) {
  13451. __extends(Ring, _super);
  13452. function Ring(opts) {
  13453. return _super.call(this, opts) || this;
  13454. }
  13455. Ring.prototype.getDefaultShape = function () {
  13456. return new RingShape();
  13457. };
  13458. Ring.prototype.buildPath = function (ctx, shape) {
  13459. var x = shape.cx;
  13460. var y = shape.cy;
  13461. var PI2 = Math.PI * 2;
  13462. ctx.moveTo(x + shape.r, y);
  13463. ctx.arc(x, y, shape.r, 0, PI2, false);
  13464. ctx.moveTo(x + shape.r0, y);
  13465. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13466. };
  13467. return Ring;
  13468. }(Path));
  13469. Ring.prototype.type = 'ring';
  13470. function smoothBezier(points, smooth, isLoop, constraint) {
  13471. var cps = [];
  13472. var v = [];
  13473. var v1 = [];
  13474. var v2 = [];
  13475. var prevPoint;
  13476. var nextPoint;
  13477. var min$1;
  13478. var max$1;
  13479. if (constraint) {
  13480. min$1 = [Infinity, Infinity];
  13481. max$1 = [-Infinity, -Infinity];
  13482. for (var i = 0, len = points.length; i < len; i++) {
  13483. min(min$1, min$1, points[i]);
  13484. max(max$1, max$1, points[i]);
  13485. }
  13486. min(min$1, min$1, constraint[0]);
  13487. max(max$1, max$1, constraint[1]);
  13488. }
  13489. for (var i = 0, len = points.length; i < len; i++) {
  13490. var point = points[i];
  13491. if (isLoop) {
  13492. prevPoint = points[i ? i - 1 : len - 1];
  13493. nextPoint = points[(i + 1) % len];
  13494. }
  13495. else {
  13496. if (i === 0 || i === len - 1) {
  13497. cps.push(clone$1(points[i]));
  13498. continue;
  13499. }
  13500. else {
  13501. prevPoint = points[i - 1];
  13502. nextPoint = points[i + 1];
  13503. }
  13504. }
  13505. sub(v, nextPoint, prevPoint);
  13506. scale(v, v, smooth);
  13507. var d0 = distance(point, prevPoint);
  13508. var d1 = distance(point, nextPoint);
  13509. var sum = d0 + d1;
  13510. if (sum !== 0) {
  13511. d0 /= sum;
  13512. d1 /= sum;
  13513. }
  13514. scale(v1, v, -d0);
  13515. scale(v2, v, d1);
  13516. var cp0 = add([], point, v1);
  13517. var cp1 = add([], point, v2);
  13518. if (constraint) {
  13519. max(cp0, cp0, min$1);
  13520. min(cp0, cp0, max$1);
  13521. max(cp1, cp1, min$1);
  13522. min(cp1, cp1, max$1);
  13523. }
  13524. cps.push(cp0);
  13525. cps.push(cp1);
  13526. }
  13527. if (isLoop) {
  13528. cps.push(cps.shift());
  13529. }
  13530. return cps;
  13531. }
  13532. function buildPath$2(ctx, shape, closePath) {
  13533. var smooth = shape.smooth;
  13534. var points = shape.points;
  13535. if (points && points.length >= 2) {
  13536. if (smooth) {
  13537. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13538. ctx.moveTo(points[0][0], points[0][1]);
  13539. var len = points.length;
  13540. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13541. var cp1 = controlPoints[i * 2];
  13542. var cp2 = controlPoints[i * 2 + 1];
  13543. var p = points[(i + 1) % len];
  13544. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13545. }
  13546. }
  13547. else {
  13548. ctx.moveTo(points[0][0], points[0][1]);
  13549. for (var i = 1, l = points.length; i < l; i++) {
  13550. ctx.lineTo(points[i][0], points[i][1]);
  13551. }
  13552. }
  13553. closePath && ctx.closePath();
  13554. }
  13555. }
  13556. var PolygonShape = (function () {
  13557. function PolygonShape() {
  13558. this.points = null;
  13559. this.smooth = 0;
  13560. this.smoothConstraint = null;
  13561. }
  13562. return PolygonShape;
  13563. }());
  13564. var Polygon = (function (_super) {
  13565. __extends(Polygon, _super);
  13566. function Polygon(opts) {
  13567. return _super.call(this, opts) || this;
  13568. }
  13569. Polygon.prototype.getDefaultShape = function () {
  13570. return new PolygonShape();
  13571. };
  13572. Polygon.prototype.buildPath = function (ctx, shape) {
  13573. buildPath$2(ctx, shape, true);
  13574. };
  13575. return Polygon;
  13576. }(Path));
  13577. Polygon.prototype.type = 'polygon';
  13578. var PolylineShape = (function () {
  13579. function PolylineShape() {
  13580. this.points = null;
  13581. this.percent = 1;
  13582. this.smooth = 0;
  13583. this.smoothConstraint = null;
  13584. }
  13585. return PolylineShape;
  13586. }());
  13587. var Polyline = (function (_super) {
  13588. __extends(Polyline, _super);
  13589. function Polyline(opts) {
  13590. return _super.call(this, opts) || this;
  13591. }
  13592. Polyline.prototype.getDefaultStyle = function () {
  13593. return {
  13594. stroke: '#000',
  13595. fill: null
  13596. };
  13597. };
  13598. Polyline.prototype.getDefaultShape = function () {
  13599. return new PolylineShape();
  13600. };
  13601. Polyline.prototype.buildPath = function (ctx, shape) {
  13602. buildPath$2(ctx, shape, false);
  13603. };
  13604. return Polyline;
  13605. }(Path));
  13606. Polyline.prototype.type = 'polyline';
  13607. var subPixelOptimizeOutputShape$1 = {};
  13608. var LineShape = (function () {
  13609. function LineShape() {
  13610. this.x1 = 0;
  13611. this.y1 = 0;
  13612. this.x2 = 0;
  13613. this.y2 = 0;
  13614. this.percent = 1;
  13615. }
  13616. return LineShape;
  13617. }());
  13618. var Line = (function (_super) {
  13619. __extends(Line, _super);
  13620. function Line(opts) {
  13621. return _super.call(this, opts) || this;
  13622. }
  13623. Line.prototype.getDefaultStyle = function () {
  13624. return {
  13625. stroke: '#000',
  13626. fill: null
  13627. };
  13628. };
  13629. Line.prototype.getDefaultShape = function () {
  13630. return new LineShape();
  13631. };
  13632. Line.prototype.buildPath = function (ctx, shape) {
  13633. var x1;
  13634. var y1;
  13635. var x2;
  13636. var y2;
  13637. if (this.subPixelOptimize) {
  13638. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13639. x1 = optimizedShape.x1;
  13640. y1 = optimizedShape.y1;
  13641. x2 = optimizedShape.x2;
  13642. y2 = optimizedShape.y2;
  13643. }
  13644. else {
  13645. x1 = shape.x1;
  13646. y1 = shape.y1;
  13647. x2 = shape.x2;
  13648. y2 = shape.y2;
  13649. }
  13650. var percent = shape.percent;
  13651. if (percent === 0) {
  13652. return;
  13653. }
  13654. ctx.moveTo(x1, y1);
  13655. if (percent < 1) {
  13656. x2 = x1 * (1 - percent) + x2 * percent;
  13657. y2 = y1 * (1 - percent) + y2 * percent;
  13658. }
  13659. ctx.lineTo(x2, y2);
  13660. };
  13661. Line.prototype.pointAt = function (p) {
  13662. var shape = this.shape;
  13663. return [
  13664. shape.x1 * (1 - p) + shape.x2 * p,
  13665. shape.y1 * (1 - p) + shape.y2 * p
  13666. ];
  13667. };
  13668. return Line;
  13669. }(Path));
  13670. Line.prototype.type = 'line';
  13671. var out = [];
  13672. var BezierCurveShape = (function () {
  13673. function BezierCurveShape() {
  13674. this.x1 = 0;
  13675. this.y1 = 0;
  13676. this.x2 = 0;
  13677. this.y2 = 0;
  13678. this.cpx1 = 0;
  13679. this.cpy1 = 0;
  13680. this.percent = 1;
  13681. }
  13682. return BezierCurveShape;
  13683. }());
  13684. function someVectorAt(shape, t, isTangent) {
  13685. var cpx2 = shape.cpx2;
  13686. var cpy2 = shape.cpy2;
  13687. if (cpx2 != null || cpy2 != null) {
  13688. return [
  13689. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13690. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13691. ];
  13692. }
  13693. else {
  13694. return [
  13695. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13696. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13697. ];
  13698. }
  13699. }
  13700. var BezierCurve = (function (_super) {
  13701. __extends(BezierCurve, _super);
  13702. function BezierCurve(opts) {
  13703. return _super.call(this, opts) || this;
  13704. }
  13705. BezierCurve.prototype.getDefaultStyle = function () {
  13706. return {
  13707. stroke: '#000',
  13708. fill: null
  13709. };
  13710. };
  13711. BezierCurve.prototype.getDefaultShape = function () {
  13712. return new BezierCurveShape();
  13713. };
  13714. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13715. var x1 = shape.x1;
  13716. var y1 = shape.y1;
  13717. var x2 = shape.x2;
  13718. var y2 = shape.y2;
  13719. var cpx1 = shape.cpx1;
  13720. var cpy1 = shape.cpy1;
  13721. var cpx2 = shape.cpx2;
  13722. var cpy2 = shape.cpy2;
  13723. var percent = shape.percent;
  13724. if (percent === 0) {
  13725. return;
  13726. }
  13727. ctx.moveTo(x1, y1);
  13728. if (cpx2 == null || cpy2 == null) {
  13729. if (percent < 1) {
  13730. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13731. cpx1 = out[1];
  13732. x2 = out[2];
  13733. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13734. cpy1 = out[1];
  13735. y2 = out[2];
  13736. }
  13737. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13738. }
  13739. else {
  13740. if (percent < 1) {
  13741. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13742. cpx1 = out[1];
  13743. cpx2 = out[2];
  13744. x2 = out[3];
  13745. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13746. cpy1 = out[1];
  13747. cpy2 = out[2];
  13748. y2 = out[3];
  13749. }
  13750. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13751. }
  13752. };
  13753. BezierCurve.prototype.pointAt = function (t) {
  13754. return someVectorAt(this.shape, t, false);
  13755. };
  13756. BezierCurve.prototype.tangentAt = function (t) {
  13757. var p = someVectorAt(this.shape, t, true);
  13758. return normalize(p, p);
  13759. };
  13760. return BezierCurve;
  13761. }(Path));
  13762. BezierCurve.prototype.type = 'bezier-curve';
  13763. var ArcShape = (function () {
  13764. function ArcShape() {
  13765. this.cx = 0;
  13766. this.cy = 0;
  13767. this.r = 0;
  13768. this.startAngle = 0;
  13769. this.endAngle = Math.PI * 2;
  13770. this.clockwise = true;
  13771. }
  13772. return ArcShape;
  13773. }());
  13774. var Arc = (function (_super) {
  13775. __extends(Arc, _super);
  13776. function Arc(opts) {
  13777. return _super.call(this, opts) || this;
  13778. }
  13779. Arc.prototype.getDefaultStyle = function () {
  13780. return {
  13781. stroke: '#000',
  13782. fill: null
  13783. };
  13784. };
  13785. Arc.prototype.getDefaultShape = function () {
  13786. return new ArcShape();
  13787. };
  13788. Arc.prototype.buildPath = function (ctx, shape) {
  13789. var x = shape.cx;
  13790. var y = shape.cy;
  13791. var r = Math.max(shape.r, 0);
  13792. var startAngle = shape.startAngle;
  13793. var endAngle = shape.endAngle;
  13794. var clockwise = shape.clockwise;
  13795. var unitX = Math.cos(startAngle);
  13796. var unitY = Math.sin(startAngle);
  13797. ctx.moveTo(unitX * r + x, unitY * r + y);
  13798. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13799. };
  13800. return Arc;
  13801. }(Path));
  13802. Arc.prototype.type = 'arc';
  13803. var CompoundPath = (function (_super) {
  13804. __extends(CompoundPath, _super);
  13805. function CompoundPath() {
  13806. var _this = _super !== null && _super.apply(this, arguments) || this;
  13807. _this.type = 'compound';
  13808. return _this;
  13809. }
  13810. CompoundPath.prototype._updatePathDirty = function () {
  13811. var paths = this.shape.paths;
  13812. var dirtyPath = this.shapeChanged();
  13813. for (var i = 0; i < paths.length; i++) {
  13814. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13815. }
  13816. if (dirtyPath) {
  13817. this.dirtyShape();
  13818. }
  13819. };
  13820. CompoundPath.prototype.beforeBrush = function () {
  13821. this._updatePathDirty();
  13822. var paths = this.shape.paths || [];
  13823. var scale = this.getGlobalScale();
  13824. for (var i = 0; i < paths.length; i++) {
  13825. if (!paths[i].path) {
  13826. paths[i].createPathProxy();
  13827. }
  13828. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13829. }
  13830. };
  13831. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13832. var paths = shape.paths || [];
  13833. for (var i = 0; i < paths.length; i++) {
  13834. paths[i].buildPath(ctx, paths[i].shape, true);
  13835. }
  13836. };
  13837. CompoundPath.prototype.afterBrush = function () {
  13838. var paths = this.shape.paths || [];
  13839. for (var i = 0; i < paths.length; i++) {
  13840. paths[i].pathUpdated();
  13841. }
  13842. };
  13843. CompoundPath.prototype.getBoundingRect = function () {
  13844. this._updatePathDirty.call(this);
  13845. return Path.prototype.getBoundingRect.call(this);
  13846. };
  13847. return CompoundPath;
  13848. }(Path));
  13849. var Gradient = (function () {
  13850. function Gradient(colorStops) {
  13851. this.colorStops = colorStops || [];
  13852. }
  13853. Gradient.prototype.addColorStop = function (offset, color) {
  13854. this.colorStops.push({
  13855. offset: offset,
  13856. color: color
  13857. });
  13858. };
  13859. return Gradient;
  13860. }());
  13861. var LinearGradient = (function (_super) {
  13862. __extends(LinearGradient, _super);
  13863. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13864. var _this = _super.call(this, colorStops) || this;
  13865. _this.x = x == null ? 0 : x;
  13866. _this.y = y == null ? 0 : y;
  13867. _this.x2 = x2 == null ? 1 : x2;
  13868. _this.y2 = y2 == null ? 0 : y2;
  13869. _this.type = 'linear';
  13870. _this.global = globalCoord || false;
  13871. return _this;
  13872. }
  13873. return LinearGradient;
  13874. }(Gradient));
  13875. var RadialGradient = (function (_super) {
  13876. __extends(RadialGradient, _super);
  13877. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13878. var _this = _super.call(this, colorStops) || this;
  13879. _this.x = x == null ? 0.5 : x;
  13880. _this.y = y == null ? 0.5 : y;
  13881. _this.r = r == null ? 0.5 : r;
  13882. _this.type = 'radial';
  13883. _this.global = globalCoord || false;
  13884. return _this;
  13885. }
  13886. return RadialGradient;
  13887. }(Gradient));
  13888. var extent = [0, 0];
  13889. var extent2 = [0, 0];
  13890. var minTv$1 = new Point();
  13891. var maxTv$1 = new Point();
  13892. var OrientedBoundingRect = (function () {
  13893. function OrientedBoundingRect(rect, transform) {
  13894. this._corners = [];
  13895. this._axes = [];
  13896. this._origin = [0, 0];
  13897. for (var i = 0; i < 4; i++) {
  13898. this._corners[i] = new Point();
  13899. }
  13900. for (var i = 0; i < 2; i++) {
  13901. this._axes[i] = new Point();
  13902. }
  13903. if (rect) {
  13904. this.fromBoundingRect(rect, transform);
  13905. }
  13906. }
  13907. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13908. var corners = this._corners;
  13909. var axes = this._axes;
  13910. var x = rect.x;
  13911. var y = rect.y;
  13912. var x2 = x + rect.width;
  13913. var y2 = y + rect.height;
  13914. corners[0].set(x, y);
  13915. corners[1].set(x2, y);
  13916. corners[2].set(x2, y2);
  13917. corners[3].set(x, y2);
  13918. if (transform) {
  13919. for (var i = 0; i < 4; i++) {
  13920. corners[i].transform(transform);
  13921. }
  13922. }
  13923. Point.sub(axes[0], corners[1], corners[0]);
  13924. Point.sub(axes[1], corners[3], corners[0]);
  13925. axes[0].normalize();
  13926. axes[1].normalize();
  13927. for (var i = 0; i < 2; i++) {
  13928. this._origin[i] = axes[i].dot(corners[0]);
  13929. }
  13930. };
  13931. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13932. var overlapped = true;
  13933. var noMtv = !mtv;
  13934. minTv$1.set(Infinity, Infinity);
  13935. maxTv$1.set(0, 0);
  13936. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13937. overlapped = false;
  13938. if (noMtv) {
  13939. return overlapped;
  13940. }
  13941. }
  13942. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13943. overlapped = false;
  13944. if (noMtv) {
  13945. return overlapped;
  13946. }
  13947. }
  13948. if (!noMtv) {
  13949. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13950. }
  13951. return overlapped;
  13952. };
  13953. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13954. var overlapped = true;
  13955. for (var i = 0; i < 2; i++) {
  13956. var axis = this._axes[i];
  13957. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13958. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13959. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13960. overlapped = false;
  13961. if (noMtv) {
  13962. return overlapped;
  13963. }
  13964. var dist0 = Math.abs(extent2[0] - extent[1]);
  13965. var dist1 = Math.abs(extent[0] - extent2[1]);
  13966. if (Math.min(dist0, dist1) > maxTv.len()) {
  13967. if (dist0 < dist1) {
  13968. Point.scale(maxTv, axis, -dist0 * inverse);
  13969. }
  13970. else {
  13971. Point.scale(maxTv, axis, dist1 * inverse);
  13972. }
  13973. }
  13974. }
  13975. else if (minTv) {
  13976. var dist0 = Math.abs(extent2[0] - extent[1]);
  13977. var dist1 = Math.abs(extent[0] - extent2[1]);
  13978. if (Math.min(dist0, dist1) < minTv.len()) {
  13979. if (dist0 < dist1) {
  13980. Point.scale(minTv, axis, dist0 * inverse);
  13981. }
  13982. else {
  13983. Point.scale(minTv, axis, -dist1 * inverse);
  13984. }
  13985. }
  13986. }
  13987. }
  13988. return overlapped;
  13989. };
  13990. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13991. var axis = this._axes[dim];
  13992. var origin = this._origin;
  13993. var proj = corners[0].dot(axis) + origin[dim];
  13994. var min = proj;
  13995. var max = proj;
  13996. for (var i = 1; i < corners.length; i++) {
  13997. var proj_1 = corners[i].dot(axis) + origin[dim];
  13998. min = Math.min(proj_1, min);
  13999. max = Math.max(proj_1, max);
  14000. }
  14001. out[0] = min;
  14002. out[1] = max;
  14003. };
  14004. return OrientedBoundingRect;
  14005. }());
  14006. var m = [];
  14007. var IncrementalDisplayable = (function (_super) {
  14008. __extends(IncrementalDisplayable, _super);
  14009. function IncrementalDisplayable() {
  14010. var _this = _super !== null && _super.apply(this, arguments) || this;
  14011. _this.notClear = true;
  14012. _this.incremental = true;
  14013. _this._displayables = [];
  14014. _this._temporaryDisplayables = [];
  14015. _this._cursor = 0;
  14016. return _this;
  14017. }
  14018. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  14019. cb.call(context, this);
  14020. };
  14021. IncrementalDisplayable.prototype.useStyle = function () {
  14022. this.style = {};
  14023. };
  14024. IncrementalDisplayable.prototype.getCursor = function () {
  14025. return this._cursor;
  14026. };
  14027. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  14028. this._cursor = this._displayables.length;
  14029. };
  14030. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  14031. this._displayables = [];
  14032. this._temporaryDisplayables = [];
  14033. this._cursor = 0;
  14034. this.markRedraw();
  14035. this.notClear = false;
  14036. };
  14037. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  14038. this._temporaryDisplayables = [];
  14039. };
  14040. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  14041. if (notPersistent) {
  14042. this._temporaryDisplayables.push(displayable);
  14043. }
  14044. else {
  14045. this._displayables.push(displayable);
  14046. }
  14047. this.markRedraw();
  14048. };
  14049. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  14050. notPersistent = notPersistent || false;
  14051. for (var i = 0; i < displayables.length; i++) {
  14052. this.addDisplayable(displayables[i], notPersistent);
  14053. }
  14054. };
  14055. IncrementalDisplayable.prototype.getDisplayables = function () {
  14056. return this._displayables;
  14057. };
  14058. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  14059. return this._temporaryDisplayables;
  14060. };
  14061. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  14062. for (var i = this._cursor; i < this._displayables.length; i++) {
  14063. cb && cb(this._displayables[i]);
  14064. }
  14065. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14066. cb && cb(this._temporaryDisplayables[i]);
  14067. }
  14068. };
  14069. IncrementalDisplayable.prototype.update = function () {
  14070. this.updateTransform();
  14071. for (var i = this._cursor; i < this._displayables.length; i++) {
  14072. var displayable = this._displayables[i];
  14073. displayable.parent = this;
  14074. displayable.update();
  14075. displayable.parent = null;
  14076. }
  14077. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  14078. var displayable = this._temporaryDisplayables[i];
  14079. displayable.parent = this;
  14080. displayable.update();
  14081. displayable.parent = null;
  14082. }
  14083. };
  14084. IncrementalDisplayable.prototype.getBoundingRect = function () {
  14085. if (!this._rect) {
  14086. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  14087. for (var i = 0; i < this._displayables.length; i++) {
  14088. var displayable = this._displayables[i];
  14089. var childRect = displayable.getBoundingRect().clone();
  14090. if (displayable.needLocalTransform()) {
  14091. childRect.applyTransform(displayable.getLocalTransform(m));
  14092. }
  14093. rect.union(childRect);
  14094. }
  14095. this._rect = rect;
  14096. }
  14097. return this._rect;
  14098. };
  14099. IncrementalDisplayable.prototype.contain = function (x, y) {
  14100. var localPos = this.transformCoordToLocal(x, y);
  14101. var rect = this.getBoundingRect();
  14102. if (rect.contain(localPos[0], localPos[1])) {
  14103. for (var i = 0; i < this._displayables.length; i++) {
  14104. var displayable = this._displayables[i];
  14105. if (displayable.contain(x, y)) {
  14106. return true;
  14107. }
  14108. }
  14109. }
  14110. return false;
  14111. };
  14112. return IncrementalDisplayable;
  14113. }(Displayable));
  14114. var transitionStore = makeInner();
  14115. /**
  14116. * Return null if animation is disabled.
  14117. */
  14118. function getAnimationConfig(animationType, animatableModel, dataIndex, // Extra opts can override the option in animatable model.
  14119. extraOpts, // TODO It's only for pictorial bar now.
  14120. extraDelayParams) {
  14121. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  14122. // If animation is enabled. Will use this animation config in payload.
  14123. // If animation is disabled. Just ignore it.
  14124. if (animatableModel && animatableModel.ecModel) {
  14125. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  14126. animationPayload = updatePayload && updatePayload.animation;
  14127. }
  14128. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14129. var isUpdate = animationType === 'update';
  14130. if (animationEnabled) {
  14131. var duration = void 0;
  14132. var easing = void 0;
  14133. var delay = void 0;
  14134. if (extraOpts) {
  14135. duration = retrieve2(extraOpts.duration, 200);
  14136. easing = retrieve2(extraOpts.easing, 'cubicOut');
  14137. delay = 0;
  14138. } else {
  14139. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  14140. easing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  14141. delay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  14142. } // animation from payload has highest priority.
  14143. if (animationPayload) {
  14144. animationPayload.duration != null && (duration = animationPayload.duration);
  14145. animationPayload.easing != null && (easing = animationPayload.easing);
  14146. animationPayload.delay != null && (delay = animationPayload.delay);
  14147. }
  14148. if (isFunction(delay)) {
  14149. delay = delay(dataIndex, extraDelayParams);
  14150. }
  14151. if (isFunction(duration)) {
  14152. duration = duration(dataIndex);
  14153. }
  14154. var config = {
  14155. duration: duration || 0,
  14156. delay: delay,
  14157. easing: easing
  14158. };
  14159. return config;
  14160. } else {
  14161. return null;
  14162. }
  14163. }
  14164. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  14165. var isFrom = false;
  14166. var removeOpt;
  14167. if (isFunction(dataIndex)) {
  14168. during = cb;
  14169. cb = dataIndex;
  14170. dataIndex = null;
  14171. } else if (isObject(dataIndex)) {
  14172. cb = dataIndex.cb;
  14173. during = dataIndex.during;
  14174. isFrom = dataIndex.isFrom;
  14175. removeOpt = dataIndex.removeOpt;
  14176. dataIndex = dataIndex.dataIndex;
  14177. }
  14178. var isRemove = animationType === 'leave';
  14179. if (!isRemove) {
  14180. // Must stop the remove animation.
  14181. el.stopAnimation('leave');
  14182. }
  14183. var animationConfig = getAnimationConfig(animationType, animatableModel, dataIndex, isRemove ? removeOpt || {} : null, animatableModel && animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14184. if (animationConfig && animationConfig.duration > 0) {
  14185. var duration = animationConfig.duration;
  14186. var animationDelay = animationConfig.delay;
  14187. var animationEasing = animationConfig.easing;
  14188. var animateConfig = {
  14189. duration: duration,
  14190. delay: animationDelay || 0,
  14191. easing: animationEasing,
  14192. done: cb,
  14193. force: !!cb || !!during,
  14194. // Set to final state in update/init animation.
  14195. // So the post processing based on the path shape can be done correctly.
  14196. setToFinal: !isRemove,
  14197. scope: animationType,
  14198. during: during
  14199. };
  14200. isFrom ? el.animateFrom(props, animateConfig) : el.animateTo(props, animateConfig);
  14201. } else {
  14202. el.stopAnimation(); // If `isFrom`, the props is the "from" props.
  14203. !isFrom && el.attr(props); // Call during at least once.
  14204. during && during(1);
  14205. cb && cb();
  14206. }
  14207. }
  14208. /**
  14209. * Update graphic element properties with or without animation according to the
  14210. * configuration in series.
  14211. *
  14212. * Caution: this method will stop previous animation.
  14213. * So do not use this method to one element twice before
  14214. * animation starts, unless you know what you are doing.
  14215. * @example
  14216. * graphic.updateProps(el, {
  14217. * position: [100, 100]
  14218. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14219. * // Or
  14220. * graphic.updateProps(el, {
  14221. * position: [100, 100]
  14222. * }, seriesModel, function () { console.log('Animation done!'); });
  14223. */
  14224. function updateProps(el, props, // TODO: TYPE AnimatableModel
  14225. animatableModel, dataIndex, cb, during) {
  14226. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  14227. }
  14228. /**
  14229. * Init graphic element properties with or without animation according to the
  14230. * configuration in series.
  14231. *
  14232. * Caution: this method will stop previous animation.
  14233. * So do not use this method to one element twice before
  14234. * animation starts, unless you know what you are doing.
  14235. */
  14236. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  14237. animateOrSetProps('enter', el, props, animatableModel, dataIndex, cb, during);
  14238. }
  14239. /**
  14240. * If element is removed.
  14241. * It can determine if element is having remove animation.
  14242. */
  14243. function isElementRemoved(el) {
  14244. if (!el.__zr) {
  14245. return true;
  14246. }
  14247. for (var i = 0; i < el.animators.length; i++) {
  14248. var animator = el.animators[i];
  14249. if (animator.scope === 'leave') {
  14250. return true;
  14251. }
  14252. }
  14253. return false;
  14254. }
  14255. /**
  14256. * Remove graphic element
  14257. */
  14258. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  14259. // Don't do remove animation twice.
  14260. if (isElementRemoved(el)) {
  14261. return;
  14262. }
  14263. animateOrSetProps('leave', el, props, animatableModel, dataIndex, cb, during);
  14264. }
  14265. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  14266. el.removeTextContent();
  14267. el.removeTextGuideLine();
  14268. removeElement(el, {
  14269. style: {
  14270. opacity: 0
  14271. }
  14272. }, animatableModel, dataIndex, done);
  14273. }
  14274. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  14275. function doRemove() {
  14276. el.parent && el.parent.remove(el);
  14277. } // Hide label and labelLine first
  14278. // TODO Also use fade out animation?
  14279. if (!el.isGroup) {
  14280. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  14281. } else {
  14282. el.traverse(function (disp) {
  14283. if (!disp.isGroup) {
  14284. // Can invoke doRemove multiple times.
  14285. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  14286. }
  14287. });
  14288. }
  14289. }
  14290. /**
  14291. * Save old style for style transition in universalTransition module.
  14292. * It's used when element will be reused in each render.
  14293. * For chart like map, heatmap, which will always create new element.
  14294. * We don't need to save this because universalTransition can get old style from the old element
  14295. */
  14296. function saveOldStyle(el) {
  14297. transitionStore(el).oldStyle = el.style;
  14298. }
  14299. function getOldStyle(el) {
  14300. return transitionStore(el).oldStyle;
  14301. }
  14302. var mathMax$4 = Math.max;
  14303. var mathMin$4 = Math.min;
  14304. var _customShapeMap = {};
  14305. /**
  14306. * Extend shape with parameters
  14307. */
  14308. function extendShape(opts) {
  14309. return Path.extend(opts);
  14310. }
  14311. var extendPathFromString = extendFromString;
  14312. /**
  14313. * Extend path
  14314. */
  14315. function extendPath(pathData, opts) {
  14316. return extendPathFromString(pathData, opts);
  14317. }
  14318. /**
  14319. * Register a user defined shape.
  14320. * The shape class can be fetched by `getShapeClass`
  14321. * This method will overwrite the registered shapes, including
  14322. * the registered built-in shapes, if using the same `name`.
  14323. * The shape can be used in `custom series` and
  14324. * `graphic component` by declaring `{type: name}`.
  14325. *
  14326. * @param name
  14327. * @param ShapeClass Can be generated by `extendShape`.
  14328. */
  14329. function registerShape(name, ShapeClass) {
  14330. _customShapeMap[name] = ShapeClass;
  14331. }
  14332. /**
  14333. * Find shape class registered by `registerShape`. Usually used in
  14334. * fetching user defined shape.
  14335. *
  14336. * [Caution]:
  14337. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  14338. * to use user registered shapes.
  14339. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  14340. * `registerShape` by default. That enables users to get both built-in
  14341. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  14342. * the built-in shapes by using names like 'circle', 'rect' via calling
  14343. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  14344. * in case that it is overwritten by users, except that some features, like
  14345. * `custom series`, `graphic component`, do it deliberately.
  14346. *
  14347. * (2) In the features like `custom series`, `graphic component`, the user input
  14348. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  14349. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  14350. * are reserved names, that is, if some user registers a shape named `'image'`,
  14351. * the shape will not be used. If we intending to add some more reserved names
  14352. * in feature, that might bring break changes (disable some existing user shape
  14353. * names). But that case probably rarely happens. So we don't make more mechanism
  14354. * to resolve this issue here.
  14355. *
  14356. * @param name
  14357. * @return The shape class. If not found, return nothing.
  14358. */
  14359. function getShapeClass(name) {
  14360. if (_customShapeMap.hasOwnProperty(name)) {
  14361. return _customShapeMap[name];
  14362. }
  14363. }
  14364. /**
  14365. * Create a path element from path data string
  14366. * @param pathData
  14367. * @param opts
  14368. * @param rect
  14369. * @param layout 'center' or 'cover' default to be cover
  14370. */
  14371. function makePath(pathData, opts, rect, layout) {
  14372. var path = createFromString(pathData, opts);
  14373. if (rect) {
  14374. if (layout === 'center') {
  14375. rect = centerGraphic(rect, path.getBoundingRect());
  14376. }
  14377. resizePath(path, rect);
  14378. }
  14379. return path;
  14380. }
  14381. /**
  14382. * Create a image element from image url
  14383. * @param imageUrl image url
  14384. * @param opts options
  14385. * @param rect constrain rect
  14386. * @param layout 'center' or 'cover'. Default to be 'cover'
  14387. */
  14388. function makeImage(imageUrl, rect, layout) {
  14389. var zrImg = new ZRImage({
  14390. style: {
  14391. image: imageUrl,
  14392. x: rect.x,
  14393. y: rect.y,
  14394. width: rect.width,
  14395. height: rect.height
  14396. },
  14397. onload: function (img) {
  14398. if (layout === 'center') {
  14399. var boundingRect = {
  14400. width: img.width,
  14401. height: img.height
  14402. };
  14403. zrImg.setStyle(centerGraphic(rect, boundingRect));
  14404. }
  14405. }
  14406. });
  14407. return zrImg;
  14408. }
  14409. /**
  14410. * Get position of centered element in bounding box.
  14411. *
  14412. * @param rect element local bounding box
  14413. * @param boundingRect constraint bounding box
  14414. * @return element position containing x, y, width, and height
  14415. */
  14416. function centerGraphic(rect, boundingRect) {
  14417. // Set rect to center, keep width / height ratio.
  14418. var aspect = boundingRect.width / boundingRect.height;
  14419. var width = rect.height * aspect;
  14420. var height;
  14421. if (width <= rect.width) {
  14422. height = rect.height;
  14423. } else {
  14424. width = rect.width;
  14425. height = width / aspect;
  14426. }
  14427. var cx = rect.x + rect.width / 2;
  14428. var cy = rect.y + rect.height / 2;
  14429. return {
  14430. x: cx - width / 2,
  14431. y: cy - height / 2,
  14432. width: width,
  14433. height: height
  14434. };
  14435. }
  14436. var mergePath$1 = mergePath;
  14437. /**
  14438. * Resize a path to fit the rect
  14439. * @param path
  14440. * @param rect
  14441. */
  14442. function resizePath(path, rect) {
  14443. if (!path.applyTransform) {
  14444. return;
  14445. }
  14446. var pathRect = path.getBoundingRect();
  14447. var m = pathRect.calculateTransform(rect);
  14448. path.applyTransform(m);
  14449. }
  14450. /**
  14451. * Sub pixel optimize line for canvas
  14452. */
  14453. function subPixelOptimizeLine$1(shape, lineWidth) {
  14454. subPixelOptimizeLine(shape, shape, {
  14455. lineWidth: lineWidth
  14456. });
  14457. return shape;
  14458. }
  14459. /**
  14460. * Sub pixel optimize rect for canvas
  14461. */
  14462. function subPixelOptimizeRect$1(param) {
  14463. subPixelOptimizeRect(param.shape, param.shape, param.style);
  14464. return param;
  14465. }
  14466. /**
  14467. * Sub pixel optimize for canvas
  14468. *
  14469. * @param position Coordinate, such as x, y
  14470. * @param lineWidth Should be nonnegative integer.
  14471. * @param positiveOrNegative Default false (negative).
  14472. * @return Optimized position.
  14473. */
  14474. var subPixelOptimize$1 = subPixelOptimize;
  14475. /**
  14476. * Get transform matrix of target (param target),
  14477. * in coordinate of its ancestor (param ancestor)
  14478. *
  14479. * @param target
  14480. * @param [ancestor]
  14481. */
  14482. function getTransform(target, ancestor) {
  14483. var mat = identity([]);
  14484. while (target && target !== ancestor) {
  14485. mul$1(mat, target.getLocalTransform(), mat);
  14486. target = target.parent;
  14487. }
  14488. return mat;
  14489. }
  14490. /**
  14491. * Apply transform to an vertex.
  14492. * @param target [x, y]
  14493. * @param transform Can be:
  14494. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14495. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14496. * @param invert Whether use invert matrix.
  14497. * @return [x, y]
  14498. */
  14499. function applyTransform$1(target, transform, invert$1) {
  14500. if (transform && !isArrayLike(transform)) {
  14501. transform = Transformable.getLocalTransform(transform);
  14502. }
  14503. if (invert$1) {
  14504. transform = invert([], transform);
  14505. }
  14506. return applyTransform([], target, transform);
  14507. }
  14508. /**
  14509. * @param direction 'left' 'right' 'top' 'bottom'
  14510. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14511. * @param invert Whether use invert matrix.
  14512. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  14513. */
  14514. function transformDirection(direction, transform, invert) {
  14515. // Pick a base, ensure that transform result will not be (0, 0).
  14516. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14517. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14518. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14519. vertex = applyTransform$1(vertex, transform, invert);
  14520. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14521. }
  14522. function isNotGroup(el) {
  14523. return !el.isGroup;
  14524. }
  14525. function isPath(el) {
  14526. return el.shape != null;
  14527. }
  14528. /**
  14529. * Apply group transition animation from g1 to g2.
  14530. * If no animatableModel, no animation.
  14531. */
  14532. function groupTransition(g1, g2, animatableModel) {
  14533. if (!g1 || !g2) {
  14534. return;
  14535. }
  14536. function getElMap(g) {
  14537. var elMap = {};
  14538. g.traverse(function (el) {
  14539. if (isNotGroup(el) && el.anid) {
  14540. elMap[el.anid] = el;
  14541. }
  14542. });
  14543. return elMap;
  14544. }
  14545. function getAnimatableProps(el) {
  14546. var obj = {
  14547. x: el.x,
  14548. y: el.y,
  14549. rotation: el.rotation
  14550. };
  14551. if (isPath(el)) {
  14552. obj.shape = extend({}, el.shape);
  14553. }
  14554. return obj;
  14555. }
  14556. var elMap1 = getElMap(g1);
  14557. g2.traverse(function (el) {
  14558. if (isNotGroup(el) && el.anid) {
  14559. var oldEl = elMap1[el.anid];
  14560. if (oldEl) {
  14561. var newProp = getAnimatableProps(el);
  14562. el.attr(getAnimatableProps(oldEl));
  14563. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  14564. }
  14565. }
  14566. });
  14567. }
  14568. function clipPointsByRect(points, rect) {
  14569. // FIXME: This way might be incorrect when graphic clipped by a corner
  14570. // and when element has a border.
  14571. return map(points, function (point) {
  14572. var x = point[0];
  14573. x = mathMax$4(x, rect.x);
  14574. x = mathMin$4(x, rect.x + rect.width);
  14575. var y = point[1];
  14576. y = mathMax$4(y, rect.y);
  14577. y = mathMin$4(y, rect.y + rect.height);
  14578. return [x, y];
  14579. });
  14580. }
  14581. /**
  14582. * Return a new clipped rect. If rect size are negative, return undefined.
  14583. */
  14584. function clipRectByRect(targetRect, rect) {
  14585. var x = mathMax$4(targetRect.x, rect.x);
  14586. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14587. var y = mathMax$4(targetRect.y, rect.y);
  14588. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14589. // should be painted. So return undefined.
  14590. if (x2 >= x && y2 >= y) {
  14591. return {
  14592. x: x,
  14593. y: y,
  14594. width: x2 - x,
  14595. height: y2 - y
  14596. };
  14597. }
  14598. }
  14599. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14600. opt, rect) {
  14601. var innerOpts = extend({
  14602. rectHover: true
  14603. }, opt);
  14604. var style = innerOpts.style = {
  14605. strokeNoScale: true
  14606. };
  14607. rect = rect || {
  14608. x: -1,
  14609. y: -1,
  14610. width: 2,
  14611. height: 2
  14612. };
  14613. if (iconStr) {
  14614. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14615. }
  14616. }
  14617. /**
  14618. * Return `true` if the given line (line `a`) and the given polygon
  14619. * are intersect.
  14620. * Note that we do not count colinear as intersect here because no
  14621. * requirement for that. We could do that if required in future.
  14622. */
  14623. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14624. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14625. var p = points[i];
  14626. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14627. return true;
  14628. }
  14629. p2 = p;
  14630. }
  14631. }
  14632. /**
  14633. * Return `true` if the given two lines (line `a` and line `b`)
  14634. * are intersect.
  14635. * Note that we do not count colinear as intersect here because no
  14636. * requirement for that. We could do that if required in future.
  14637. */
  14638. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14639. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14640. var mx = a2x - a1x;
  14641. var my = a2y - a1y;
  14642. var nx = b2x - b1x;
  14643. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14644. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14645. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14646. if (nearZero(nmCrossProduct)) {
  14647. return false;
  14648. } // `vec_m` and `vec_n` are intersect iff
  14649. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14650. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14651. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14652. var b1a1x = a1x - b1x;
  14653. var b1a1y = a1y - b1y;
  14654. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14655. if (q < 0 || q > 1) {
  14656. return false;
  14657. }
  14658. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14659. if (p < 0 || p > 1) {
  14660. return false;
  14661. }
  14662. return true;
  14663. }
  14664. /**
  14665. * Cross product of 2-dimension vector.
  14666. */
  14667. function crossProduct2d(x1, y1, x2, y2) {
  14668. return x1 * y2 - x2 * y1;
  14669. }
  14670. function nearZero(val) {
  14671. return val <= 1e-6 && val >= -1e-6;
  14672. }
  14673. function setTooltipConfig(opt) {
  14674. var itemTooltipOption = opt.itemTooltipOption;
  14675. var componentModel = opt.componentModel;
  14676. var itemName = opt.itemName;
  14677. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  14678. formatter: itemTooltipOption
  14679. } : itemTooltipOption;
  14680. var mainType = componentModel.mainType;
  14681. var componentIndex = componentModel.componentIndex;
  14682. var formatterParams = {
  14683. componentType: mainType,
  14684. name: itemName,
  14685. $vars: ['name']
  14686. };
  14687. formatterParams[mainType + 'Index'] = componentIndex;
  14688. var formatterParamsExtra = opt.formatterParamsExtra;
  14689. if (formatterParamsExtra) {
  14690. each(keys(formatterParamsExtra), function (key) {
  14691. if (!hasOwn(formatterParams, key)) {
  14692. formatterParams[key] = formatterParamsExtra[key];
  14693. formatterParams.$vars.push(key);
  14694. }
  14695. });
  14696. }
  14697. var ecData = getECData(opt.el);
  14698. ecData.componentMainType = mainType;
  14699. ecData.componentIndex = componentIndex;
  14700. ecData.tooltipConfig = {
  14701. name: itemName,
  14702. option: defaults({
  14703. content: itemName,
  14704. formatterParams: formatterParams
  14705. }, itemTooltipOptionObj)
  14706. };
  14707. }
  14708. function traverseElement(el, cb) {
  14709. var stopped; // TODO
  14710. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  14711. if (el.isGroup) {
  14712. stopped = cb(el);
  14713. }
  14714. if (!stopped) {
  14715. el.traverse(cb);
  14716. }
  14717. }
  14718. function traverseElements(els, cb) {
  14719. if (els) {
  14720. if (isArray(els)) {
  14721. for (var i = 0; i < els.length; i++) {
  14722. traverseElement(els[i], cb);
  14723. }
  14724. } else {
  14725. traverseElement(els, cb);
  14726. }
  14727. }
  14728. } // Register built-in shapes. These shapes might be overwritten
  14729. // by users, although we do not recommend that.
  14730. registerShape('circle', Circle);
  14731. registerShape('ellipse', Ellipse);
  14732. registerShape('sector', Sector);
  14733. registerShape('ring', Ring);
  14734. registerShape('polygon', Polygon);
  14735. registerShape('polyline', Polyline);
  14736. registerShape('rect', Rect);
  14737. registerShape('line', Line);
  14738. registerShape('bezierCurve', BezierCurve);
  14739. registerShape('arc', Arc);
  14740. var graphic = /*#__PURE__*/Object.freeze({
  14741. __proto__: null,
  14742. updateProps: updateProps,
  14743. initProps: initProps,
  14744. removeElement: removeElement,
  14745. removeElementWithFadeOut: removeElementWithFadeOut,
  14746. isElementRemoved: isElementRemoved,
  14747. extendShape: extendShape,
  14748. extendPath: extendPath,
  14749. registerShape: registerShape,
  14750. getShapeClass: getShapeClass,
  14751. makePath: makePath,
  14752. makeImage: makeImage,
  14753. mergePath: mergePath$1,
  14754. resizePath: resizePath,
  14755. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14756. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14757. subPixelOptimize: subPixelOptimize$1,
  14758. getTransform: getTransform,
  14759. applyTransform: applyTransform$1,
  14760. transformDirection: transformDirection,
  14761. groupTransition: groupTransition,
  14762. clipPointsByRect: clipPointsByRect,
  14763. clipRectByRect: clipRectByRect,
  14764. createIcon: createIcon,
  14765. linePolygonIntersect: linePolygonIntersect,
  14766. lineLineIntersect: lineLineIntersect,
  14767. setTooltipConfig: setTooltipConfig,
  14768. traverseElements: traverseElements,
  14769. Group: Group,
  14770. Image: ZRImage,
  14771. Text: ZRText,
  14772. Circle: Circle,
  14773. Ellipse: Ellipse,
  14774. Sector: Sector,
  14775. Ring: Ring,
  14776. Polygon: Polygon,
  14777. Polyline: Polyline,
  14778. Rect: Rect,
  14779. Line: Line,
  14780. BezierCurve: BezierCurve,
  14781. Arc: Arc,
  14782. IncrementalDisplayable: IncrementalDisplayable,
  14783. CompoundPath: CompoundPath,
  14784. LinearGradient: LinearGradient,
  14785. RadialGradient: RadialGradient,
  14786. BoundingRect: BoundingRect,
  14787. OrientedBoundingRect: OrientedBoundingRect,
  14788. Point: Point,
  14789. Path: Path
  14790. });
  14791. var EMPTY_OBJ = {};
  14792. function setLabelText(label, labelTexts) {
  14793. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14794. var stateName = SPECIAL_STATES[i];
  14795. var text = labelTexts[stateName];
  14796. var state = label.ensureState(stateName);
  14797. state.style = state.style || {};
  14798. state.style.text = text;
  14799. }
  14800. var oldStates = label.currentStates.slice();
  14801. label.clearStates(true);
  14802. label.setStyle({
  14803. text: labelTexts.normal
  14804. });
  14805. label.useStates(oldStates, true);
  14806. }
  14807. function getLabelText(opt, stateModels, interpolatedValue) {
  14808. var labelFetcher = opt.labelFetcher;
  14809. var labelDataIndex = opt.labelDataIndex;
  14810. var labelDimIndex = opt.labelDimIndex;
  14811. var normalModel = stateModels.normal;
  14812. var baseText;
  14813. if (labelFetcher) {
  14814. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14815. interpolatedValue: interpolatedValue
  14816. } : null);
  14817. }
  14818. if (baseText == null) {
  14819. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14820. }
  14821. var statesText = {
  14822. normal: baseText
  14823. };
  14824. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14825. var stateName = SPECIAL_STATES[i];
  14826. var stateModel = stateModels[stateName];
  14827. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14828. }
  14829. return statesText;
  14830. }
  14831. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14832. ) {
  14833. opt = opt || EMPTY_OBJ;
  14834. var isSetOnText = targetEl instanceof ZRText;
  14835. var needsCreateText = false;
  14836. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14837. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14838. if (stateModel && stateModel.getShallow('show')) {
  14839. needsCreateText = true;
  14840. break;
  14841. }
  14842. }
  14843. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14844. if (needsCreateText) {
  14845. if (!isSetOnText) {
  14846. // Reuse the previous
  14847. if (!textContent) {
  14848. textContent = new ZRText();
  14849. targetEl.setTextContent(textContent);
  14850. } // Use same state proxy
  14851. if (targetEl.stateProxy) {
  14852. textContent.stateProxy = targetEl.stateProxy;
  14853. }
  14854. }
  14855. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14856. var normalModel = labelStatesModels.normal;
  14857. var showNormal = !!normalModel.getShallow('show');
  14858. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14859. normalStyle.text = labelStatesTexts.normal;
  14860. if (!isSetOnText) {
  14861. // Always create new
  14862. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14863. }
  14864. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14865. var stateName = SPECIAL_STATES[i];
  14866. var stateModel = labelStatesModels[stateName];
  14867. if (stateModel) {
  14868. var stateObj = textContent.ensureState(stateName);
  14869. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14870. if (stateShow !== showNormal) {
  14871. stateObj.ignore = !stateShow;
  14872. }
  14873. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14874. stateObj.style.text = labelStatesTexts[stateName];
  14875. if (!isSetOnText) {
  14876. var targetElEmphasisState = targetEl.ensureState(stateName);
  14877. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14878. }
  14879. }
  14880. } // PENDING: if there is many requirements that emphasis position
  14881. // need to be different from normal position, we might consider
  14882. // auto silent is those cases.
  14883. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14884. if (textContent.style.x != null) {
  14885. normalStyle.x = textContent.style.x;
  14886. }
  14887. if (textContent.style.y != null) {
  14888. normalStyle.y = textContent.style.y;
  14889. }
  14890. textContent.ignore = !showNormal; // Always create new style.
  14891. textContent.useStyle(normalStyle);
  14892. textContent.dirty();
  14893. if (opt.enableTextSetter) {
  14894. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14895. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14896. setLabelText(textContent, labelStatesTexts);
  14897. };
  14898. }
  14899. } else if (textContent) {
  14900. // Not display rich text.
  14901. textContent.ignore = true;
  14902. }
  14903. targetEl.dirty();
  14904. }
  14905. function getLabelStatesModels(itemModel, labelName) {
  14906. labelName = labelName || 'label';
  14907. var statesModels = {
  14908. normal: itemModel.getModel(labelName)
  14909. };
  14910. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14911. var stateName = SPECIAL_STATES[i];
  14912. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14913. }
  14914. return statesModels;
  14915. }
  14916. /**
  14917. * Set basic textStyle properties.
  14918. */
  14919. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14920. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14921. ) {
  14922. var textStyle = {};
  14923. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14924. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14925. return textStyle;
  14926. }
  14927. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14928. opt = opt || {};
  14929. var textConfig = {};
  14930. var labelPosition;
  14931. var labelRotate = textStyleModel.getShallow('rotate');
  14932. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14933. var labelOffset = textStyleModel.getShallow('offset');
  14934. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14935. // in bar series, and magric type should be considered.
  14936. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14937. if (labelPosition != null) {
  14938. textConfig.position = labelPosition;
  14939. }
  14940. if (labelOffset != null) {
  14941. textConfig.offset = labelOffset;
  14942. }
  14943. if (labelRotate != null) {
  14944. labelRotate *= Math.PI / 180;
  14945. textConfig.rotation = labelRotate;
  14946. }
  14947. if (labelDistance != null) {
  14948. textConfig.distance = labelDistance;
  14949. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14950. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14951. return textConfig;
  14952. }
  14953. /**
  14954. * The uniform entry of set text style, that is, retrieve style definitions
  14955. * from `model` and set to `textStyle` object.
  14956. *
  14957. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14958. * properties will be set. (Consider the states of normal and emphasis and
  14959. * default value can be adopted, merge would make the logic too complicated
  14960. * to manage.)
  14961. */
  14962. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14963. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14964. opt = opt || EMPTY_OBJ;
  14965. var ecModel = textStyleModel.ecModel;
  14966. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14967. // {
  14968. // data: [{
  14969. // value: 12,
  14970. // label: {
  14971. // rich: {
  14972. // // no 'a' here but using parent 'a'.
  14973. // }
  14974. // }
  14975. // }],
  14976. // rich: {
  14977. // a: { ... }
  14978. // }
  14979. // }
  14980. var richItemNames = getRichItemNames(textStyleModel);
  14981. var richResult;
  14982. if (richItemNames) {
  14983. richResult = {};
  14984. for (var name_1 in richItemNames) {
  14985. if (richItemNames.hasOwnProperty(name_1)) {
  14986. // Cascade is supported in rich.
  14987. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14988. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14989. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14990. // That might confuses users. So probably we should put `textStyleModel` as the
  14991. // root ancestor of the `richTextStyle`. But that would be a break change.
  14992. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14993. }
  14994. }
  14995. }
  14996. if (richResult) {
  14997. textStyle.rich = richResult;
  14998. }
  14999. var overflow = textStyleModel.get('overflow');
  15000. if (overflow) {
  15001. textStyle.overflow = overflow;
  15002. }
  15003. var margin = textStyleModel.get('minMargin');
  15004. if (margin != null) {
  15005. textStyle.margin = margin;
  15006. }
  15007. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  15008. } // Consider case:
  15009. // {
  15010. // data: [{
  15011. // value: 12,
  15012. // label: {
  15013. // rich: {
  15014. // // no 'a' here but using parent 'a'.
  15015. // }
  15016. // }
  15017. // }],
  15018. // rich: {
  15019. // a: { ... }
  15020. // }
  15021. // }
  15022. // TODO TextStyleModel
  15023. function getRichItemNames(textStyleModel) {
  15024. // Use object to remove duplicated names.
  15025. var richItemNameMap;
  15026. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  15027. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  15028. if (rich) {
  15029. richItemNameMap = richItemNameMap || {};
  15030. var richKeys = keys(rich);
  15031. for (var i = 0; i < richKeys.length; i++) {
  15032. var richKey = richKeys[i];
  15033. richItemNameMap[richKey] = 1;
  15034. }
  15035. }
  15036. textStyleModel = textStyleModel.parentModel;
  15037. }
  15038. return richItemNameMap;
  15039. }
  15040. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  15041. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign', 'ellipsis'];
  15042. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  15043. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  15044. // In merge mode, default value should not be given.
  15045. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  15046. var inheritColor = opt && opt.inheritColor;
  15047. var fillColor = textStyleModel.getShallow('color');
  15048. var strokeColor = textStyleModel.getShallow('textBorderColor');
  15049. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  15050. if (fillColor === 'inherit' || fillColor === 'auto') {
  15051. if ("development" !== 'production') {
  15052. if (fillColor === 'auto') {
  15053. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15054. }
  15055. }
  15056. if (inheritColor) {
  15057. fillColor = inheritColor;
  15058. } else {
  15059. fillColor = null;
  15060. }
  15061. }
  15062. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  15063. if ("development" !== 'production') {
  15064. if (strokeColor === 'auto') {
  15065. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  15066. }
  15067. }
  15068. if (inheritColor) {
  15069. strokeColor = inheritColor;
  15070. } else {
  15071. strokeColor = null;
  15072. }
  15073. }
  15074. if (!isAttached) {
  15075. // Only use default global textStyle.color if text is individual.
  15076. // Otherwise it will use the strategy of attached text color because text may be on a path.
  15077. fillColor = fillColor || globalTextStyle.color;
  15078. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  15079. }
  15080. if (fillColor != null) {
  15081. textStyle.fill = fillColor;
  15082. }
  15083. if (strokeColor != null) {
  15084. textStyle.stroke = strokeColor;
  15085. }
  15086. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  15087. if (textBorderWidth != null) {
  15088. textStyle.lineWidth = textBorderWidth;
  15089. }
  15090. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  15091. if (textBorderType != null) {
  15092. textStyle.lineDash = textBorderType;
  15093. }
  15094. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  15095. if (textBorderDashOffset != null) {
  15096. textStyle.lineDashOffset = textBorderDashOffset;
  15097. }
  15098. if (!isNotNormal && opacity == null && !inRich) {
  15099. opacity = opt && opt.defaultOpacity;
  15100. }
  15101. if (opacity != null) {
  15102. textStyle.opacity = opacity;
  15103. } // TODO
  15104. if (!isNotNormal && !isAttached) {
  15105. // Set default finally.
  15106. if (textStyle.fill == null && opt.inheritColor) {
  15107. textStyle.fill = opt.inheritColor;
  15108. }
  15109. } // Do not use `getFont` here, because merge should be supported, where
  15110. // part of these properties may be changed in emphasis style, and the
  15111. // others should remain their original value got from normal style.
  15112. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  15113. var key = TEXT_PROPS_WITH_GLOBAL[i];
  15114. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  15115. if (val != null) {
  15116. textStyle[key] = val;
  15117. }
  15118. }
  15119. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  15120. var key = TEXT_PROPS_SELF[i];
  15121. var val = textStyleModel.getShallow(key);
  15122. if (val != null) {
  15123. textStyle[key] = val;
  15124. }
  15125. }
  15126. if (textStyle.verticalAlign == null) {
  15127. var baseline = textStyleModel.getShallow('baseline');
  15128. if (baseline != null) {
  15129. textStyle.verticalAlign = baseline;
  15130. }
  15131. }
  15132. if (!isBlock || !opt.disableBox) {
  15133. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  15134. var key = TEXT_PROPS_BOX[i];
  15135. var val = textStyleModel.getShallow(key);
  15136. if (val != null) {
  15137. textStyle[key] = val;
  15138. }
  15139. }
  15140. var borderType = textStyleModel.getShallow('borderType');
  15141. if (borderType != null) {
  15142. textStyle.borderDash = borderType;
  15143. }
  15144. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  15145. if ("development" !== 'production') {
  15146. if (textStyle.backgroundColor === 'auto') {
  15147. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  15148. }
  15149. }
  15150. textStyle.backgroundColor = inheritColor;
  15151. }
  15152. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  15153. if ("development" !== 'production') {
  15154. if (textStyle.borderColor === 'auto') {
  15155. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  15156. }
  15157. }
  15158. textStyle.borderColor = inheritColor;
  15159. }
  15160. }
  15161. }
  15162. function getFont(opt, ecModel) {
  15163. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  15164. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  15165. 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(' '));
  15166. }
  15167. var labelInner = makeInner();
  15168. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  15169. if (!label) {
  15170. return;
  15171. }
  15172. var obj = labelInner(label);
  15173. obj.prevValue = obj.value;
  15174. obj.value = value;
  15175. var normalLabelModel = labelStatesModels.normal;
  15176. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  15177. if (obj.valueAnimation) {
  15178. obj.precision = normalLabelModel.get('precision');
  15179. obj.defaultInterpolatedText = getDefaultText;
  15180. obj.statesModels = labelStatesModels;
  15181. }
  15182. }
  15183. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  15184. var labelInnerStore = labelInner(textEl);
  15185. if (!labelInnerStore.valueAnimation || labelInnerStore.prevValue === labelInnerStore.value) {
  15186. // Value not changed, no new label animation
  15187. return;
  15188. }
  15189. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  15190. // Otherwise it will jump to the `obj.value` when this new animation started.
  15191. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  15192. var targetValue = labelInnerStore.value;
  15193. function during(percent) {
  15194. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  15195. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  15196. var labelText = getLabelText({
  15197. labelDataIndex: dataIndex,
  15198. labelFetcher: labelFetcher,
  15199. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  15200. }, labelInnerStore.statesModels, interpolated);
  15201. setLabelText(textEl, labelText);
  15202. }
  15203. textEl.percent = 0;
  15204. (labelInnerStore.prevValue == null ? initProps : updateProps)(textEl, {
  15205. // percent is used to prevent animation from being aborted #15916
  15206. percent: 1
  15207. }, animatableModel, dataIndex, null, during);
  15208. }
  15209. var PATH_COLOR = ['textStyle', 'color'];
  15210. var textStyleParams = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'padding', 'lineHeight', 'rich', 'width', 'height', 'overflow']; // TODO Performance improvement?
  15211. var tmpText = new ZRText();
  15212. var TextStyleMixin =
  15213. /** @class */
  15214. function () {
  15215. function TextStyleMixin() {}
  15216. /**
  15217. * Get color property or get color from option.textStyle.color
  15218. */
  15219. // TODO Callback
  15220. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  15221. var ecModel = this.ecModel;
  15222. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15223. };
  15224. /**
  15225. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15226. * @return {string}
  15227. */
  15228. TextStyleMixin.prototype.getFont = function () {
  15229. return getFont({
  15230. fontStyle: this.getShallow('fontStyle'),
  15231. fontWeight: this.getShallow('fontWeight'),
  15232. fontSize: this.getShallow('fontSize'),
  15233. fontFamily: this.getShallow('fontFamily')
  15234. }, this.ecModel);
  15235. };
  15236. TextStyleMixin.prototype.getTextRect = function (text) {
  15237. var style = {
  15238. text: text,
  15239. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline')
  15240. };
  15241. for (var i = 0; i < textStyleParams.length; i++) {
  15242. style[textStyleParams[i]] = this.getShallow(textStyleParams[i]);
  15243. }
  15244. tmpText.useStyle(style);
  15245. tmpText.update();
  15246. return tmpText.getBoundingRect();
  15247. };
  15248. return TextStyleMixin;
  15249. }();
  15250. 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`.
  15251. // So do not transfer decal directly.
  15252. ];
  15253. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  15254. var LineStyleMixin =
  15255. /** @class */
  15256. function () {
  15257. function LineStyleMixin() {}
  15258. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  15259. return getLineStyle(this, excludes);
  15260. };
  15261. return LineStyleMixin;
  15262. }();
  15263. 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`.
  15264. // So do not transfer decal directly.
  15265. ];
  15266. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  15267. var ItemStyleMixin =
  15268. /** @class */
  15269. function () {
  15270. function ItemStyleMixin() {}
  15271. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  15272. return getItemStyle(this, excludes, includes);
  15273. };
  15274. return ItemStyleMixin;
  15275. }();
  15276. var Model =
  15277. /** @class */
  15278. function () {
  15279. function Model(option, parentModel, ecModel) {
  15280. this.parentModel = parentModel;
  15281. this.ecModel = ecModel;
  15282. this.option = option; // Simple optimization
  15283. // if (this.init) {
  15284. // if (arguments.length <= 4) {
  15285. // this.init(option, parentModel, ecModel, extraOpt);
  15286. // }
  15287. // else {
  15288. // this.init.apply(this, arguments);
  15289. // }
  15290. // }
  15291. }
  15292. Model.prototype.init = function (option, parentModel, ecModel) {
  15293. var rest = [];
  15294. for (var _i = 3; _i < arguments.length; _i++) {
  15295. rest[_i - 3] = arguments[_i];
  15296. }
  15297. };
  15298. /**
  15299. * Merge the input option to me.
  15300. */
  15301. Model.prototype.mergeOption = function (option, ecModel) {
  15302. merge(this.option, option, true);
  15303. }; // `path` can be 'a.b.c', so the return value type have to be `ModelOption`
  15304. // TODO: TYPE strict key check?
  15305. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  15306. Model.prototype.get = function (path, ignoreParent) {
  15307. if (path == null) {
  15308. return this.option;
  15309. }
  15310. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  15311. };
  15312. Model.prototype.getShallow = function (key, ignoreParent) {
  15313. var option = this.option;
  15314. var val = option == null ? option : option[key];
  15315. if (val == null && !ignoreParent) {
  15316. var parentModel = this.parentModel;
  15317. if (parentModel) {
  15318. // FIXME:TS do not know how to make it works
  15319. val = parentModel.getShallow(key);
  15320. }
  15321. }
  15322. return val;
  15323. }; // `path` can be 'a.b.c', so the return value type have to be `Model<ModelOption>`
  15324. // getModel(path: string | string[], parentModel?: Model): Model;
  15325. // TODO 'a.b.c' is deprecated
  15326. Model.prototype.getModel = function (path, parentModel) {
  15327. var hasPath = path != null;
  15328. var pathFinal = hasPath ? this.parsePath(path) : null;
  15329. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  15330. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  15331. return new Model(obj, parentModel, this.ecModel);
  15332. };
  15333. /**
  15334. * If model has option
  15335. */
  15336. Model.prototype.isEmpty = function () {
  15337. return this.option == null;
  15338. };
  15339. Model.prototype.restoreData = function () {}; // Pending
  15340. Model.prototype.clone = function () {
  15341. var Ctor = this.constructor;
  15342. return new Ctor(clone(this.option));
  15343. }; // setReadOnly(properties): void {
  15344. // clazzUtil.setReadOnly(this, properties);
  15345. // }
  15346. // If path is null/undefined, return null/undefined.
  15347. Model.prototype.parsePath = function (path) {
  15348. if (typeof path === 'string') {
  15349. return path.split('.');
  15350. }
  15351. return path;
  15352. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  15353. // Default to be a identity resolver.
  15354. // Can be modified to a different resolver.
  15355. Model.prototype.resolveParentPath = function (path) {
  15356. return path;
  15357. }; // FIXME:TS check whether put this method here
  15358. Model.prototype.isAnimationEnabled = function () {
  15359. if (!env.node && this.option) {
  15360. if (this.option.animation != null) {
  15361. return !!this.option.animation;
  15362. } else if (this.parentModel) {
  15363. return this.parentModel.isAnimationEnabled();
  15364. }
  15365. }
  15366. };
  15367. Model.prototype._doGet = function (pathArr, parentModel) {
  15368. var obj = this.option;
  15369. if (!pathArr) {
  15370. return obj;
  15371. }
  15372. for (var i = 0; i < pathArr.length; i++) {
  15373. // Ignore empty
  15374. if (!pathArr[i]) {
  15375. continue;
  15376. } // obj could be number/string/... (like 0)
  15377. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15378. if (obj == null) {
  15379. break;
  15380. }
  15381. }
  15382. if (obj == null && parentModel) {
  15383. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  15384. }
  15385. return obj;
  15386. };
  15387. return Model;
  15388. }();
  15389. enableClassExtend(Model);
  15390. enableClassCheck(Model);
  15391. mixin(Model, LineStyleMixin);
  15392. mixin(Model, ItemStyleMixin);
  15393. mixin(Model, AreaStyleMixin);
  15394. mixin(Model, TextStyleMixin);
  15395. var base = Math.round(Math.random() * 10);
  15396. /**
  15397. * @public
  15398. * @param {string} type
  15399. * @return {string}
  15400. */
  15401. function getUID(type) {
  15402. // Considering the case of crossing js context,
  15403. // use Math.random to make id as unique as possible.
  15404. return [type || '', base++].join('_');
  15405. }
  15406. /**
  15407. * Implements `SubTypeDefaulterManager` for `target`.
  15408. */
  15409. function enableSubTypeDefaulter(target) {
  15410. var subTypeDefaulters = {};
  15411. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  15412. var componentTypeInfo = parseClassType(componentType);
  15413. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  15414. };
  15415. target.determineSubType = function (componentType, option) {
  15416. var type = option.type;
  15417. if (!type) {
  15418. var componentTypeMain = parseClassType(componentType).main;
  15419. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15420. type = subTypeDefaulters[componentTypeMain](option);
  15421. }
  15422. }
  15423. return type;
  15424. };
  15425. }
  15426. /**
  15427. * Implements `TopologicalTravelable<any>` for `entity`.
  15428. *
  15429. * Topological travel on Activity Network (Activity On Vertices).
  15430. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15431. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15432. * If there is circular dependencey, Error will be thrown.
  15433. */
  15434. function enableTopologicalTravel(entity, dependencyGetter) {
  15435. /**
  15436. * @param targetNameList Target Component type list.
  15437. * Can be ['aa', 'bb', 'aa.xx']
  15438. * @param fullNameList By which we can build dependency graph.
  15439. * @param callback Params: componentType, dependencies.
  15440. * @param context Scope of callback.
  15441. */
  15442. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15443. if (!targetNameList.length) {
  15444. return;
  15445. }
  15446. var result = makeDepndencyGraph(fullNameList);
  15447. var graph = result.graph;
  15448. var noEntryList = result.noEntryList;
  15449. var targetNameSet = {};
  15450. each(targetNameList, function (name) {
  15451. targetNameSet[name] = true;
  15452. });
  15453. while (noEntryList.length) {
  15454. var currComponentType = noEntryList.pop();
  15455. var currVertex = graph[currComponentType];
  15456. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15457. if (isInTargetNameSet) {
  15458. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15459. delete targetNameSet[currComponentType];
  15460. }
  15461. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15462. }
  15463. each(targetNameSet, function () {
  15464. var errMsg = '';
  15465. if ("development" !== 'production') {
  15466. errMsg = makePrintable('Circular dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  15467. }
  15468. throw new Error(errMsg);
  15469. });
  15470. function removeEdge(succComponentType) {
  15471. graph[succComponentType].entryCount--;
  15472. if (graph[succComponentType].entryCount === 0) {
  15473. noEntryList.push(succComponentType);
  15474. }
  15475. } // Consider this case: legend depends on series, and we call
  15476. // chart.setOption({series: [...]}), where only series is in option.
  15477. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15478. // not be called, but only sereis.mergeOption is called. Thus legend
  15479. // have no chance to update its local record about series (like which
  15480. // name of series is available in legend).
  15481. function removeEdgeAndAdd(succComponentType) {
  15482. targetNameSet[succComponentType] = true;
  15483. removeEdge(succComponentType);
  15484. }
  15485. };
  15486. function makeDepndencyGraph(fullNameList) {
  15487. var graph = {};
  15488. var noEntryList = [];
  15489. each(fullNameList, function (name) {
  15490. var thisItem = createDependencyGraphItem(graph, name);
  15491. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15492. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15493. thisItem.entryCount = availableDeps.length;
  15494. if (thisItem.entryCount === 0) {
  15495. noEntryList.push(name);
  15496. }
  15497. each(availableDeps, function (dependentName) {
  15498. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15499. thisItem.predecessor.push(dependentName);
  15500. }
  15501. var thatItem = createDependencyGraphItem(graph, dependentName);
  15502. if (indexOf(thatItem.successor, dependentName) < 0) {
  15503. thatItem.successor.push(name);
  15504. }
  15505. });
  15506. });
  15507. return {
  15508. graph: graph,
  15509. noEntryList: noEntryList
  15510. };
  15511. }
  15512. function createDependencyGraphItem(graph, name) {
  15513. if (!graph[name]) {
  15514. graph[name] = {
  15515. predecessor: [],
  15516. successor: []
  15517. };
  15518. }
  15519. return graph[name];
  15520. }
  15521. function getAvailableDependencies(originalDeps, fullNameList) {
  15522. var availableDeps = [];
  15523. each(originalDeps, function (dep) {
  15524. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15525. });
  15526. return availableDeps;
  15527. }
  15528. }
  15529. function inheritDefaultOption(superOption, subOption) {
  15530. // See also `model/Component.ts#getDefaultOption`
  15531. return merge(merge({}, superOption, true), subOption, true);
  15532. }
  15533. /*
  15534. * Licensed to the Apache Software Foundation (ASF) under one
  15535. * or more contributor license agreements. See the NOTICE file
  15536. * distributed with this work for additional information
  15537. * regarding copyright ownership. The ASF licenses this file
  15538. * to you under the Apache License, Version 2.0 (the
  15539. * "License"); you may not use this file except in compliance
  15540. * with the License. You may obtain a copy of the License at
  15541. *
  15542. * http://www.apache.org/licenses/LICENSE-2.0
  15543. *
  15544. * Unless required by applicable law or agreed to in writing,
  15545. * software distributed under the License is distributed on an
  15546. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15547. * KIND, either express or implied. See the License for the
  15548. * specific language governing permissions and limitations
  15549. * under the License.
  15550. */
  15551. /**
  15552. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15553. */
  15554. /*
  15555. * Licensed to the Apache Software Foundation (ASF) under one
  15556. * or more contributor license agreements. See the NOTICE file
  15557. * distributed with this work for additional information
  15558. * regarding copyright ownership. The ASF licenses this file
  15559. * to you under the Apache License, Version 2.0 (the
  15560. * "License"); you may not use this file except in compliance
  15561. * with the License. You may obtain a copy of the License at
  15562. *
  15563. * http://www.apache.org/licenses/LICENSE-2.0
  15564. *
  15565. * Unless required by applicable law or agreed to in writing,
  15566. * software distributed under the License is distributed on an
  15567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15568. * KIND, either express or implied. See the License for the
  15569. * specific language governing permissions and limitations
  15570. * under the License.
  15571. */
  15572. /**
  15573. * Language: English.
  15574. */
  15575. var langEN = {
  15576. time: {
  15577. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  15578. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  15579. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  15580. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  15581. },
  15582. legend: {
  15583. selector: {
  15584. all: 'All',
  15585. inverse: 'Inv'
  15586. }
  15587. },
  15588. toolbox: {
  15589. brush: {
  15590. title: {
  15591. rect: 'Box Select',
  15592. polygon: 'Lasso Select',
  15593. lineX: 'Horizontally Select',
  15594. lineY: 'Vertically Select',
  15595. keep: 'Keep Selections',
  15596. clear: 'Clear Selections'
  15597. }
  15598. },
  15599. dataView: {
  15600. title: 'Data View',
  15601. lang: ['Data View', 'Close', 'Refresh']
  15602. },
  15603. dataZoom: {
  15604. title: {
  15605. zoom: 'Zoom',
  15606. back: 'Zoom Reset'
  15607. }
  15608. },
  15609. magicType: {
  15610. title: {
  15611. line: 'Switch to Line Chart',
  15612. bar: 'Switch to Bar Chart',
  15613. stack: 'Stack',
  15614. tiled: 'Tile'
  15615. }
  15616. },
  15617. restore: {
  15618. title: 'Restore'
  15619. },
  15620. saveAsImage: {
  15621. title: 'Save as Image',
  15622. lang: ['Right Click to Save Image']
  15623. }
  15624. },
  15625. series: {
  15626. typeNames: {
  15627. pie: 'Pie chart',
  15628. bar: 'Bar chart',
  15629. line: 'Line chart',
  15630. scatter: 'Scatter plot',
  15631. effectScatter: 'Ripple scatter plot',
  15632. radar: 'Radar chart',
  15633. tree: 'Tree',
  15634. treemap: 'Treemap',
  15635. boxplot: 'Boxplot',
  15636. candlestick: 'Candlestick',
  15637. k: 'K line chart',
  15638. heatmap: 'Heat map',
  15639. map: 'Map',
  15640. parallel: 'Parallel coordinate map',
  15641. lines: 'Line graph',
  15642. graph: 'Relationship graph',
  15643. sankey: 'Sankey diagram',
  15644. funnel: 'Funnel chart',
  15645. gauge: 'Gauge',
  15646. pictorialBar: 'Pictorial bar',
  15647. themeRiver: 'Theme River Map',
  15648. sunburst: 'Sunburst'
  15649. }
  15650. },
  15651. aria: {
  15652. general: {
  15653. withTitle: 'This is a chart about "{title}"',
  15654. withoutTitle: 'This is a chart'
  15655. },
  15656. series: {
  15657. single: {
  15658. prefix: '',
  15659. withName: ' with type {seriesType} named {seriesName}.',
  15660. withoutName: ' with type {seriesType}.'
  15661. },
  15662. multiple: {
  15663. prefix: '. It consists of {seriesCount} series count.',
  15664. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15665. withoutName: ' The {seriesId} series is a {seriesType}.',
  15666. separator: {
  15667. middle: '',
  15668. end: ''
  15669. }
  15670. }
  15671. },
  15672. data: {
  15673. allData: 'The data is as follows: ',
  15674. partialData: 'The first {displayCnt} items are: ',
  15675. withName: 'the data for {name} is {value}',
  15676. withoutName: '{value}',
  15677. separator: {
  15678. middle: ', ',
  15679. end: '. '
  15680. }
  15681. }
  15682. }
  15683. };
  15684. /*
  15685. * Licensed to the Apache Software Foundation (ASF) under one
  15686. * or more contributor license agreements. See the NOTICE file
  15687. * distributed with this work for additional information
  15688. * regarding copyright ownership. The ASF licenses this file
  15689. * to you under the Apache License, Version 2.0 (the
  15690. * "License"); you may not use this file except in compliance
  15691. * with the License. You may obtain a copy of the License at
  15692. *
  15693. * http://www.apache.org/licenses/LICENSE-2.0
  15694. *
  15695. * Unless required by applicable law or agreed to in writing,
  15696. * software distributed under the License is distributed on an
  15697. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15698. * KIND, either express or implied. See the License for the
  15699. * specific language governing permissions and limitations
  15700. * under the License.
  15701. */
  15702. /**
  15703. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15704. */
  15705. /*
  15706. * Licensed to the Apache Software Foundation (ASF) under one
  15707. * or more contributor license agreements. See the NOTICE file
  15708. * distributed with this work for additional information
  15709. * regarding copyright ownership. The ASF licenses this file
  15710. * to you under the Apache License, Version 2.0 (the
  15711. * "License"); you may not use this file except in compliance
  15712. * with the License. You may obtain a copy of the License at
  15713. *
  15714. * http://www.apache.org/licenses/LICENSE-2.0
  15715. *
  15716. * Unless required by applicable law or agreed to in writing,
  15717. * software distributed under the License is distributed on an
  15718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15719. * KIND, either express or implied. See the License for the
  15720. * specific language governing permissions and limitations
  15721. * under the License.
  15722. */
  15723. var langZH = {
  15724. time: {
  15725. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15726. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15727. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15728. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15729. },
  15730. legend: {
  15731. selector: {
  15732. all: '全选',
  15733. inverse: '反选'
  15734. }
  15735. },
  15736. toolbox: {
  15737. brush: {
  15738. title: {
  15739. rect: '矩形选择',
  15740. polygon: '圈选',
  15741. lineX: '横向选择',
  15742. lineY: '纵向选择',
  15743. keep: '保持选择',
  15744. clear: '清除选择'
  15745. }
  15746. },
  15747. dataView: {
  15748. title: '数据视图',
  15749. lang: ['数据视图', '关闭', '刷新']
  15750. },
  15751. dataZoom: {
  15752. title: {
  15753. zoom: '区域缩放',
  15754. back: '区域缩放还原'
  15755. }
  15756. },
  15757. magicType: {
  15758. title: {
  15759. line: '切换为折线图',
  15760. bar: '切换为柱状图',
  15761. stack: '切换为堆叠',
  15762. tiled: '切换为平铺'
  15763. }
  15764. },
  15765. restore: {
  15766. title: '还原'
  15767. },
  15768. saveAsImage: {
  15769. title: '保存为图片',
  15770. lang: ['右键另存为图片']
  15771. }
  15772. },
  15773. series: {
  15774. typeNames: {
  15775. pie: '饼图',
  15776. bar: '柱状图',
  15777. line: '折线图',
  15778. scatter: '散点图',
  15779. effectScatter: '涟漪散点图',
  15780. radar: '雷达图',
  15781. tree: '树图',
  15782. treemap: '矩形树图',
  15783. boxplot: '箱型图',
  15784. candlestick: 'K线图',
  15785. k: 'K线图',
  15786. heatmap: '热力图',
  15787. map: '地图',
  15788. parallel: '平行坐标图',
  15789. lines: '线图',
  15790. graph: '关系图',
  15791. sankey: '桑基图',
  15792. funnel: '漏斗图',
  15793. gauge: '仪表盘图',
  15794. pictorialBar: '象形柱图',
  15795. themeRiver: '主题河流图',
  15796. sunburst: '旭日图'
  15797. }
  15798. },
  15799. aria: {
  15800. general: {
  15801. withTitle: '这是一个关于“{title}”的图表。',
  15802. withoutTitle: '这是一个图表,'
  15803. },
  15804. series: {
  15805. single: {
  15806. prefix: '',
  15807. withName: '图表类型是{seriesType},表示{seriesName}。',
  15808. withoutName: '图表类型是{seriesType}。'
  15809. },
  15810. multiple: {
  15811. prefix: '它由{seriesCount}个图表系列组成。',
  15812. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15813. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15814. separator: {
  15815. middle: ';',
  15816. end: '。'
  15817. }
  15818. }
  15819. },
  15820. data: {
  15821. allData: '其数据是——',
  15822. partialData: '其中,前{displayCnt}项是——',
  15823. withName: '{name}的数据是{value}',
  15824. withoutName: '{value}',
  15825. separator: {
  15826. middle: ',',
  15827. end: ''
  15828. }
  15829. }
  15830. }
  15831. };
  15832. var LOCALE_ZH = 'ZH';
  15833. var LOCALE_EN = 'EN';
  15834. var DEFAULT_LOCALE = LOCALE_EN;
  15835. var localeStorage = {};
  15836. var localeModels = {};
  15837. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15838. var langStr = (
  15839. /* eslint-disable-next-line */
  15840. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15841. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15842. }();
  15843. function registerLocale(locale, localeObj) {
  15844. locale = locale.toUpperCase();
  15845. localeModels[locale] = new Model(localeObj);
  15846. localeStorage[locale] = localeObj;
  15847. } // export function getLocale(locale: string) {
  15848. // return localeStorage[locale];
  15849. // }
  15850. function createLocaleObject(locale) {
  15851. if (isString(locale)) {
  15852. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15853. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15854. return clone(localeObj);
  15855. } else {
  15856. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15857. }
  15858. } else {
  15859. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15860. }
  15861. }
  15862. function getLocaleModel(lang) {
  15863. return localeModels[lang];
  15864. }
  15865. function getDefaultLocaleModel() {
  15866. return localeModels[DEFAULT_LOCALE];
  15867. } // Default locale
  15868. registerLocale(LOCALE_EN, langEN);
  15869. registerLocale(LOCALE_ZH, langZH);
  15870. var ONE_SECOND = 1000;
  15871. var ONE_MINUTE = ONE_SECOND * 60;
  15872. var ONE_HOUR = ONE_MINUTE * 60;
  15873. var ONE_DAY = ONE_HOUR * 24;
  15874. var ONE_YEAR = ONE_DAY * 365;
  15875. var defaultLeveledFormatter = {
  15876. year: '{yyyy}',
  15877. month: '{MMM}',
  15878. day: '{d}',
  15879. hour: '{HH}:{mm}',
  15880. minute: '{HH}:{mm}',
  15881. second: '{HH}:{mm}:{ss}',
  15882. millisecond: '{HH}:{mm}:{ss} {SSS}',
  15883. none: '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}'
  15884. };
  15885. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15886. var fullLeveledFormatter = {
  15887. year: '{yyyy}',
  15888. month: '{yyyy}-{MM}',
  15889. day: fullDayFormatter,
  15890. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15891. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15892. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15893. millisecond: defaultLeveledFormatter.none
  15894. };
  15895. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15896. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15897. function pad(str, len) {
  15898. str += '';
  15899. return '0000'.substr(0, len - str.length) + str;
  15900. }
  15901. function getPrimaryTimeUnit(timeUnit) {
  15902. switch (timeUnit) {
  15903. case 'half-year':
  15904. case 'quarter':
  15905. return 'month';
  15906. case 'week':
  15907. case 'half-week':
  15908. return 'day';
  15909. case 'half-day':
  15910. case 'quarter-day':
  15911. return 'hour';
  15912. default:
  15913. // year, minutes, second, milliseconds
  15914. return timeUnit;
  15915. }
  15916. }
  15917. function isPrimaryTimeUnit(timeUnit) {
  15918. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15919. }
  15920. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15921. switch (timeUnit) {
  15922. case 'year':
  15923. case 'month':
  15924. return 'day';
  15925. case 'millisecond':
  15926. return 'millisecond';
  15927. default:
  15928. // Also for day, hour, minute, second
  15929. return 'second';
  15930. }
  15931. }
  15932. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15933. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15934. time, template, isUTC, lang) {
  15935. var date = parseDate(time);
  15936. var y = date[fullYearGetterName(isUTC)]();
  15937. var M = date[monthGetterName(isUTC)]() + 1;
  15938. var q = Math.floor((M - 1) / 3) + 1;
  15939. var d = date[dateGetterName(isUTC)]();
  15940. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15941. var H = date[hoursGetterName(isUTC)]();
  15942. var h = (H - 1) % 12 + 1;
  15943. var m = date[minutesGetterName(isUTC)]();
  15944. var s = date[secondsGetterName(isUTC)]();
  15945. var S = date[millisecondsGetterName(isUTC)]();
  15946. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15947. var timeModel = localeModel.getModel('time');
  15948. var month = timeModel.get('month');
  15949. var monthAbbr = timeModel.get('monthAbbr');
  15950. var dayOfWeek = timeModel.get('dayOfWeek');
  15951. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15952. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, pad(y % 100 + '', 2)).replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15953. }
  15954. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15955. var template = null;
  15956. if (isString(formatter)) {
  15957. // Single formatter for all units at all levels
  15958. template = formatter;
  15959. } else if (isFunction(formatter)) {
  15960. // Callback formatter
  15961. template = formatter(tick.value, idx, {
  15962. level: tick.level
  15963. });
  15964. } else {
  15965. var defaults$1 = extend({}, defaultLeveledFormatter);
  15966. if (tick.level > 0) {
  15967. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15968. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15969. }
  15970. }
  15971. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15972. : defaults(formatter, defaults$1) : defaults$1;
  15973. var unit = getUnitFromValue(tick.value, isUTC);
  15974. if (mergedFormatter[unit]) {
  15975. template = mergedFormatter[unit];
  15976. } else if (mergedFormatter.inherit) {
  15977. // Unit formatter is not defined and should inherit from bigger units
  15978. var targetId = timeUnits.indexOf(unit);
  15979. for (var i = targetId - 1; i >= 0; --i) {
  15980. if (mergedFormatter[unit]) {
  15981. template = mergedFormatter[unit];
  15982. break;
  15983. }
  15984. }
  15985. template = template || defaults$1.none;
  15986. }
  15987. if (isArray(template)) {
  15988. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15989. levelId = Math.min(levelId, template.length - 1);
  15990. template = template[levelId];
  15991. }
  15992. }
  15993. return format(new Date(tick.value), template, isUTC, lang);
  15994. }
  15995. function getUnitFromValue(value, isUTC) {
  15996. var date = parseDate(value);
  15997. var M = date[monthGetterName(isUTC)]() + 1;
  15998. var d = date[dateGetterName(isUTC)]();
  15999. var h = date[hoursGetterName(isUTC)]();
  16000. var m = date[minutesGetterName(isUTC)]();
  16001. var s = date[secondsGetterName(isUTC)]();
  16002. var S = date[millisecondsGetterName(isUTC)]();
  16003. var isSecond = S === 0;
  16004. var isMinute = isSecond && s === 0;
  16005. var isHour = isMinute && m === 0;
  16006. var isDay = isHour && h === 0;
  16007. var isMonth = isDay && d === 1;
  16008. var isYear = isMonth && M === 1;
  16009. if (isYear) {
  16010. return 'year';
  16011. } else if (isMonth) {
  16012. return 'month';
  16013. } else if (isDay) {
  16014. return 'day';
  16015. } else if (isHour) {
  16016. return 'hour';
  16017. } else if (isMinute) {
  16018. return 'minute';
  16019. } else if (isSecond) {
  16020. return 'second';
  16021. } else {
  16022. return 'millisecond';
  16023. }
  16024. }
  16025. function getUnitValue(value, unit, isUTC) {
  16026. var date = isNumber(value) ? parseDate(value) : value;
  16027. unit = unit || getUnitFromValue(value, isUTC);
  16028. switch (unit) {
  16029. case 'year':
  16030. return date[fullYearGetterName(isUTC)]();
  16031. case 'half-year':
  16032. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  16033. case 'quarter':
  16034. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  16035. case 'month':
  16036. return date[monthGetterName(isUTC)]();
  16037. case 'day':
  16038. return date[dateGetterName(isUTC)]();
  16039. case 'half-day':
  16040. return date[hoursGetterName(isUTC)]() / 24;
  16041. case 'hour':
  16042. return date[hoursGetterName(isUTC)]();
  16043. case 'minute':
  16044. return date[minutesGetterName(isUTC)]();
  16045. case 'second':
  16046. return date[secondsGetterName(isUTC)]();
  16047. case 'millisecond':
  16048. return date[millisecondsGetterName(isUTC)]();
  16049. }
  16050. }
  16051. function fullYearGetterName(isUTC) {
  16052. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  16053. }
  16054. function monthGetterName(isUTC) {
  16055. return isUTC ? 'getUTCMonth' : 'getMonth';
  16056. }
  16057. function dateGetterName(isUTC) {
  16058. return isUTC ? 'getUTCDate' : 'getDate';
  16059. }
  16060. function hoursGetterName(isUTC) {
  16061. return isUTC ? 'getUTCHours' : 'getHours';
  16062. }
  16063. function minutesGetterName(isUTC) {
  16064. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  16065. }
  16066. function secondsGetterName(isUTC) {
  16067. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  16068. }
  16069. function millisecondsGetterName(isUTC) {
  16070. return isUTC ? 'getUTCMilliseconds' : 'getMilliseconds';
  16071. }
  16072. function fullYearSetterName(isUTC) {
  16073. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  16074. }
  16075. function monthSetterName(isUTC) {
  16076. return isUTC ? 'setUTCMonth' : 'setMonth';
  16077. }
  16078. function dateSetterName(isUTC) {
  16079. return isUTC ? 'setUTCDate' : 'setDate';
  16080. }
  16081. function hoursSetterName(isUTC) {
  16082. return isUTC ? 'setUTCHours' : 'setHours';
  16083. }
  16084. function minutesSetterName(isUTC) {
  16085. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  16086. }
  16087. function secondsSetterName(isUTC) {
  16088. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  16089. }
  16090. function millisecondsSetterName(isUTC) {
  16091. return isUTC ? 'setUTCMilliseconds' : 'setMilliseconds';
  16092. }
  16093. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  16094. var textEl = new ZRText({
  16095. style: {
  16096. text: text,
  16097. font: font,
  16098. align: align,
  16099. verticalAlign: verticalAlign,
  16100. padding: padding,
  16101. rich: rich,
  16102. overflow: truncate ? 'truncate' : null,
  16103. lineHeight: lineHeight
  16104. }
  16105. });
  16106. return textEl.getBoundingRect();
  16107. }
  16108. /**
  16109. * Add a comma each three digit.
  16110. */
  16111. function addCommas(x) {
  16112. if (!isNumeric(x)) {
  16113. return isString(x) ? x : '-';
  16114. }
  16115. var parts = (x + '').split('.');
  16116. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  16117. }
  16118. function toCamelCase(str, upperCaseFirst) {
  16119. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16120. return group1.toUpperCase();
  16121. });
  16122. if (upperCaseFirst && str) {
  16123. str = str.charAt(0).toUpperCase() + str.slice(1);
  16124. }
  16125. return str;
  16126. }
  16127. var normalizeCssArray$1 = normalizeCssArray;
  16128. /**
  16129. * Make value user readable for tooltip and label.
  16130. * "User readable":
  16131. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  16132. * Avoid to display an empty string, which users can not recognize there is
  16133. * a value and it might look like a bug.
  16134. */
  16135. function makeValueReadable(value, valueType, useUTC) {
  16136. var USER_READABLE_DEFUALT_TIME_PATTERN = '{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}';
  16137. function stringToUserReadable(str) {
  16138. return str && trim(str) ? str : '-';
  16139. }
  16140. function isNumberUserReadable(num) {
  16141. return !!(num != null && !isNaN(num) && isFinite(num));
  16142. }
  16143. var isTypeTime = valueType === 'time';
  16144. var isValueDate = value instanceof Date;
  16145. if (isTypeTime || isValueDate) {
  16146. var date = isTypeTime ? parseDate(value) : value;
  16147. if (!isNaN(+date)) {
  16148. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  16149. } else if (isValueDate) {
  16150. return '-';
  16151. } // In other cases, continue to try to display the value in the following code.
  16152. }
  16153. if (valueType === 'ordinal') {
  16154. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  16155. } // By default.
  16156. var numericResult = numericToNumber(value);
  16157. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : typeof value === 'boolean' ? value + '' : '-';
  16158. }
  16159. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16160. var wrapVar = function (varName, seriesIdx) {
  16161. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16162. };
  16163. /**
  16164. * Template formatter
  16165. * @param {Array.<Object>|Object} paramsList
  16166. */
  16167. function formatTpl(tpl, paramsList, encode) {
  16168. if (!isArray(paramsList)) {
  16169. paramsList = [paramsList];
  16170. }
  16171. var seriesLen = paramsList.length;
  16172. if (!seriesLen) {
  16173. return '';
  16174. }
  16175. var $vars = paramsList[0].$vars || [];
  16176. for (var i = 0; i < $vars.length; i++) {
  16177. var alias = TPL_VAR_ALIAS[i];
  16178. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16179. }
  16180. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16181. for (var k = 0; k < $vars.length; k++) {
  16182. var val = paramsList[seriesIdx][$vars[k]];
  16183. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16184. }
  16185. }
  16186. return tpl;
  16187. }
  16188. /**
  16189. * simple Template formatter
  16190. */
  16191. function formatTplSimple(tpl, param, encode) {
  16192. each(param, function (value, key) {
  16193. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  16194. });
  16195. return tpl;
  16196. }
  16197. function getTooltipMarker(inOpt, extraCssText) {
  16198. var opt = isString(inOpt) ? {
  16199. color: inOpt,
  16200. extraCssText: extraCssText
  16201. } : inOpt || {};
  16202. var color = opt.color;
  16203. var type = opt.type;
  16204. extraCssText = opt.extraCssText;
  16205. var renderMode = opt.renderMode || 'html';
  16206. if (!color) {
  16207. return '';
  16208. }
  16209. if (renderMode === 'html') {
  16210. 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
  16211. + 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>';
  16212. } else {
  16213. // Should better not to auto generate style name by auto-increment number here.
  16214. // Because this util is usually called in tooltip formatter, which is probably
  16215. // called repeatedly when mouse move and the auto-increment number increases fast.
  16216. // Users can make their own style name by theirselves, make it unique and readable.
  16217. var markerId = opt.markerId || 'markerX';
  16218. return {
  16219. renderMode: renderMode,
  16220. content: '{' + markerId + '|} ',
  16221. style: type === 'subItem' ? {
  16222. width: 4,
  16223. height: 4,
  16224. borderRadius: 2,
  16225. backgroundColor: color
  16226. } : {
  16227. width: 10,
  16228. height: 10,
  16229. borderRadius: 5,
  16230. backgroundColor: color
  16231. }
  16232. };
  16233. }
  16234. }
  16235. /**
  16236. * @deprecated Use `time/format` instead.
  16237. * ISO Date format
  16238. * @param {string} tpl
  16239. * @param {number} value
  16240. * @param {boolean} [isUTC=false] Default in local time.
  16241. * see `module:echarts/scale/Time`
  16242. * and `module:echarts/util/number#parseDate`.
  16243. * @inner
  16244. */
  16245. function formatTime(tpl, value, isUTC) {
  16246. if ("development" !== 'production') {
  16247. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  16248. }
  16249. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16250. tpl = 'MM-dd\nyyyy';
  16251. }
  16252. var date = parseDate(value);
  16253. var getUTC = isUTC ? 'getUTC' : 'get';
  16254. var y = date[getUTC + 'FullYear']();
  16255. var M = date[getUTC + 'Month']() + 1;
  16256. var d = date[getUTC + 'Date']();
  16257. var h = date[getUTC + 'Hours']();
  16258. var m = date[getUTC + 'Minutes']();
  16259. var s = date[getUTC + 'Seconds']();
  16260. var S = date[getUTC + 'Milliseconds']();
  16261. 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));
  16262. return tpl;
  16263. }
  16264. /**
  16265. * Capital first
  16266. * @param {string} str
  16267. * @return {string}
  16268. */
  16269. function capitalFirst(str) {
  16270. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16271. }
  16272. /**
  16273. * @return Never be null/undefined.
  16274. */
  16275. function convertToColorString(color, defaultColor) {
  16276. defaultColor = defaultColor || 'transparent';
  16277. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  16278. }
  16279. /**
  16280. * open new tab
  16281. * @param link url
  16282. * @param target blank or self
  16283. */
  16284. function windowOpen(link, target) {
  16285. /* global window */
  16286. if (target === '_blank' || target === 'blank') {
  16287. var blank = window.open();
  16288. blank.opener = null;
  16289. blank.location.href = link;
  16290. } else {
  16291. window.open(link, target);
  16292. }
  16293. }
  16294. var each$1 = each;
  16295. /**
  16296. * @public
  16297. */
  16298. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16299. /**
  16300. * @public
  16301. */
  16302. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16303. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16304. var x = 0;
  16305. var y = 0;
  16306. if (maxWidth == null) {
  16307. maxWidth = Infinity;
  16308. }
  16309. if (maxHeight == null) {
  16310. maxHeight = Infinity;
  16311. }
  16312. var currentLineMaxSize = 0;
  16313. group.eachChild(function (child, idx) {
  16314. var rect = child.getBoundingRect();
  16315. var nextChild = group.childAt(idx + 1);
  16316. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16317. var nextX;
  16318. var nextY;
  16319. if (orient === 'horizontal') {
  16320. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16321. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16322. // FIXME compare before adding gap?
  16323. if (nextX > maxWidth || child.newline) {
  16324. x = 0;
  16325. nextX = moveX;
  16326. y += currentLineMaxSize + gap;
  16327. currentLineMaxSize = rect.height;
  16328. } else {
  16329. // FIXME: consider rect.y is not `0`?
  16330. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16331. }
  16332. } else {
  16333. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16334. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16335. if (nextY > maxHeight || child.newline) {
  16336. x += currentLineMaxSize + gap;
  16337. y = 0;
  16338. nextY = moveY;
  16339. currentLineMaxSize = rect.width;
  16340. } else {
  16341. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16342. }
  16343. }
  16344. if (child.newline) {
  16345. return;
  16346. }
  16347. child.x = x;
  16348. child.y = y;
  16349. child.markRedraw();
  16350. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16351. });
  16352. }
  16353. /**
  16354. * VBox or HBox layouting
  16355. * @param {string} orient
  16356. * @param {module:zrender/graphic/Group} group
  16357. * @param {number} gap
  16358. * @param {number} [width=Infinity]
  16359. * @param {number} [height=Infinity]
  16360. */
  16361. var box = boxLayout;
  16362. /**
  16363. * VBox layouting
  16364. * @param {module:zrender/graphic/Group} group
  16365. * @param {number} gap
  16366. * @param {number} [width=Infinity]
  16367. * @param {number} [height=Infinity]
  16368. */
  16369. var vbox = curry(boxLayout, 'vertical');
  16370. /**
  16371. * HBox layouting
  16372. * @param {module:zrender/graphic/Group} group
  16373. * @param {number} gap
  16374. * @param {number} [width=Infinity]
  16375. * @param {number} [height=Infinity]
  16376. */
  16377. var hbox = curry(boxLayout, 'horizontal');
  16378. /**
  16379. * If x or x2 is not specified or 'center' 'left' 'right',
  16380. * the width would be as long as possible.
  16381. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16382. * the height would be as long as possible.
  16383. */
  16384. function getAvailableSize(positionInfo, containerRect, margin) {
  16385. var containerWidth = containerRect.width;
  16386. var containerHeight = containerRect.height;
  16387. var x = parsePercent$1(positionInfo.left, containerWidth);
  16388. var y = parsePercent$1(positionInfo.top, containerHeight);
  16389. var x2 = parsePercent$1(positionInfo.right, containerWidth);
  16390. var y2 = parsePercent$1(positionInfo.bottom, containerHeight);
  16391. (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0);
  16392. (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth);
  16393. (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0);
  16394. (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight);
  16395. margin = normalizeCssArray$1(margin || 0);
  16396. return {
  16397. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16398. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16399. };
  16400. }
  16401. /**
  16402. * Parse position info.
  16403. */
  16404. function getLayoutRect(positionInfo, containerRect, margin) {
  16405. margin = normalizeCssArray$1(margin || 0);
  16406. var containerWidth = containerRect.width;
  16407. var containerHeight = containerRect.height;
  16408. var left = parsePercent$1(positionInfo.left, containerWidth);
  16409. var top = parsePercent$1(positionInfo.top, containerHeight);
  16410. var right = parsePercent$1(positionInfo.right, containerWidth);
  16411. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16412. var width = parsePercent$1(positionInfo.width, containerWidth);
  16413. var height = parsePercent$1(positionInfo.height, containerHeight);
  16414. var verticalMargin = margin[2] + margin[0];
  16415. var horizontalMargin = margin[1] + margin[3];
  16416. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16417. if (isNaN(width)) {
  16418. width = containerWidth - right - horizontalMargin - left;
  16419. }
  16420. if (isNaN(height)) {
  16421. height = containerHeight - bottom - verticalMargin - top;
  16422. }
  16423. if (aspect != null) {
  16424. // If width and height are not given
  16425. // 1. Graph should not exceeds the container
  16426. // 2. Aspect must be keeped
  16427. // 3. Graph should take the space as more as possible
  16428. // FIXME
  16429. // Margin is not considered, because there is no case that both
  16430. // using margin and aspect so far.
  16431. if (isNaN(width) && isNaN(height)) {
  16432. if (aspect > containerWidth / containerHeight) {
  16433. width = containerWidth * 0.8;
  16434. } else {
  16435. height = containerHeight * 0.8;
  16436. }
  16437. } // Calculate width or height with given aspect
  16438. if (isNaN(width)) {
  16439. width = aspect * height;
  16440. }
  16441. if (isNaN(height)) {
  16442. height = width / aspect;
  16443. }
  16444. } // If left is not specified, calculate left from right and width
  16445. if (isNaN(left)) {
  16446. left = containerWidth - right - width - horizontalMargin;
  16447. }
  16448. if (isNaN(top)) {
  16449. top = containerHeight - bottom - height - verticalMargin;
  16450. } // Align left and top
  16451. switch (positionInfo.left || positionInfo.right) {
  16452. case 'center':
  16453. left = containerWidth / 2 - width / 2 - margin[3];
  16454. break;
  16455. case 'right':
  16456. left = containerWidth - width - horizontalMargin;
  16457. break;
  16458. }
  16459. switch (positionInfo.top || positionInfo.bottom) {
  16460. case 'middle':
  16461. case 'center':
  16462. top = containerHeight / 2 - height / 2 - margin[0];
  16463. break;
  16464. case 'bottom':
  16465. top = containerHeight - height - verticalMargin;
  16466. break;
  16467. } // If something is wrong and left, top, width, height are calculated as NaN
  16468. left = left || 0;
  16469. top = top || 0;
  16470. if (isNaN(width)) {
  16471. // Width may be NaN if only one value is given except width
  16472. width = containerWidth - horizontalMargin - left - (right || 0);
  16473. }
  16474. if (isNaN(height)) {
  16475. // Height may be NaN if only one value is given except height
  16476. height = containerHeight - verticalMargin - top - (bottom || 0);
  16477. }
  16478. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16479. rect.margin = margin;
  16480. return rect;
  16481. }
  16482. /**
  16483. * Position a zr element in viewport
  16484. * Group position is specified by either
  16485. * {left, top}, {right, bottom}
  16486. * If all properties exists, right and bottom will be igonred.
  16487. *
  16488. * Logic:
  16489. * 1. Scale (against origin point in parent coord)
  16490. * 2. Rotate (against origin point in parent coord)
  16491. * 3. Translate (with el.position by this method)
  16492. * So this method only fixes the last step 'Translate', which does not affect
  16493. * scaling and rotating.
  16494. *
  16495. * If be called repeatedly with the same input el, the same result will be gotten.
  16496. *
  16497. * Return true if the layout happened.
  16498. *
  16499. * @param el Should have `getBoundingRect` method.
  16500. * @param positionInfo
  16501. * @param positionInfo.left
  16502. * @param positionInfo.top
  16503. * @param positionInfo.right
  16504. * @param positionInfo.bottom
  16505. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  16506. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  16507. * @param containerRect
  16508. * @param margin
  16509. * @param opt
  16510. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  16511. * @param opt.boundingMode
  16512. * Specify how to calculate boundingRect when locating.
  16513. * 'all': Position the boundingRect that is transformed and uioned
  16514. * both itself and its descendants.
  16515. * This mode simplies confine the elements in the bounding
  16516. * of their container (e.g., using 'right: 0').
  16517. * 'raw': Position the boundingRect that is not transformed and only itself.
  16518. * This mode is useful when you want a element can overflow its
  16519. * container. (Consider a rotated circle needs to be located in a corner.)
  16520. * In this mode positionInfo.width/height can only be number.
  16521. */
  16522. function positionElement(el, positionInfo, containerRect, margin, opt, out) {
  16523. var h = !opt || !opt.hv || opt.hv[0];
  16524. var v = !opt || !opt.hv || opt.hv[1];
  16525. var boundingMode = opt && opt.boundingMode || 'all';
  16526. out = out || el;
  16527. out.x = el.x;
  16528. out.y = el.y;
  16529. if (!h && !v) {
  16530. return false;
  16531. }
  16532. var rect;
  16533. if (boundingMode === 'raw') {
  16534. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16535. } else {
  16536. rect = el.getBoundingRect();
  16537. if (el.needLocalTransform()) {
  16538. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16539. // which should not be modified.
  16540. rect = rect.clone();
  16541. rect.applyTransform(transform);
  16542. }
  16543. } // The real width and height can not be specified but calculated by the given el.
  16544. var layoutRect = getLayoutRect(defaults({
  16545. width: rect.width,
  16546. height: rect.height
  16547. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16548. // (see zrender/core/Transformable#getLocalTransform),
  16549. // we can just only modify el.position to get final result.
  16550. var dx = h ? layoutRect.x - rect.x : 0;
  16551. var dy = v ? layoutRect.y - rect.y : 0;
  16552. if (boundingMode === 'raw') {
  16553. out.x = dx;
  16554. out.y = dy;
  16555. } else {
  16556. out.x += dx;
  16557. out.y += dy;
  16558. }
  16559. if (out === el) {
  16560. el.markRedraw();
  16561. }
  16562. return true;
  16563. }
  16564. /**
  16565. * @param option Contains some of the properties in HV_NAMES.
  16566. * @param hvIdx 0: horizontal; 1: vertical.
  16567. */
  16568. function sizeCalculable(option, hvIdx) {
  16569. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  16570. }
  16571. function fetchLayoutMode(ins) {
  16572. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  16573. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  16574. type: layoutMode
  16575. } : null;
  16576. }
  16577. /**
  16578. * Consider Case:
  16579. * When default option has {left: 0, width: 100}, and we set {right: 0}
  16580. * through setOption or media query, using normal zrUtil.merge will cause
  16581. * {right: 0} does not take effect.
  16582. *
  16583. * @example
  16584. * ComponentModel.extend({
  16585. * init: function () {
  16586. * ...
  16587. * let inputPositionParams = layout.getLayoutParams(option);
  16588. * this.mergeOption(inputPositionParams);
  16589. * },
  16590. * mergeOption: function (newOption) {
  16591. * newOption && zrUtil.merge(thisOption, newOption, true);
  16592. * layout.mergeLayoutParam(thisOption, newOption);
  16593. * }
  16594. * });
  16595. *
  16596. * @param targetOption
  16597. * @param newOption
  16598. * @param opt
  16599. */
  16600. function mergeLayoutParam(targetOption, newOption, opt) {
  16601. var ignoreSize = opt && opt.ignoreSize;
  16602. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16603. var hResult = merge(HV_NAMES[0], 0);
  16604. var vResult = merge(HV_NAMES[1], 1);
  16605. copy(HV_NAMES[0], targetOption, hResult);
  16606. copy(HV_NAMES[1], targetOption, vResult);
  16607. function merge(names, hvIdx) {
  16608. var newParams = {};
  16609. var newValueCount = 0;
  16610. var merged = {};
  16611. var mergedValueCount = 0;
  16612. var enoughParamNumber = 2;
  16613. each$1(names, function (name) {
  16614. merged[name] = targetOption[name];
  16615. });
  16616. each$1(names, function (name) {
  16617. // Consider case: newOption.width is null, which is
  16618. // set by user for removing width setting.
  16619. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16620. hasValue(newParams, name) && newValueCount++;
  16621. hasValue(merged, name) && mergedValueCount++;
  16622. });
  16623. if (ignoreSize[hvIdx]) {
  16624. // Only one of left/right is premitted to exist.
  16625. if (hasValue(newOption, names[1])) {
  16626. merged[names[2]] = null;
  16627. } else if (hasValue(newOption, names[2])) {
  16628. merged[names[1]] = null;
  16629. }
  16630. return merged;
  16631. } // Case: newOption: {width: ..., right: ...},
  16632. // or targetOption: {right: ...} and newOption: {width: ...},
  16633. // There is no conflict when merged only has params count
  16634. // little than enoughParamNumber.
  16635. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16636. return merged;
  16637. } // Case: newOption: {width: ..., right: ...},
  16638. // Than we can make sure user only want those two, and ignore
  16639. // all origin params in targetOption.
  16640. else if (newValueCount >= enoughParamNumber) {
  16641. return newParams;
  16642. } else {
  16643. // Chose another param from targetOption by priority.
  16644. for (var i = 0; i < names.length; i++) {
  16645. var name_1 = names[i];
  16646. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16647. newParams[name_1] = targetOption[name_1];
  16648. break;
  16649. }
  16650. }
  16651. return newParams;
  16652. }
  16653. }
  16654. function hasProp(obj, name) {
  16655. return obj.hasOwnProperty(name);
  16656. }
  16657. function hasValue(obj, name) {
  16658. return obj[name] != null && obj[name] !== 'auto';
  16659. }
  16660. function copy(names, target, source) {
  16661. each$1(names, function (name) {
  16662. target[name] = source[name];
  16663. });
  16664. }
  16665. }
  16666. /**
  16667. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16668. */
  16669. function getLayoutParams(source) {
  16670. return copyLayoutParams({}, source);
  16671. }
  16672. /**
  16673. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16674. * @param {Object} source
  16675. * @return {Object} Result contains those props.
  16676. */
  16677. function copyLayoutParams(target, source) {
  16678. source && target && each$1(LOCATION_PARAMS, function (name) {
  16679. source.hasOwnProperty(name) && (target[name] = source[name]);
  16680. });
  16681. return target;
  16682. }
  16683. var inner = makeInner();
  16684. var ComponentModel =
  16685. /** @class */
  16686. function (_super) {
  16687. __extends(ComponentModel, _super);
  16688. function ComponentModel(option, parentModel, ecModel) {
  16689. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16690. _this.uid = getUID('ec_cpt_model');
  16691. return _this;
  16692. }
  16693. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16694. this.mergeDefaultAndTheme(option, ecModel);
  16695. };
  16696. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16697. var layoutMode = fetchLayoutMode(this);
  16698. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16699. var themeModel = ecModel.getTheme();
  16700. merge(option, themeModel.get(this.mainType));
  16701. merge(option, this.getDefaultOption());
  16702. if (layoutMode) {
  16703. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16704. }
  16705. };
  16706. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16707. merge(this.option, option, true);
  16708. var layoutMode = fetchLayoutMode(this);
  16709. if (layoutMode) {
  16710. mergeLayoutParam(this.option, option, layoutMode);
  16711. }
  16712. };
  16713. /**
  16714. * Called immediately after `init` or `mergeOption` of this instance called.
  16715. */
  16716. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16717. /**
  16718. * [How to declare defaultOption]:
  16719. *
  16720. * (A) If using class declaration in typescript (since echarts 5):
  16721. * ```ts
  16722. * import {ComponentOption} from '../model/option.js';
  16723. * export interface XxxOption extends ComponentOption {
  16724. * aaa: number
  16725. * }
  16726. * export class XxxModel extends Component {
  16727. * static type = 'xxx';
  16728. * static defaultOption: XxxOption = {
  16729. * aaa: 123
  16730. * }
  16731. * }
  16732. * Component.registerClass(XxxModel);
  16733. * ```
  16734. * ```ts
  16735. * import {inheritDefaultOption} from '../util/component.js';
  16736. * import {XxxModel, XxxOption} from './XxxModel.js';
  16737. * export interface XxxSubOption extends XxxOption {
  16738. * bbb: number
  16739. * }
  16740. * class XxxSubModel extends XxxModel {
  16741. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16742. * bbb: 456
  16743. * })
  16744. * fn() {
  16745. * let opt = this.getDefaultOption();
  16746. * // opt is {aaa: 123, bbb: 456}
  16747. * }
  16748. * }
  16749. * ```
  16750. *
  16751. * (B) If using class extend (previous approach in echarts 3 & 4):
  16752. * ```js
  16753. * let XxxComponent = Component.extend({
  16754. * defaultOption: {
  16755. * xx: 123
  16756. * }
  16757. * })
  16758. * ```
  16759. * ```js
  16760. * let XxxSubComponent = XxxComponent.extend({
  16761. * defaultOption: {
  16762. * yy: 456
  16763. * },
  16764. * fn: function () {
  16765. * let opt = this.getDefaultOption();
  16766. * // opt is {xx: 123, yy: 456}
  16767. * }
  16768. * })
  16769. * ```
  16770. */
  16771. ComponentModel.prototype.getDefaultOption = function () {
  16772. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16773. // in legacy env and auto merge defaultOption. So if using class
  16774. // declaration, defaultOption should be merged manually.
  16775. if (!isExtendedClass(ctor)) {
  16776. // When using ts class, defaultOption must be declared as static.
  16777. return ctor.defaultOption;
  16778. } // FIXME: remove this approach?
  16779. var fields = inner(this);
  16780. if (!fields.defaultOption) {
  16781. var optList = [];
  16782. var clz = ctor;
  16783. while (clz) {
  16784. var opt = clz.prototype.defaultOption;
  16785. opt && optList.push(opt);
  16786. clz = clz.superClass;
  16787. }
  16788. var defaultOption = {};
  16789. for (var i = optList.length - 1; i >= 0; i--) {
  16790. defaultOption = merge(defaultOption, optList[i], true);
  16791. }
  16792. fields.defaultOption = defaultOption;
  16793. }
  16794. return fields.defaultOption;
  16795. };
  16796. /**
  16797. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16798. * The same behavior as `modelUtil.parseFinder`.
  16799. *
  16800. * @param useDefault In many cases like series refer axis and axis refer grid,
  16801. * If axis index / axis id not specified, use the first target as default.
  16802. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16803. */
  16804. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16805. var indexKey = mainType + 'Index';
  16806. var idKey = mainType + 'Id';
  16807. return queryReferringComponents(this.ecModel, mainType, {
  16808. index: this.get(indexKey, true),
  16809. id: this.get(idKey, true)
  16810. }, opt);
  16811. };
  16812. ComponentModel.prototype.getBoxLayoutParams = function () {
  16813. // Consider itself having box layout configs.
  16814. var boxLayoutModel = this;
  16815. return {
  16816. left: boxLayoutModel.get('left'),
  16817. top: boxLayoutModel.get('top'),
  16818. right: boxLayoutModel.get('right'),
  16819. bottom: boxLayoutModel.get('bottom'),
  16820. width: boxLayoutModel.get('width'),
  16821. height: boxLayoutModel.get('height')
  16822. };
  16823. };
  16824. /**
  16825. * Get key for zlevel.
  16826. * If developers don't configure zlevel. We will assign zlevel to series based on the key.
  16827. * For example, lines with trail effect and progressive series will in an individual zlevel.
  16828. */
  16829. ComponentModel.prototype.getZLevelKey = function () {
  16830. return '';
  16831. };
  16832. ComponentModel.prototype.setZLevel = function (zlevel) {
  16833. this.option.zlevel = zlevel;
  16834. };
  16835. ComponentModel.protoInitialize = function () {
  16836. var proto = ComponentModel.prototype;
  16837. proto.type = 'component';
  16838. proto.id = '';
  16839. proto.name = '';
  16840. proto.mainType = '';
  16841. proto.subType = '';
  16842. proto.componentIndex = 0;
  16843. }();
  16844. return ComponentModel;
  16845. }(Model);
  16846. mountExtend(ComponentModel, Model);
  16847. enableClassManagement(ComponentModel);
  16848. enableSubTypeDefaulter(ComponentModel);
  16849. enableTopologicalTravel(ComponentModel, getDependencies);
  16850. function getDependencies(componentType) {
  16851. var deps = [];
  16852. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16853. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16854. }); // Ensure main type.
  16855. deps = map(deps, function (type) {
  16856. return parseClassType(type).main;
  16857. }); // Hack dataset for convenience.
  16858. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16859. deps.unshift('dataset');
  16860. }
  16861. return deps;
  16862. }
  16863. /*
  16864. * Licensed to the Apache Software Foundation (ASF) under one
  16865. * or more contributor license agreements. See the NOTICE file
  16866. * distributed with this work for additional information
  16867. * regarding copyright ownership. The ASF licenses this file
  16868. * to you under the Apache License, Version 2.0 (the
  16869. * "License"); you may not use this file except in compliance
  16870. * with the License. You may obtain a copy of the License at
  16871. *
  16872. * http://www.apache.org/licenses/LICENSE-2.0
  16873. *
  16874. * Unless required by applicable law or agreed to in writing,
  16875. * software distributed under the License is distributed on an
  16876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16877. * KIND, either express or implied. See the License for the
  16878. * specific language governing permissions and limitations
  16879. * under the License.
  16880. */
  16881. /**
  16882. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16883. */
  16884. /*
  16885. * Licensed to the Apache Software Foundation (ASF) under one
  16886. * or more contributor license agreements. See the NOTICE file
  16887. * distributed with this work for additional information
  16888. * regarding copyright ownership. The ASF licenses this file
  16889. * to you under the Apache License, Version 2.0 (the
  16890. * "License"); you may not use this file except in compliance
  16891. * with the License. You may obtain a copy of the License at
  16892. *
  16893. * http://www.apache.org/licenses/LICENSE-2.0
  16894. *
  16895. * Unless required by applicable law or agreed to in writing,
  16896. * software distributed under the License is distributed on an
  16897. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16898. * KIND, either express or implied. See the License for the
  16899. * specific language governing permissions and limitations
  16900. * under the License.
  16901. */
  16902. var platform = ''; // Navigator not exists in node
  16903. if (typeof navigator !== 'undefined') {
  16904. /* global navigator */
  16905. platform = navigator.platform || '';
  16906. }
  16907. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16908. var globalDefault = {
  16909. darkMode: 'auto',
  16910. // backgroundColor: 'rgba(0,0,0,0)',
  16911. colorBy: 'series',
  16912. color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16913. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16914. aria: {
  16915. decal: {
  16916. decals: [{
  16917. color: decalColor,
  16918. dashArrayX: [1, 0],
  16919. dashArrayY: [2, 5],
  16920. symbolSize: 1,
  16921. rotation: Math.PI / 6
  16922. }, {
  16923. color: decalColor,
  16924. symbol: 'circle',
  16925. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16926. dashArrayY: [6, 0],
  16927. symbolSize: 0.8
  16928. }, {
  16929. color: decalColor,
  16930. dashArrayX: [1, 0],
  16931. dashArrayY: [4, 3],
  16932. rotation: -Math.PI / 4
  16933. }, {
  16934. color: decalColor,
  16935. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16936. dashArrayY: [6, 0]
  16937. }, {
  16938. color: decalColor,
  16939. dashArrayX: [[1, 0], [1, 6]],
  16940. dashArrayY: [1, 0, 6, 0],
  16941. rotation: Math.PI / 4
  16942. }, {
  16943. color: decalColor,
  16944. symbol: 'triangle',
  16945. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16946. dashArrayY: [7, 2],
  16947. symbolSize: 0.75
  16948. }]
  16949. }
  16950. },
  16951. // If xAxis and yAxis declared, grid is created by default.
  16952. // grid: {},
  16953. textStyle: {
  16954. // color: '#000',
  16955. // decoration: 'none',
  16956. // PENDING
  16957. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16958. // fontFamily: 'Arial, Verdana, sans-serif',
  16959. fontSize: 12,
  16960. fontStyle: 'normal',
  16961. fontWeight: 'normal'
  16962. },
  16963. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16964. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16965. // Default is source-over
  16966. blendMode: null,
  16967. stateAnimation: {
  16968. duration: 300,
  16969. easing: 'cubicOut'
  16970. },
  16971. animation: 'auto',
  16972. animationDuration: 1000,
  16973. animationDurationUpdate: 500,
  16974. animationEasing: 'cubicInOut',
  16975. animationEasingUpdate: 'cubicInOut',
  16976. animationThreshold: 2000,
  16977. // Configuration for progressive/incremental rendering
  16978. progressiveThreshold: 3000,
  16979. progressive: 400,
  16980. // Threshold of if use single hover layer to optimize.
  16981. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16982. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16983. // which is unexpected.
  16984. // see example <echarts/test/heatmap-large.html>.
  16985. hoverLayerThreshold: 3000,
  16986. // See: module:echarts/scale/Time
  16987. useUTC: false
  16988. };
  16989. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'itemGroupId', 'seriesName']);
  16990. var SOURCE_FORMAT_ORIGINAL = 'original';
  16991. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16992. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16993. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16994. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16995. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16996. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16997. var SERIES_LAYOUT_BY_ROW = 'row';
  16998. var BE_ORDINAL = {
  16999. Must: 1,
  17000. Might: 2,
  17001. Not: 3 // Other cases
  17002. };
  17003. var innerGlobalModel = makeInner();
  17004. /**
  17005. * MUST be called before mergeOption of all series.
  17006. */
  17007. function resetSourceDefaulter(ecModel) {
  17008. // `datasetMap` is used to make default encode.
  17009. innerGlobalModel(ecModel).datasetMap = createHashMap();
  17010. }
  17011. /**
  17012. * [The strategy of the arrengment of data dimensions for dataset]:
  17013. * "value way": all axes are non-category axes. So series one by one take
  17014. * several (the number is coordSysDims.length) dimensions from dataset.
  17015. * The result of data arrengment of data dimensions like:
  17016. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17017. * "category way": at least one axis is category axis. So the the first data
  17018. * dimension is always mapped to the first category axis and shared by
  17019. * all of the series. The other data dimensions are taken by series like
  17020. * "value way" does.
  17021. * The result of data arrengment of data dimensions like:
  17022. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17023. *
  17024. * @return encode Never be `null/undefined`.
  17025. */
  17026. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17027. var encode = {};
  17028. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17029. if (!datasetModel || !coordDimensions) {
  17030. return encode;
  17031. }
  17032. var encodeItemName = [];
  17033. var encodeSeriesName = [];
  17034. var ecModel = seriesModel.ecModel;
  17035. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  17036. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17037. var baseCategoryDimIndex;
  17038. var categoryWayValueDimStart;
  17039. coordDimensions = coordDimensions.slice();
  17040. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  17041. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  17042. name: coordDimInfoLoose
  17043. };
  17044. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17045. baseCategoryDimIndex = coordDimIdx;
  17046. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  17047. }
  17048. encode[coordDimInfo.name] = [];
  17049. });
  17050. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17051. categoryWayDim: categoryWayValueDimStart,
  17052. valueWayDim: 0
  17053. }); // TODO
  17054. // Auto detect first time axis and do arrangement.
  17055. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17056. var coordDimName = coordDimInfo.name;
  17057. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  17058. if (baseCategoryDimIndex == null) {
  17059. var start = datasetRecord.valueWayDim;
  17060. pushDim(encode[coordDimName], start, count);
  17061. pushDim(encodeSeriesName, start, count);
  17062. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  17063. // especially when encode x y specified.
  17064. // consider: when multiple series share one dimension
  17065. // category axis, series name should better use
  17066. // the other dimension name. On the other hand, use
  17067. // both dimensions name.
  17068. } // In category way, the first category axis.
  17069. else if (baseCategoryDimIndex === coordDimIdx) {
  17070. pushDim(encode[coordDimName], 0, count);
  17071. pushDim(encodeItemName, 0, count);
  17072. } // In category way, the other axis.
  17073. else {
  17074. var start = datasetRecord.categoryWayDim;
  17075. pushDim(encode[coordDimName], start, count);
  17076. pushDim(encodeSeriesName, start, count);
  17077. datasetRecord.categoryWayDim += count;
  17078. }
  17079. });
  17080. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17081. for (var i = 0; i < idxCount; i++) {
  17082. dimIdxArr.push(idxFrom + i);
  17083. }
  17084. }
  17085. function getDataDimCountOnCoordDim(coordDimInfo) {
  17086. var dimsDef = coordDimInfo.dimsDef;
  17087. return dimsDef ? dimsDef.length : 1;
  17088. }
  17089. encodeItemName.length && (encode.itemName = encodeItemName);
  17090. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17091. return encode;
  17092. }
  17093. /**
  17094. * Work for data like [{name: ..., value: ...}, ...].
  17095. *
  17096. * @return encode Never be `null/undefined`.
  17097. */
  17098. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17099. var encode = {};
  17100. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17101. if (!datasetModel) {
  17102. return encode;
  17103. }
  17104. var sourceFormat = source.sourceFormat;
  17105. var dimensionsDefine = source.dimensionsDefine;
  17106. var potentialNameDimIndex;
  17107. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17108. each(dimensionsDefine, function (dim, idx) {
  17109. if ((isObject(dim) ? dim.name : dim) === 'name') {
  17110. potentialNameDimIndex = idx;
  17111. }
  17112. });
  17113. }
  17114. var idxResult = function () {
  17115. var idxRes0 = {};
  17116. var idxRes1 = {};
  17117. var guessRecords = []; // 5 is an experience value.
  17118. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17119. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17120. guessRecords.push(guessResult);
  17121. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17122. // and then find a name dim with the priority:
  17123. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17124. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17125. idxRes0.v = i;
  17126. }
  17127. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17128. idxRes0.n = i;
  17129. }
  17130. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17131. return idxRes0;
  17132. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17133. // find the first BE_ORDINAL.Might as the value dim,
  17134. // and then find a name dim with the priority:
  17135. // "other dim" > "the value dim itself".
  17136. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17137. // treated as number.
  17138. if (!isPureNumber) {
  17139. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17140. idxRes1.v = i;
  17141. }
  17142. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17143. idxRes1.n = i;
  17144. }
  17145. }
  17146. }
  17147. function fulfilled(idxResult) {
  17148. return idxResult.v != null && idxResult.n != null;
  17149. }
  17150. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17151. }();
  17152. if (idxResult) {
  17153. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  17154. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label uses itemName in charts.
  17155. // So we don't set encodeLabel here.
  17156. encode.itemName = [nameDimIndex];
  17157. encode.seriesName = [nameDimIndex];
  17158. }
  17159. return encode;
  17160. }
  17161. /**
  17162. * @return If return null/undefined, indicate that should not use datasetModel.
  17163. */
  17164. function querySeriesUpstreamDatasetModel(seriesModel) {
  17165. // Caution: consider the scenario:
  17166. // A dataset is declared and a series is not expected to use the dataset,
  17167. // and at the beginning `setOption({series: { noData })` (just prepare other
  17168. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17169. // the user should set an empty array to avoid that dataset is used by default.
  17170. var thisData = seriesModel.get('data', true);
  17171. if (!thisData) {
  17172. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  17173. index: seriesModel.get('datasetIndex', true),
  17174. id: seriesModel.get('datasetId', true)
  17175. }, SINGLE_REFERRING).models[0];
  17176. }
  17177. }
  17178. /**
  17179. * @return Always return an array event empty.
  17180. */
  17181. function queryDatasetUpstreamDatasetModels(datasetModel) {
  17182. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  17183. // Otherwise, no reference.
  17184. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  17185. return [];
  17186. }
  17187. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  17188. index: datasetModel.get('fromDatasetIndex', true),
  17189. id: datasetModel.get('fromDatasetId', true)
  17190. }, SINGLE_REFERRING).models;
  17191. }
  17192. /**
  17193. * The rule should not be complex, otherwise user might not
  17194. * be able to known where the data is wrong.
  17195. * The code is ugly, but how to make it neat?
  17196. */
  17197. function guessOrdinal(source, dimIndex) {
  17198. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17199. } // dimIndex may be overflow source data.
  17200. // return {BE_ORDINAL}
  17201. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17202. var result; // Experience value.
  17203. var maxLoop = 5;
  17204. if (isTypedArray(data)) {
  17205. return BE_ORDINAL.Not;
  17206. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17207. // always exists in source.
  17208. var dimName;
  17209. var dimType;
  17210. if (dimensionsDefine) {
  17211. var dimDefItem = dimensionsDefine[dimIndex];
  17212. if (isObject(dimDefItem)) {
  17213. dimName = dimDefItem.name;
  17214. dimType = dimDefItem.type;
  17215. } else if (isString(dimDefItem)) {
  17216. dimName = dimDefItem;
  17217. }
  17218. }
  17219. if (dimType != null) {
  17220. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17221. }
  17222. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17223. var dataArrayRows = data;
  17224. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17225. var sample = dataArrayRows[dimIndex];
  17226. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17227. if ((result = detectValue(sample[startIndex + i])) != null) {
  17228. return result;
  17229. }
  17230. }
  17231. } else {
  17232. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  17233. var row = dataArrayRows[startIndex + i];
  17234. if (row && (result = detectValue(row[dimIndex])) != null) {
  17235. return result;
  17236. }
  17237. }
  17238. }
  17239. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17240. var dataObjectRows = data;
  17241. if (!dimName) {
  17242. return BE_ORDINAL.Not;
  17243. }
  17244. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  17245. var item = dataObjectRows[i];
  17246. if (item && (result = detectValue(item[dimName])) != null) {
  17247. return result;
  17248. }
  17249. }
  17250. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17251. var dataKeyedColumns = data;
  17252. if (!dimName) {
  17253. return BE_ORDINAL.Not;
  17254. }
  17255. var sample = dataKeyedColumns[dimName];
  17256. if (!sample || isTypedArray(sample)) {
  17257. return BE_ORDINAL.Not;
  17258. }
  17259. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17260. if ((result = detectValue(sample[i])) != null) {
  17261. return result;
  17262. }
  17263. }
  17264. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17265. var dataOriginal = data;
  17266. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  17267. var item = dataOriginal[i];
  17268. var val = getDataItemValue(item);
  17269. if (!isArray(val)) {
  17270. return BE_ORDINAL.Not;
  17271. }
  17272. if ((result = detectValue(val[dimIndex])) != null) {
  17273. return result;
  17274. }
  17275. }
  17276. }
  17277. function detectValue(val) {
  17278. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17279. // `isFinit('')` get `true`.
  17280. if (val != null && isFinite(val) && val !== '') {
  17281. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17282. } else if (beStr && val !== '-') {
  17283. return BE_ORDINAL.Must;
  17284. }
  17285. }
  17286. return BE_ORDINAL.Not;
  17287. }
  17288. var internalOptionCreatorMap = createHashMap();
  17289. function registerInternalOptionCreator(mainType, creator) {
  17290. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  17291. internalOptionCreatorMap.set(mainType, creator);
  17292. }
  17293. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  17294. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  17295. if (!internalOptionCreator) {
  17296. return newCmptOptionList;
  17297. }
  17298. var internalOptions = internalOptionCreator(ecModel);
  17299. if (!internalOptions) {
  17300. return newCmptOptionList;
  17301. }
  17302. if ("development" !== 'production') {
  17303. for (var i = 0; i < internalOptions.length; i++) {
  17304. assert(isComponentIdInternal(internalOptions[i]));
  17305. }
  17306. }
  17307. return newCmptOptionList.concat(internalOptions);
  17308. }
  17309. var innerColor = makeInner();
  17310. var innerDecal = makeInner();
  17311. var PaletteMixin =
  17312. /** @class */
  17313. function () {
  17314. function PaletteMixin() {}
  17315. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  17316. var defaultPalette = normalizeToArray(this.get('color', true));
  17317. var layeredPalette = this.get('colorLayer', true);
  17318. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  17319. };
  17320. PaletteMixin.prototype.clearColorPalette = function () {
  17321. clearPalette(this, innerColor);
  17322. };
  17323. return PaletteMixin;
  17324. }();
  17325. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  17326. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  17327. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  17328. }
  17329. function getNearestPalette(palettes, requestColorNum) {
  17330. var paletteNum = palettes.length; // TODO palettes must be in order
  17331. for (var i = 0; i < paletteNum; i++) {
  17332. if (palettes[i].length > requestColorNum) {
  17333. return palettes[i];
  17334. }
  17335. }
  17336. return palettes[paletteNum - 1];
  17337. }
  17338. /**
  17339. * @param name MUST NOT be null/undefined. Otherwise call this function
  17340. * twise with the same parameters will get different result.
  17341. * @param scope default this.
  17342. * @return Can be null/undefined
  17343. */
  17344. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  17345. scope = scope || that;
  17346. var scopeFields = inner(scope);
  17347. var paletteIdx = scopeFields.paletteIdx || 0;
  17348. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  17349. if (paletteNameMap.hasOwnProperty(name)) {
  17350. return paletteNameMap[name];
  17351. }
  17352. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  17353. palette = palette || defaultPalette;
  17354. if (!palette || !palette.length) {
  17355. return;
  17356. }
  17357. var pickedPaletteItem = palette[paletteIdx];
  17358. if (name) {
  17359. paletteNameMap[name] = pickedPaletteItem;
  17360. }
  17361. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  17362. return pickedPaletteItem;
  17363. }
  17364. function clearPalette(that, inner) {
  17365. inner(that).paletteIdx = 0;
  17366. inner(that).paletteNameMap = {};
  17367. }
  17368. // Internal method names:
  17369. // -----------------------
  17370. var reCreateSeriesIndices;
  17371. var assertSeriesInitialized;
  17372. var initBase;
  17373. var OPTION_INNER_KEY = '\0_ec_inner';
  17374. var OPTION_INNER_VALUE = 1;
  17375. var BUITIN_COMPONENTS_MAP = {
  17376. grid: 'GridComponent',
  17377. polar: 'PolarComponent',
  17378. geo: 'GeoComponent',
  17379. singleAxis: 'SingleAxisComponent',
  17380. parallel: 'ParallelComponent',
  17381. calendar: 'CalendarComponent',
  17382. graphic: 'GraphicComponent',
  17383. toolbox: 'ToolboxComponent',
  17384. tooltip: 'TooltipComponent',
  17385. axisPointer: 'AxisPointerComponent',
  17386. brush: 'BrushComponent',
  17387. title: 'TitleComponent',
  17388. timeline: 'TimelineComponent',
  17389. markPoint: 'MarkPointComponent',
  17390. markLine: 'MarkLineComponent',
  17391. markArea: 'MarkAreaComponent',
  17392. legend: 'LegendComponent',
  17393. dataZoom: 'DataZoomComponent',
  17394. visualMap: 'VisualMapComponent',
  17395. // aria: 'AriaComponent',
  17396. // dataset: 'DatasetComponent',
  17397. // Dependencies
  17398. xAxis: 'GridComponent',
  17399. yAxis: 'GridComponent',
  17400. angleAxis: 'PolarComponent',
  17401. radiusAxis: 'PolarComponent'
  17402. };
  17403. var BUILTIN_CHARTS_MAP = {
  17404. line: 'LineChart',
  17405. bar: 'BarChart',
  17406. pie: 'PieChart',
  17407. scatter: 'ScatterChart',
  17408. radar: 'RadarChart',
  17409. map: 'MapChart',
  17410. tree: 'TreeChart',
  17411. treemap: 'TreemapChart',
  17412. graph: 'GraphChart',
  17413. gauge: 'GaugeChart',
  17414. funnel: 'FunnelChart',
  17415. parallel: 'ParallelChart',
  17416. sankey: 'SankeyChart',
  17417. boxplot: 'BoxplotChart',
  17418. candlestick: 'CandlestickChart',
  17419. effectScatter: 'EffectScatterChart',
  17420. lines: 'LinesChart',
  17421. heatmap: 'HeatmapChart',
  17422. pictorialBar: 'PictorialBarChart',
  17423. themeRiver: 'ThemeRiverChart',
  17424. sunburst: 'SunburstChart',
  17425. custom: 'CustomChart'
  17426. };
  17427. var componetsMissingLogPrinted = {};
  17428. function checkMissingComponents(option) {
  17429. each(option, function (componentOption, mainType) {
  17430. if (!ComponentModel.hasClass(mainType)) {
  17431. var componentImportName = BUITIN_COMPONENTS_MAP[mainType];
  17432. if (componentImportName && !componetsMissingLogPrinted[componentImportName]) {
  17433. error("Component " + mainType + " is used but not imported.\nimport { " + componentImportName + " } from 'echarts/components';\necharts.use([" + componentImportName + "]);");
  17434. componetsMissingLogPrinted[componentImportName] = true;
  17435. }
  17436. }
  17437. });
  17438. }
  17439. var GlobalModel =
  17440. /** @class */
  17441. function (_super) {
  17442. __extends(GlobalModel, _super);
  17443. function GlobalModel() {
  17444. return _super !== null && _super.apply(this, arguments) || this;
  17445. }
  17446. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  17447. theme = theme || {};
  17448. this.option = null; // Mark as not initialized.
  17449. this._theme = new Model(theme);
  17450. this._locale = new Model(locale);
  17451. this._optionManager = optionManager;
  17452. };
  17453. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  17454. if ("development" !== 'production') {
  17455. assert(option != null, 'option is null/undefined');
  17456. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  17457. }
  17458. var innerOpt = normalizeSetOptionInput(opts);
  17459. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  17460. this._resetOption(null, innerOpt);
  17461. };
  17462. /**
  17463. * @param type null/undefined: reset all.
  17464. * 'recreate': force recreate all.
  17465. * 'timeline': only reset timeline option
  17466. * 'media': only reset media query option
  17467. * @return Whether option changed.
  17468. */
  17469. GlobalModel.prototype.resetOption = function (type, opt) {
  17470. return this._resetOption(type, normalizeSetOptionInput(opt));
  17471. };
  17472. GlobalModel.prototype._resetOption = function (type, opt) {
  17473. var optionChanged = false;
  17474. var optionManager = this._optionManager;
  17475. if (!type || type === 'recreate') {
  17476. var baseOption = optionManager.mountOption(type === 'recreate');
  17477. if ("development" !== 'production') {
  17478. checkMissingComponents(baseOption);
  17479. }
  17480. if (!this.option || type === 'recreate') {
  17481. initBase(this, baseOption);
  17482. } else {
  17483. this.restoreData();
  17484. this._mergeOption(baseOption, opt);
  17485. }
  17486. optionChanged = true;
  17487. }
  17488. if (type === 'timeline' || type === 'media') {
  17489. this.restoreData();
  17490. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  17491. // it should better not have the same props with `MediaUnit['option']`.
  17492. // Because either `option2` or `MediaUnit['option']` will be always merged to "current option"
  17493. // rather than original "baseOption". If they both override a prop, the result might be
  17494. // unexpected when media state changed after `setOption` called.
  17495. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  17496. // (`{baseOption, media}`) in `setOption`.
  17497. // For `timeline`, the case is the same.
  17498. if (!type || type === 'recreate' || type === 'timeline') {
  17499. var timelineOption = optionManager.getTimelineOption(this);
  17500. if (timelineOption) {
  17501. optionChanged = true;
  17502. this._mergeOption(timelineOption, opt);
  17503. }
  17504. }
  17505. if (!type || type === 'recreate' || type === 'media') {
  17506. var mediaOptions = optionManager.getMediaOption(this);
  17507. if (mediaOptions.length) {
  17508. each(mediaOptions, function (mediaOption) {
  17509. optionChanged = true;
  17510. this._mergeOption(mediaOption, opt);
  17511. }, this);
  17512. }
  17513. }
  17514. return optionChanged;
  17515. };
  17516. GlobalModel.prototype.mergeOption = function (option) {
  17517. this._mergeOption(option, null);
  17518. };
  17519. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  17520. var option = this.option;
  17521. var componentsMap = this._componentsMap;
  17522. var componentsCount = this._componentsCount;
  17523. var newCmptTypes = [];
  17524. var newCmptTypeMap = createHashMap();
  17525. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  17526. resetSourceDefaulter(this); // If no component class, merge directly.
  17527. // For example: color, animaiton options, etc.
  17528. each(newOption, function (componentOption, mainType) {
  17529. if (componentOption == null) {
  17530. return;
  17531. }
  17532. if (!ComponentModel.hasClass(mainType)) {
  17533. // globalSettingTask.dirty();
  17534. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17535. } else if (mainType) {
  17536. newCmptTypes.push(mainType);
  17537. newCmptTypeMap.set(mainType, true);
  17538. }
  17539. });
  17540. if (replaceMergeMainTypeMap) {
  17541. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  17542. // we trade it as it is declared in option as `{xxx: []}`. Because:
  17543. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  17544. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  17545. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  17546. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  17547. newCmptTypes.push(mainTypeInReplaceMerge);
  17548. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  17549. }
  17550. });
  17551. }
  17552. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17553. function visitComponent(mainType) {
  17554. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  17555. var oldCmptList = componentsMap.get(mainType);
  17556. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  17557. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  17558. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  17559. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  17560. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  17561. // components, which is probably incorrect logic.
  17562. option[mainType] = null;
  17563. componentsMap.set(mainType, null);
  17564. componentsCount.set(mainType, 0);
  17565. var optionsByMainType = [];
  17566. var cmptsByMainType = [];
  17567. var cmptsCountByMainType = 0;
  17568. var tooltipExists;
  17569. var tooltipWarningLogged;
  17570. each(mappingResult, function (resultItem, index) {
  17571. var componentModel = resultItem.existing;
  17572. var newCmptOption = resultItem.newOption;
  17573. if (!newCmptOption) {
  17574. if (componentModel) {
  17575. // Consider where is no new option and should be merged using {},
  17576. // see removeEdgeAndAdd in topologicalTravel and
  17577. // ComponentModel.getAllClassMainTypes.
  17578. componentModel.mergeOption({}, this);
  17579. componentModel.optionUpdated({}, false);
  17580. } // If no both `resultItem.exist` and `resultItem.option`,
  17581. // either it is in `replaceMerge` and not matched by any id,
  17582. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  17583. } else {
  17584. var isSeriesType = mainType === 'series';
  17585. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, !isSeriesType // Give a more detailed warn later if series don't exists
  17586. );
  17587. if (!ComponentModelClass) {
  17588. if ("development" !== 'production') {
  17589. var subType = resultItem.keyInfo.subType;
  17590. var seriesImportName = BUILTIN_CHARTS_MAP[subType];
  17591. if (!componetsMissingLogPrinted[subType]) {
  17592. componetsMissingLogPrinted[subType] = true;
  17593. if (seriesImportName) {
  17594. error("Series " + subType + " is used but not imported.\nimport { " + seriesImportName + " } from 'echarts/charts';\necharts.use([" + seriesImportName + "]);");
  17595. } else {
  17596. error("Unknown series " + subType);
  17597. }
  17598. }
  17599. }
  17600. return;
  17601. } // TODO Before multiple tooltips get supported, we do this check to avoid unexpected exception.
  17602. if (mainType === 'tooltip') {
  17603. if (tooltipExists) {
  17604. if ("development" !== 'production') {
  17605. if (!tooltipWarningLogged) {
  17606. warn('Currently only one tooltip component is allowed.');
  17607. tooltipWarningLogged = true;
  17608. }
  17609. }
  17610. return;
  17611. }
  17612. tooltipExists = true;
  17613. }
  17614. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17615. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17616. componentModel.mergeOption(newCmptOption, this);
  17617. componentModel.optionUpdated(newCmptOption, false);
  17618. } else {
  17619. // PENDING Global as parent ?
  17620. var extraOpt = extend({
  17621. componentIndex: index
  17622. }, resultItem.keyInfo);
  17623. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  17624. extend(componentModel, extraOpt);
  17625. if (resultItem.brandNew) {
  17626. componentModel.__requireNewView = true;
  17627. }
  17628. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  17629. // newCmptOption has been used as componentModel.option
  17630. // and may be merged with theme and default, so pass null
  17631. // to avoid confusion.
  17632. componentModel.optionUpdated(null, true);
  17633. }
  17634. }
  17635. if (componentModel) {
  17636. optionsByMainType.push(componentModel.option);
  17637. cmptsByMainType.push(componentModel);
  17638. cmptsCountByMainType++;
  17639. } else {
  17640. // Always do assign to avoid elided item in array.
  17641. optionsByMainType.push(void 0);
  17642. cmptsByMainType.push(void 0);
  17643. }
  17644. }, this);
  17645. option[mainType] = optionsByMainType;
  17646. componentsMap.set(mainType, cmptsByMainType);
  17647. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  17648. if (mainType === 'series') {
  17649. reCreateSeriesIndices(this);
  17650. }
  17651. } // If no series declared, ensure `_seriesIndices` initialized.
  17652. if (!this._seriesIndices) {
  17653. reCreateSeriesIndices(this);
  17654. }
  17655. };
  17656. /**
  17657. * Get option for output (cloned option and inner info removed)
  17658. */
  17659. GlobalModel.prototype.getOption = function () {
  17660. var option = clone(this.option);
  17661. each(option, function (optInMainType, mainType) {
  17662. if (ComponentModel.hasClass(mainType)) {
  17663. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  17664. // Inner cmpts might not be at last since ec5.0, but still
  17665. // compatible for users: if inner cmpt at last, splice the returned array.
  17666. var realLen = opts.length;
  17667. var metNonInner = false;
  17668. for (var i = realLen - 1; i >= 0; i--) {
  17669. // Remove options with inner id.
  17670. if (opts[i] && !isComponentIdInternal(opts[i])) {
  17671. metNonInner = true;
  17672. } else {
  17673. opts[i] = null;
  17674. !metNonInner && realLen--;
  17675. }
  17676. }
  17677. opts.length = realLen;
  17678. option[mainType] = opts;
  17679. }
  17680. });
  17681. delete option[OPTION_INNER_KEY];
  17682. return option;
  17683. };
  17684. GlobalModel.prototype.getTheme = function () {
  17685. return this._theme;
  17686. };
  17687. GlobalModel.prototype.getLocaleModel = function () {
  17688. return this._locale;
  17689. };
  17690. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17691. this._payload = payload;
  17692. };
  17693. GlobalModel.prototype.getUpdatePayload = function () {
  17694. return this._payload;
  17695. };
  17696. /**
  17697. * @param idx If not specified, return the first one.
  17698. */
  17699. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17700. var list = this._componentsMap.get(mainType);
  17701. if (list) {
  17702. var cmpt = list[idx || 0];
  17703. if (cmpt) {
  17704. return cmpt;
  17705. } else if (idx == null) {
  17706. for (var i = 0; i < list.length; i++) {
  17707. if (list[i]) {
  17708. return list[i];
  17709. }
  17710. }
  17711. }
  17712. }
  17713. };
  17714. /**
  17715. * @return Never be null/undefined.
  17716. */
  17717. GlobalModel.prototype.queryComponents = function (condition) {
  17718. var mainType = condition.mainType;
  17719. if (!mainType) {
  17720. return [];
  17721. }
  17722. var index = condition.index;
  17723. var id = condition.id;
  17724. var name = condition.name;
  17725. var cmpts = this._componentsMap.get(mainType);
  17726. if (!cmpts || !cmpts.length) {
  17727. return [];
  17728. }
  17729. var result;
  17730. if (index != null) {
  17731. result = [];
  17732. each(normalizeToArray(index), function (idx) {
  17733. cmpts[idx] && result.push(cmpts[idx]);
  17734. });
  17735. } else if (id != null) {
  17736. result = queryByIdOrName('id', id, cmpts);
  17737. } else if (name != null) {
  17738. result = queryByIdOrName('name', name, cmpts);
  17739. } else {
  17740. // Return all non-empty components in that mainType
  17741. result = filter(cmpts, function (cmpt) {
  17742. return !!cmpt;
  17743. });
  17744. }
  17745. return filterBySubType(result, condition);
  17746. };
  17747. /**
  17748. * The interface is different from queryComponents,
  17749. * which is convenient for inner usage.
  17750. *
  17751. * @usage
  17752. * let result = findComponents(
  17753. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17754. * );
  17755. * let result = findComponents(
  17756. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17757. * );
  17758. * let result = findComponents(
  17759. * {mainType: 'series',
  17760. * filter: function (model, index) {...}}
  17761. * );
  17762. * // result like [component0, componnet1, ...]
  17763. */
  17764. GlobalModel.prototype.findComponents = function (condition) {
  17765. var query = condition.query;
  17766. var mainType = condition.mainType;
  17767. var queryCond = getQueryCond(query);
  17768. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17769. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17770. return !!cmpt;
  17771. });
  17772. return doFilter(filterBySubType(result, condition));
  17773. function getQueryCond(q) {
  17774. var indexAttr = mainType + 'Index';
  17775. var idAttr = mainType + 'Id';
  17776. var nameAttr = mainType + 'Name';
  17777. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17778. mainType: mainType,
  17779. // subType will be filtered finally.
  17780. index: q[indexAttr],
  17781. id: q[idAttr],
  17782. name: q[nameAttr]
  17783. } : null;
  17784. }
  17785. function doFilter(res) {
  17786. return condition.filter ? filter(res, condition.filter) : res;
  17787. }
  17788. };
  17789. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17790. var componentsMap = this._componentsMap;
  17791. if (isFunction(mainType)) {
  17792. var ctxForAll_1 = cb;
  17793. var cbForAll_1 = mainType;
  17794. componentsMap.each(function (cmpts, componentType) {
  17795. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17796. var cmpt = cmpts[i];
  17797. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17798. }
  17799. });
  17800. } else {
  17801. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17802. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17803. var cmpt = cmpts[i];
  17804. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17805. }
  17806. }
  17807. };
  17808. /**
  17809. * Get series list before filtered by name.
  17810. */
  17811. GlobalModel.prototype.getSeriesByName = function (name) {
  17812. var nameStr = convertOptionIdName(name, null);
  17813. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17814. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17815. });
  17816. };
  17817. /**
  17818. * Get series list before filtered by index.
  17819. */
  17820. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17821. return this._componentsMap.get('series')[seriesIndex];
  17822. };
  17823. /**
  17824. * Get series list before filtered by type.
  17825. * FIXME: rename to getRawSeriesByType?
  17826. */
  17827. GlobalModel.prototype.getSeriesByType = function (subType) {
  17828. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17829. return !!oneSeries && oneSeries.subType === subType;
  17830. });
  17831. };
  17832. /**
  17833. * Get all series before filtered.
  17834. */
  17835. GlobalModel.prototype.getSeries = function () {
  17836. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17837. return !!oneSeries;
  17838. });
  17839. };
  17840. /**
  17841. * Count series before filtered.
  17842. */
  17843. GlobalModel.prototype.getSeriesCount = function () {
  17844. return this._componentsCount.get('series');
  17845. };
  17846. /**
  17847. * After filtering, series may be different
  17848. * from raw series.
  17849. */
  17850. GlobalModel.prototype.eachSeries = function (cb, context) {
  17851. assertSeriesInitialized(this);
  17852. each(this._seriesIndices, function (rawSeriesIndex) {
  17853. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17854. cb.call(context, series, rawSeriesIndex);
  17855. }, this);
  17856. };
  17857. /**
  17858. * Iterate raw series before filtered.
  17859. *
  17860. * @param {Function} cb
  17861. * @param {*} context
  17862. */
  17863. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17864. each(this._componentsMap.get('series'), function (series) {
  17865. series && cb.call(context, series, series.componentIndex);
  17866. });
  17867. };
  17868. /**
  17869. * After filtering, series may be different.
  17870. * from raw series.
  17871. */
  17872. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17873. assertSeriesInitialized(this);
  17874. each(this._seriesIndices, function (rawSeriesIndex) {
  17875. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17876. if (series.subType === subType) {
  17877. cb.call(context, series, rawSeriesIndex);
  17878. }
  17879. }, this);
  17880. };
  17881. /**
  17882. * Iterate raw series before filtered of given type.
  17883. */
  17884. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17885. return each(this.getSeriesByType(subType), cb, context);
  17886. };
  17887. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17888. assertSeriesInitialized(this);
  17889. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17890. };
  17891. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17892. return (this._seriesIndices || []).slice();
  17893. };
  17894. GlobalModel.prototype.filterSeries = function (cb, context) {
  17895. assertSeriesInitialized(this);
  17896. var newSeriesIndices = [];
  17897. each(this._seriesIndices, function (seriesRawIdx) {
  17898. var series = this._componentsMap.get('series')[seriesRawIdx];
  17899. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17900. }, this);
  17901. this._seriesIndices = newSeriesIndices;
  17902. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17903. };
  17904. GlobalModel.prototype.restoreData = function (payload) {
  17905. reCreateSeriesIndices(this);
  17906. var componentsMap = this._componentsMap;
  17907. var componentTypes = [];
  17908. componentsMap.each(function (components, componentType) {
  17909. if (ComponentModel.hasClass(componentType)) {
  17910. componentTypes.push(componentType);
  17911. }
  17912. });
  17913. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17914. each(componentsMap.get(componentType), function (component) {
  17915. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17916. component.restoreData();
  17917. }
  17918. });
  17919. });
  17920. };
  17921. GlobalModel.internalField = function () {
  17922. reCreateSeriesIndices = function (ecModel) {
  17923. var seriesIndices = ecModel._seriesIndices = [];
  17924. each(ecModel._componentsMap.get('series'), function (series) {
  17925. // series may have been removed by `replaceMerge`.
  17926. series && seriesIndices.push(series.componentIndex);
  17927. });
  17928. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17929. };
  17930. assertSeriesInitialized = function (ecModel) {
  17931. // Components that use _seriesIndices should depends on series component,
  17932. // which make sure that their initialization is after series.
  17933. if ("development" !== 'production') {
  17934. if (!ecModel._seriesIndices) {
  17935. throw new Error('Option should contains series.');
  17936. }
  17937. }
  17938. };
  17939. initBase = function (ecModel, baseOption) {
  17940. // Using OPTION_INNER_KEY to mark that this option cannot be used outside,
  17941. // i.e. `chart.setOption(chart.getModel().option);` is forbidden.
  17942. ecModel.option = {};
  17943. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17944. // before series initialized.
  17945. ecModel._componentsMap = createHashMap({
  17946. series: []
  17947. });
  17948. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17949. // performed before theme and globalDefault merge.
  17950. var airaOption = baseOption.aria;
  17951. if (isObject(airaOption) && airaOption.enabled == null) {
  17952. airaOption.enabled = true;
  17953. }
  17954. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17955. merge(baseOption, globalDefault, false);
  17956. ecModel._mergeOption(baseOption, null);
  17957. };
  17958. }();
  17959. return GlobalModel;
  17960. }(Model);
  17961. function isNotTargetSeries(seriesModel, payload) {
  17962. if (payload) {
  17963. var index = payload.seriesIndex;
  17964. var id = payload.seriesId;
  17965. var name_1 = payload.seriesName;
  17966. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17967. }
  17968. }
  17969. function mergeTheme(option, theme) {
  17970. // PENDING
  17971. // NOT use `colorLayer` in theme if option has `color`
  17972. var notMergeColorLayer = option.color && !option.colorLayer;
  17973. each(theme, function (themeItem, name) {
  17974. if (name === 'colorLayer' && notMergeColorLayer) {
  17975. return;
  17976. } // If it is component model mainType, the model handles that merge later.
  17977. // otherwise, merge them here.
  17978. if (!ComponentModel.hasClass(name)) {
  17979. if (typeof themeItem === 'object') {
  17980. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17981. } else {
  17982. if (option[name] == null) {
  17983. option[name] = themeItem;
  17984. }
  17985. }
  17986. }
  17987. });
  17988. }
  17989. function queryByIdOrName(attr, idOrName, cmpts) {
  17990. // Here is a break from echarts4: string and number are
  17991. // treated as equal.
  17992. if (isArray(idOrName)) {
  17993. var keyMap_1 = createHashMap();
  17994. each(idOrName, function (idOrNameItem) {
  17995. if (idOrNameItem != null) {
  17996. var idName = convertOptionIdName(idOrNameItem, null);
  17997. idName != null && keyMap_1.set(idOrNameItem, true);
  17998. }
  17999. });
  18000. return filter(cmpts, function (cmpt) {
  18001. return cmpt && keyMap_1.get(cmpt[attr]);
  18002. });
  18003. } else {
  18004. var idName_1 = convertOptionIdName(idOrName, null);
  18005. return filter(cmpts, function (cmpt) {
  18006. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  18007. });
  18008. }
  18009. }
  18010. function filterBySubType(components, condition) {
  18011. // Using hasOwnProperty for restrict. Consider
  18012. // subType is undefined in user payload.
  18013. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  18014. return cmpt && cmpt.subType === condition.subType;
  18015. }) : components;
  18016. }
  18017. function normalizeSetOptionInput(opts) {
  18018. var replaceMergeMainTypeMap = createHashMap();
  18019. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  18020. if ("development" !== 'production') {
  18021. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  18022. }
  18023. replaceMergeMainTypeMap.set(mainType, true);
  18024. });
  18025. return {
  18026. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  18027. };
  18028. }
  18029. mixin(GlobalModel, PaletteMixin);
  18030. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isSSR', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  18031. 'getOption', // 'getViewOfComponentModel',
  18032. // 'getViewOfSeriesModel',
  18033. 'getId', 'updateLabelLayout'];
  18034. var ExtensionAPI =
  18035. /** @class */
  18036. function () {
  18037. function ExtensionAPI(ecInstance) {
  18038. each(availableMethods, function (methodName) {
  18039. this[methodName] = bind(ecInstance[methodName], ecInstance);
  18040. }, this);
  18041. }
  18042. return ExtensionAPI;
  18043. }();
  18044. var coordinateSystemCreators = {};
  18045. var CoordinateSystemManager =
  18046. /** @class */
  18047. function () {
  18048. function CoordinateSystemManager() {
  18049. this._coordinateSystems = [];
  18050. }
  18051. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  18052. var coordinateSystems = [];
  18053. each(coordinateSystemCreators, function (creator, type) {
  18054. var list = creator.create(ecModel, api);
  18055. coordinateSystems = coordinateSystems.concat(list || []);
  18056. });
  18057. this._coordinateSystems = coordinateSystems;
  18058. };
  18059. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  18060. each(this._coordinateSystems, function (coordSys) {
  18061. coordSys.update && coordSys.update(ecModel, api);
  18062. });
  18063. };
  18064. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  18065. return this._coordinateSystems.slice();
  18066. };
  18067. CoordinateSystemManager.register = function (type, creator) {
  18068. coordinateSystemCreators[type] = creator;
  18069. };
  18070. CoordinateSystemManager.get = function (type) {
  18071. return coordinateSystemCreators[type];
  18072. };
  18073. return CoordinateSystemManager;
  18074. }();
  18075. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  18076. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  18077. /**
  18078. * TERM EXPLANATIONS:
  18079. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  18080. */
  18081. var OptionManager =
  18082. /** @class */
  18083. function () {
  18084. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18085. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18086. // rawOption cloned and backuped when timeline changed, which does no
  18087. // good to performance. What's more, that both timeline and setOption
  18088. // method supply 'notMerge' brings complex and some problems.
  18089. // Consider this case:
  18090. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18091. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18092. function OptionManager(api) {
  18093. this._timelineOptions = [];
  18094. this._mediaList = [];
  18095. /**
  18096. * -1, means default.
  18097. * empty means no media.
  18098. */
  18099. this._currentMediaIndices = [];
  18100. this._api = api;
  18101. }
  18102. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  18103. if (rawOption) {
  18104. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18105. each(normalizeToArray(rawOption.series), function (series) {
  18106. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18107. });
  18108. each(normalizeToArray(rawOption.dataset), function (dataset) {
  18109. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  18110. });
  18111. } // Caution: some series modify option data, if do not clone,
  18112. // it should ensure that the repeat modify correctly
  18113. // (create a new object when modify itself).
  18114. rawOption = clone(rawOption); // FIXME
  18115. // If some property is set in timeline options or media option but
  18116. // not set in baseOption, a warning should be given.
  18117. var optionBackup = this._optionBackup;
  18118. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  18119. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  18120. if (optionBackup) {
  18121. // FIXME
  18122. // the restore merge solution is essentially incorrect.
  18123. // the mapping can not be 100% consistent with ecModel, which probably brings
  18124. // potential bug!
  18125. // The first merge is delayed, because in most cases, users do not call `setOption` twice.
  18126. // let fakeCmptsMap = this._fakeCmptsMap;
  18127. // if (!fakeCmptsMap) {
  18128. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  18129. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  18130. // }
  18131. // mergeToBackupOption(
  18132. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  18133. // );
  18134. // For simplicity, timeline options and media options do not support merge,
  18135. // that is, if you `setOption` twice and both has timeline options, the latter
  18136. // timeline options will not be merged to the former, but just substitute them.
  18137. if (newParsedOption.timelineOptions.length) {
  18138. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  18139. }
  18140. if (newParsedOption.mediaList.length) {
  18141. optionBackup.mediaList = newParsedOption.mediaList;
  18142. }
  18143. if (newParsedOption.mediaDefault) {
  18144. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  18145. }
  18146. } else {
  18147. this._optionBackup = newParsedOption;
  18148. }
  18149. };
  18150. OptionManager.prototype.mountOption = function (isRecreate) {
  18151. var optionBackup = this._optionBackup;
  18152. this._timelineOptions = optionBackup.timelineOptions;
  18153. this._mediaList = optionBackup.mediaList;
  18154. this._mediaDefault = optionBackup.mediaDefault;
  18155. this._currentMediaIndices = [];
  18156. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  18157. // called, and is merged into every new option by inner method `mergeToBackupOption`
  18158. // each time `setOption` called, can be only used in `isRecreate`, because
  18159. // its reliability is under suspicion. In other cases option merge is
  18160. // performed by `model.mergeOption`.
  18161. ? optionBackup.baseOption : this._newBaseOption);
  18162. };
  18163. OptionManager.prototype.getTimelineOption = function (ecModel) {
  18164. var option;
  18165. var timelineOptions = this._timelineOptions;
  18166. if (timelineOptions.length) {
  18167. // getTimelineOption can only be called after ecModel inited,
  18168. // so we can get currentIndex from timelineModel.
  18169. var timelineModel = ecModel.getComponent('timeline');
  18170. if (timelineModel) {
  18171. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  18172. timelineOptions[timelineModel.getCurrentIndex()]);
  18173. }
  18174. }
  18175. return option;
  18176. };
  18177. OptionManager.prototype.getMediaOption = function (ecModel) {
  18178. var ecWidth = this._api.getWidth();
  18179. var ecHeight = this._api.getHeight();
  18180. var mediaList = this._mediaList;
  18181. var mediaDefault = this._mediaDefault;
  18182. var indices = [];
  18183. var result = []; // No media defined.
  18184. if (!mediaList.length && !mediaDefault) {
  18185. return result;
  18186. } // Multi media may be applied, the latter defined media has higher priority.
  18187. for (var i = 0, len = mediaList.length; i < len; i++) {
  18188. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18189. indices.push(i);
  18190. }
  18191. } // FIXME
  18192. // Whether mediaDefault should force users to provide? Otherwise
  18193. // the change by media query can not be recorvered.
  18194. if (!indices.length && mediaDefault) {
  18195. indices = [-1];
  18196. }
  18197. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18198. result = map(indices, function (index) {
  18199. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  18200. });
  18201. } // Otherwise return nothing.
  18202. this._currentMediaIndices = indices;
  18203. return result;
  18204. };
  18205. return OptionManager;
  18206. }();
  18207. /**
  18208. * [RAW_OPTION_PATTERNS]
  18209. * (Note: "series: []" represents all other props in `ECUnitOption`)
  18210. *
  18211. * (1) No prop "baseOption" declared:
  18212. * Root option is used as "baseOption" (except prop "options" and "media").
  18213. * ```js
  18214. * option = {
  18215. * series: [],
  18216. * timeline: {},
  18217. * options: [],
  18218. * };
  18219. * option = {
  18220. * series: [],
  18221. * media: {},
  18222. * };
  18223. * option = {
  18224. * series: [],
  18225. * timeline: {},
  18226. * options: [],
  18227. * media: {},
  18228. * }
  18229. * ```
  18230. *
  18231. * (2) Prop "baseOption" declared:
  18232. * If "baseOption" declared, `ECUnitOption` props can only be declared
  18233. * inside "baseOption" except prop "timeline" (compat ec2).
  18234. * ```js
  18235. * option = {
  18236. * baseOption: {
  18237. * timeline: {},
  18238. * series: [],
  18239. * },
  18240. * options: []
  18241. * };
  18242. * option = {
  18243. * baseOption: {
  18244. * series: [],
  18245. * },
  18246. * media: []
  18247. * };
  18248. * option = {
  18249. * baseOption: {
  18250. * timeline: {},
  18251. * series: [],
  18252. * },
  18253. * options: []
  18254. * media: []
  18255. * };
  18256. * option = {
  18257. * // ec3 compat ec2: allow (only) `timeline` declared
  18258. * // outside baseOption. Keep this setting for compat.
  18259. * timeline: {},
  18260. * baseOption: {
  18261. * series: [],
  18262. * },
  18263. * options: [],
  18264. * media: []
  18265. * };
  18266. * ```
  18267. */
  18268. function parseRawOption( // `rawOption` May be modified
  18269. rawOption, optionPreprocessorFuncs, isNew) {
  18270. var mediaList = [];
  18271. var mediaDefault;
  18272. var baseOption;
  18273. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  18274. var timelineOnRoot = rawOption.timeline;
  18275. var timelineOptionsOnRoot = rawOption.options;
  18276. var mediaOnRoot = rawOption.media;
  18277. var hasMedia = !!rawOption.media;
  18278. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  18279. if (declaredBaseOption) {
  18280. baseOption = declaredBaseOption; // For merge option.
  18281. if (!baseOption.timeline) {
  18282. baseOption.timeline = timelineOnRoot;
  18283. }
  18284. } // For convenience, enable to use the root option as the `baseOption`:
  18285. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  18286. else {
  18287. if (hasTimeline || hasMedia) {
  18288. rawOption.options = rawOption.media = null;
  18289. }
  18290. baseOption = rawOption;
  18291. }
  18292. if (hasMedia) {
  18293. if (isArray(mediaOnRoot)) {
  18294. each(mediaOnRoot, function (singleMedia) {
  18295. if ("development" !== 'production') {
  18296. // Real case of wrong config.
  18297. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  18298. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  18299. }
  18300. }
  18301. if (singleMedia && singleMedia.option) {
  18302. if (singleMedia.query) {
  18303. mediaList.push(singleMedia);
  18304. } else if (!mediaDefault) {
  18305. // Use the first media default.
  18306. mediaDefault = singleMedia;
  18307. }
  18308. }
  18309. });
  18310. } else {
  18311. if ("development" !== 'production') {
  18312. // Real case of wrong config.
  18313. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  18314. }
  18315. }
  18316. }
  18317. doPreprocess(baseOption);
  18318. each(timelineOptionsOnRoot, function (option) {
  18319. return doPreprocess(option);
  18320. });
  18321. each(mediaList, function (media) {
  18322. return doPreprocess(media.option);
  18323. });
  18324. function doPreprocess(option) {
  18325. each(optionPreprocessorFuncs, function (preProcess) {
  18326. preProcess(option, isNew);
  18327. });
  18328. }
  18329. return {
  18330. baseOption: baseOption,
  18331. timelineOptions: timelineOptionsOnRoot || [],
  18332. mediaDefault: mediaDefault,
  18333. mediaList: mediaList
  18334. };
  18335. }
  18336. /**
  18337. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18338. * Support: width, height, aspectRatio
  18339. * Can use max or min as prefix.
  18340. */
  18341. function applyMediaQuery(query, ecWidth, ecHeight) {
  18342. var realMap = {
  18343. width: ecWidth,
  18344. height: ecHeight,
  18345. aspectratio: ecWidth / ecHeight // lower case for convenience.
  18346. };
  18347. var applicable = true;
  18348. each(query, function (value, attr) {
  18349. var matched = attr.match(QUERY_REG);
  18350. if (!matched || !matched[1] || !matched[2]) {
  18351. return;
  18352. }
  18353. var operator = matched[1];
  18354. var realAttr = matched[2].toLowerCase();
  18355. if (!compare(realMap[realAttr], value, operator)) {
  18356. applicable = false;
  18357. }
  18358. });
  18359. return applicable;
  18360. }
  18361. function compare(real, expect, operator) {
  18362. if (operator === 'min') {
  18363. return real >= expect;
  18364. } else if (operator === 'max') {
  18365. return real <= expect;
  18366. } else {
  18367. // Equals
  18368. return real === expect;
  18369. }
  18370. }
  18371. function indicesEquals(indices1, indices2) {
  18372. // indices is always order by asc and has only finite number.
  18373. return indices1.join(',') === indices2.join(',');
  18374. }
  18375. var each$2 = each;
  18376. var isObject$1 = isObject;
  18377. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18378. function compatEC2ItemStyle(opt) {
  18379. var itemStyleOpt = opt && opt.itemStyle;
  18380. if (!itemStyleOpt) {
  18381. return;
  18382. }
  18383. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18384. var styleName = POSSIBLE_STYLES[i];
  18385. var normalItemStyleOpt = itemStyleOpt.normal;
  18386. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18387. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18388. if ("development" !== 'production') {
  18389. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  18390. }
  18391. opt[styleName] = opt[styleName] || {};
  18392. if (!opt[styleName].normal) {
  18393. opt[styleName].normal = normalItemStyleOpt[styleName];
  18394. } else {
  18395. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18396. }
  18397. normalItemStyleOpt[styleName] = null;
  18398. }
  18399. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18400. if ("development" !== 'production') {
  18401. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  18402. }
  18403. opt[styleName] = opt[styleName] || {};
  18404. if (!opt[styleName].emphasis) {
  18405. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18406. } else {
  18407. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18408. }
  18409. emphasisItemStyleOpt[styleName] = null;
  18410. }
  18411. }
  18412. }
  18413. function convertNormalEmphasis(opt, optType, useExtend) {
  18414. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18415. var normalOpt = opt[optType].normal;
  18416. var emphasisOpt = opt[optType].emphasis;
  18417. if (normalOpt) {
  18418. if ("development" !== 'production') {
  18419. // eslint-disable-next-line max-len
  18420. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  18421. } // Timeline controlStyle has other properties besides normal and emphasis
  18422. if (useExtend) {
  18423. opt[optType].normal = opt[optType].emphasis = null;
  18424. defaults(opt[optType], normalOpt);
  18425. } else {
  18426. opt[optType] = normalOpt;
  18427. }
  18428. }
  18429. if (emphasisOpt) {
  18430. if ("development" !== 'production') {
  18431. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  18432. }
  18433. opt.emphasis = opt.emphasis || {};
  18434. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  18435. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  18436. if (emphasisOpt.focus) {
  18437. opt.emphasis.focus = emphasisOpt.focus;
  18438. }
  18439. if (emphasisOpt.blurScope) {
  18440. opt.emphasis.blurScope = emphasisOpt.blurScope;
  18441. }
  18442. }
  18443. }
  18444. }
  18445. function removeEC3NormalStatus(opt) {
  18446. convertNormalEmphasis(opt, 'itemStyle');
  18447. convertNormalEmphasis(opt, 'lineStyle');
  18448. convertNormalEmphasis(opt, 'areaStyle');
  18449. convertNormalEmphasis(opt, 'label');
  18450. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18451. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18452. convertNormalEmphasis(opt, 'edgeLabel');
  18453. }
  18454. function compatTextStyle(opt, propName) {
  18455. // Check whether is not object (string\null\undefined ...)
  18456. var labelOptSingle = isObject$1(opt) && opt[propName];
  18457. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  18458. if (textStyle) {
  18459. if ("development" !== 'production') {
  18460. // eslint-disable-next-line max-len
  18461. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  18462. }
  18463. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18464. var textPropName = TEXT_STYLE_OPTIONS[i];
  18465. if (textStyle.hasOwnProperty(textPropName)) {
  18466. labelOptSingle[textPropName] = textStyle[textPropName];
  18467. }
  18468. }
  18469. }
  18470. }
  18471. function compatEC3CommonStyles(opt) {
  18472. if (opt) {
  18473. removeEC3NormalStatus(opt);
  18474. compatTextStyle(opt, 'label');
  18475. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18476. }
  18477. }
  18478. function processSeries(seriesOpt) {
  18479. if (!isObject$1(seriesOpt)) {
  18480. return;
  18481. }
  18482. compatEC2ItemStyle(seriesOpt);
  18483. removeEC3NormalStatus(seriesOpt);
  18484. compatTextStyle(seriesOpt, 'label'); // treemap
  18485. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18486. compatTextStyle(seriesOpt, 'edgeLabel');
  18487. if (seriesOpt.emphasis) {
  18488. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18489. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18490. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18491. }
  18492. var markPoint = seriesOpt.markPoint;
  18493. if (markPoint) {
  18494. compatEC2ItemStyle(markPoint);
  18495. compatEC3CommonStyles(markPoint);
  18496. }
  18497. var markLine = seriesOpt.markLine;
  18498. if (markLine) {
  18499. compatEC2ItemStyle(markLine);
  18500. compatEC3CommonStyles(markLine);
  18501. }
  18502. var markArea = seriesOpt.markArea;
  18503. if (markArea) {
  18504. compatEC3CommonStyles(markArea);
  18505. }
  18506. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18507. // then the backward compat based on option type will not be performed.
  18508. if (seriesOpt.type === 'graph') {
  18509. data = data || seriesOpt.nodes;
  18510. var edgeData = seriesOpt.links || seriesOpt.edges;
  18511. if (edgeData && !isTypedArray(edgeData)) {
  18512. for (var i = 0; i < edgeData.length; i++) {
  18513. compatEC3CommonStyles(edgeData[i]);
  18514. }
  18515. }
  18516. each(seriesOpt.categories, function (opt) {
  18517. removeEC3NormalStatus(opt);
  18518. });
  18519. }
  18520. if (data && !isTypedArray(data)) {
  18521. for (var i = 0; i < data.length; i++) {
  18522. compatEC3CommonStyles(data[i]);
  18523. }
  18524. } // mark point data
  18525. markPoint = seriesOpt.markPoint;
  18526. if (markPoint && markPoint.data) {
  18527. var mpData = markPoint.data;
  18528. for (var i = 0; i < mpData.length; i++) {
  18529. compatEC3CommonStyles(mpData[i]);
  18530. }
  18531. } // mark line data
  18532. markLine = seriesOpt.markLine;
  18533. if (markLine && markLine.data) {
  18534. var mlData = markLine.data;
  18535. for (var i = 0; i < mlData.length; i++) {
  18536. if (isArray(mlData[i])) {
  18537. compatEC3CommonStyles(mlData[i][0]);
  18538. compatEC3CommonStyles(mlData[i][1]);
  18539. } else {
  18540. compatEC3CommonStyles(mlData[i]);
  18541. }
  18542. }
  18543. } // Series
  18544. if (seriesOpt.type === 'gauge') {
  18545. compatTextStyle(seriesOpt, 'axisLabel');
  18546. compatTextStyle(seriesOpt, 'title');
  18547. compatTextStyle(seriesOpt, 'detail');
  18548. } else if (seriesOpt.type === 'treemap') {
  18549. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18550. each(seriesOpt.levels, function (opt) {
  18551. removeEC3NormalStatus(opt);
  18552. });
  18553. } else if (seriesOpt.type === 'tree') {
  18554. removeEC3NormalStatus(seriesOpt.leaves);
  18555. } // sunburst starts from ec4, so it does not need to compat levels.
  18556. }
  18557. function toArr(o) {
  18558. return isArray(o) ? o : o ? [o] : [];
  18559. }
  18560. function toObj(o) {
  18561. return (isArray(o) ? o[0] : o) || {};
  18562. }
  18563. function globalCompatStyle(option, isTheme) {
  18564. each$2(toArr(option.series), function (seriesOpt) {
  18565. isObject$1(seriesOpt) && processSeries(seriesOpt);
  18566. });
  18567. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18568. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18569. each$2(axes, function (axisName) {
  18570. each$2(toArr(option[axisName]), function (axisOpt) {
  18571. if (axisOpt) {
  18572. compatTextStyle(axisOpt, 'axisLabel');
  18573. compatTextStyle(axisOpt.axisPointer, 'label');
  18574. }
  18575. });
  18576. });
  18577. each$2(toArr(option.parallel), function (parallelOpt) {
  18578. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18579. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18580. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18581. });
  18582. each$2(toArr(option.calendar), function (calendarOpt) {
  18583. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18584. compatTextStyle(calendarOpt, 'dayLabel');
  18585. compatTextStyle(calendarOpt, 'monthLabel');
  18586. compatTextStyle(calendarOpt, 'yearLabel');
  18587. }); // radar.name.textStyle
  18588. each$2(toArr(option.radar), function (radarOpt) {
  18589. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  18590. if (radarOpt.name && radarOpt.axisName == null) {
  18591. radarOpt.axisName = radarOpt.name;
  18592. delete radarOpt.name;
  18593. if ("development" !== 'production') {
  18594. deprecateLog('name property in radar component has been changed to axisName');
  18595. }
  18596. }
  18597. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  18598. radarOpt.axisNameGap = radarOpt.nameGap;
  18599. delete radarOpt.nameGap;
  18600. if ("development" !== 'production') {
  18601. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  18602. }
  18603. }
  18604. if ("development" !== 'production') {
  18605. each$2(radarOpt.indicator, function (indicatorOpt) {
  18606. if (indicatorOpt.text) {
  18607. deprecateReplaceLog('text', 'name', 'radar.indicator');
  18608. }
  18609. });
  18610. }
  18611. });
  18612. each$2(toArr(option.geo), function (geoOpt) {
  18613. if (isObject$1(geoOpt)) {
  18614. compatEC3CommonStyles(geoOpt);
  18615. each$2(toArr(geoOpt.regions), function (regionObj) {
  18616. compatEC3CommonStyles(regionObj);
  18617. });
  18618. }
  18619. });
  18620. each$2(toArr(option.timeline), function (timelineOpt) {
  18621. compatEC3CommonStyles(timelineOpt);
  18622. convertNormalEmphasis(timelineOpt, 'label');
  18623. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18624. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18625. var data = timelineOpt.data;
  18626. isArray(data) && each(data, function (item) {
  18627. if (isObject(item)) {
  18628. convertNormalEmphasis(item, 'label');
  18629. convertNormalEmphasis(item, 'itemStyle');
  18630. }
  18631. });
  18632. });
  18633. each$2(toArr(option.toolbox), function (toolboxOpt) {
  18634. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18635. each$2(toolboxOpt.feature, function (featureOpt) {
  18636. convertNormalEmphasis(featureOpt, 'iconStyle');
  18637. });
  18638. });
  18639. compatTextStyle(toObj(option.axisPointer), 'label');
  18640. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  18641. // storedLogs = {};
  18642. }
  18643. function get(opt, path) {
  18644. var pathArr = path.split(',');
  18645. var obj = opt;
  18646. for (var i = 0; i < pathArr.length; i++) {
  18647. obj = obj && obj[pathArr[i]];
  18648. if (obj == null) {
  18649. break;
  18650. }
  18651. }
  18652. return obj;
  18653. }
  18654. function set$1(opt, path, val, overwrite) {
  18655. var pathArr = path.split(',');
  18656. var obj = opt;
  18657. var key;
  18658. var i = 0;
  18659. for (; i < pathArr.length - 1; i++) {
  18660. key = pathArr[i];
  18661. if (obj[key] == null) {
  18662. obj[key] = {};
  18663. }
  18664. obj = obj[key];
  18665. }
  18666. if (overwrite || obj[pathArr[i]] == null) {
  18667. obj[pathArr[i]] = val;
  18668. }
  18669. }
  18670. function compatLayoutProperties(option) {
  18671. option && each(LAYOUT_PROPERTIES, function (prop) {
  18672. if (prop[0] in option && !(prop[1] in option)) {
  18673. option[prop[1]] = option[prop[0]];
  18674. }
  18675. });
  18676. }
  18677. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18678. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18679. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  18680. function compatBarItemStyle(option) {
  18681. var itemStyle = option && option.itemStyle;
  18682. if (itemStyle) {
  18683. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  18684. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  18685. var newName = BAR_ITEM_STYLE_MAP[i][0];
  18686. if (itemStyle[oldName] != null) {
  18687. itemStyle[newName] = itemStyle[oldName];
  18688. if ("development" !== 'production') {
  18689. deprecateReplaceLog(oldName, newName);
  18690. }
  18691. }
  18692. }
  18693. }
  18694. }
  18695. function compatPieLabel(option) {
  18696. if (!option) {
  18697. return;
  18698. }
  18699. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18700. if ("development" !== 'production') {
  18701. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18702. }
  18703. option.edgeDistance = option.margin;
  18704. }
  18705. }
  18706. function compatSunburstState(option) {
  18707. if (!option) {
  18708. return;
  18709. }
  18710. if (option.downplay && !option.blur) {
  18711. option.blur = option.downplay;
  18712. if ("development" !== 'production') {
  18713. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18714. }
  18715. }
  18716. }
  18717. function compatGraphFocus(option) {
  18718. if (!option) {
  18719. return;
  18720. }
  18721. if (option.focusNodeAdjacency != null) {
  18722. option.emphasis = option.emphasis || {};
  18723. if (option.emphasis.focus == null) {
  18724. if ("development" !== 'production') {
  18725. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18726. }
  18727. option.emphasis.focus = 'adjacency';
  18728. }
  18729. }
  18730. }
  18731. function traverseTree(data, cb) {
  18732. if (data) {
  18733. for (var i = 0; i < data.length; i++) {
  18734. cb(data[i]);
  18735. data[i] && traverseTree(data[i].children, cb);
  18736. }
  18737. }
  18738. }
  18739. function globalBackwardCompat(option, isTheme) {
  18740. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18741. option.series = normalizeToArray(option.series);
  18742. each(option.series, function (seriesOpt) {
  18743. if (!isObject(seriesOpt)) {
  18744. return;
  18745. }
  18746. var seriesType = seriesOpt.type;
  18747. if (seriesType === 'line') {
  18748. if (seriesOpt.clipOverflow != null) {
  18749. seriesOpt.clip = seriesOpt.clipOverflow;
  18750. if ("development" !== 'production') {
  18751. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18752. }
  18753. }
  18754. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18755. if (seriesOpt.clockWise != null) {
  18756. seriesOpt.clockwise = seriesOpt.clockWise;
  18757. if ("development" !== 'production') {
  18758. deprecateReplaceLog('clockWise', 'clockwise');
  18759. }
  18760. }
  18761. compatPieLabel(seriesOpt.label);
  18762. var data = seriesOpt.data;
  18763. if (data && !isTypedArray(data)) {
  18764. for (var i = 0; i < data.length; i++) {
  18765. compatPieLabel(data[i]);
  18766. }
  18767. }
  18768. if (seriesOpt.hoverOffset != null) {
  18769. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18770. if (seriesOpt.emphasis.scaleSize = null) {
  18771. if ("development" !== 'production') {
  18772. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18773. }
  18774. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18775. }
  18776. }
  18777. } else if (seriesType === 'gauge') {
  18778. var pointerColor = get(seriesOpt, 'pointer.color');
  18779. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18780. } else if (seriesType === 'bar') {
  18781. compatBarItemStyle(seriesOpt);
  18782. compatBarItemStyle(seriesOpt.backgroundStyle);
  18783. compatBarItemStyle(seriesOpt.emphasis);
  18784. var data = seriesOpt.data;
  18785. if (data && !isTypedArray(data)) {
  18786. for (var i = 0; i < data.length; i++) {
  18787. if (typeof data[i] === 'object') {
  18788. compatBarItemStyle(data[i]);
  18789. compatBarItemStyle(data[i] && data[i].emphasis);
  18790. }
  18791. }
  18792. }
  18793. } else if (seriesType === 'sunburst') {
  18794. var highlightPolicy = seriesOpt.highlightPolicy;
  18795. if (highlightPolicy) {
  18796. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18797. if (!seriesOpt.emphasis.focus) {
  18798. seriesOpt.emphasis.focus = highlightPolicy;
  18799. if ("development" !== 'production') {
  18800. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18801. }
  18802. }
  18803. }
  18804. compatSunburstState(seriesOpt);
  18805. traverseTree(seriesOpt.data, compatSunburstState);
  18806. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18807. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18808. } else if (seriesType === 'map') {
  18809. if (seriesOpt.mapType && !seriesOpt.map) {
  18810. if ("development" !== 'production') {
  18811. deprecateReplaceLog('mapType', 'map', 'map');
  18812. }
  18813. seriesOpt.map = seriesOpt.mapType;
  18814. }
  18815. if (seriesOpt.mapLocation) {
  18816. if ("development" !== 'production') {
  18817. deprecateLog('`mapLocation` is not used anymore.');
  18818. }
  18819. defaults(seriesOpt, seriesOpt.mapLocation);
  18820. }
  18821. }
  18822. if (seriesOpt.hoverAnimation != null) {
  18823. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18824. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18825. if ("development" !== 'production') {
  18826. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18827. }
  18828. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18829. }
  18830. }
  18831. compatLayoutProperties(seriesOpt);
  18832. }); // dataRange has changed to visualMap
  18833. if (option.dataRange) {
  18834. option.visualMap = option.dataRange;
  18835. }
  18836. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18837. var options = option[componentName];
  18838. if (options) {
  18839. if (!isArray(options)) {
  18840. options = [options];
  18841. }
  18842. each(options, function (option) {
  18843. compatLayoutProperties(option);
  18844. });
  18845. }
  18846. });
  18847. }
  18848. // data processing stage is blocked in stream.
  18849. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18850. // (2) Only register once when import repeatedly.
  18851. // Should be executed after series is filtered and before stack calculation.
  18852. function dataStack(ecModel) {
  18853. var stackInfoMap = createHashMap();
  18854. ecModel.eachSeries(function (seriesModel) {
  18855. var stack = seriesModel.get('stack'); // Compatible: when `stack` is set as '', do not stack.
  18856. if (stack) {
  18857. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18858. var data = seriesModel.getData();
  18859. var stackInfo = {
  18860. // Used for calculate axis extent automatically.
  18861. // TODO: Type getCalculationInfo return more specific type?
  18862. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18863. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18864. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18865. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18866. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18867. data: data,
  18868. seriesModel: seriesModel
  18869. }; // If stacked on axis that do not support data stack.
  18870. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18871. return;
  18872. }
  18873. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18874. stackInfoList.push(stackInfo);
  18875. }
  18876. });
  18877. stackInfoMap.each(calculateStack);
  18878. }
  18879. function calculateStack(stackInfoList) {
  18880. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18881. var resultVal = [];
  18882. var resultNaN = [NaN, NaN];
  18883. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18884. var targetData = targetStackInfo.data;
  18885. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  18886. var stackStrategy = targetStackInfo.seriesModel.get('stackStrategy') || 'samesign'; // Should not write on raw data, because stack series model list changes
  18887. // depending on legend selection.
  18888. targetData.modify(dims, function (v0, v1, dataIndex) {
  18889. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18890. // should also be NaN, to draw a appropriate belt area.
  18891. if (isNaN(sum)) {
  18892. return resultNaN;
  18893. }
  18894. var byValue;
  18895. var stackedDataRawIndex;
  18896. if (isStackedByIndex) {
  18897. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18898. } else {
  18899. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18900. } // If stackOver is NaN, chart view will render point on value start.
  18901. var stackedOver = NaN;
  18902. for (var j = idxInStack - 1; j >= 0; j--) {
  18903. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18904. if (!isStackedByIndex) {
  18905. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18906. }
  18907. if (stackedDataRawIndex >= 0) {
  18908. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18909. if (stackStrategy === 'all' // single stack group
  18910. || stackStrategy === 'positive' && val > 0 || stackStrategy === 'negative' && val < 0 || stackStrategy === 'samesign' && sum >= 0 && val > 0 // All positive stack
  18911. || stackStrategy === 'samesign' && sum <= 0 && val < 0 // All negative stack
  18912. ) {
  18913. // The sum has to be very small to be affected by the
  18914. // floating arithmetic problem. An incorrect result will probably
  18915. // cause axis min/max to be filtered incorrectly.
  18916. sum = addSafe(sum, val);
  18917. stackedOver = val;
  18918. break;
  18919. }
  18920. }
  18921. }
  18922. resultVal[0] = sum;
  18923. resultVal[1] = stackedOver;
  18924. return resultVal;
  18925. });
  18926. });
  18927. }
  18928. var SourceImpl =
  18929. /** @class */
  18930. function () {
  18931. function SourceImpl(fields) {
  18932. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18933. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18934. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18935. this.startIndex = fields.startIndex || 0;
  18936. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18937. this.metaRawOption = fields.metaRawOption;
  18938. var dimensionsDefine = this.dimensionsDefine = fields.dimensionsDefine;
  18939. if (dimensionsDefine) {
  18940. for (var i = 0; i < dimensionsDefine.length; i++) {
  18941. var dim = dimensionsDefine[i];
  18942. if (dim.type == null) {
  18943. if (guessOrdinal(this, i) === BE_ORDINAL.Must) {
  18944. dim.type = 'ordinal';
  18945. }
  18946. }
  18947. }
  18948. }
  18949. }
  18950. return SourceImpl;
  18951. }();
  18952. function isSourceInstance(val) {
  18953. return val instanceof SourceImpl;
  18954. }
  18955. /**
  18956. * Create a source from option.
  18957. * NOTE: Created source is immutable. Don't change any properties in it.
  18958. */
  18959. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18960. sourceFormat) {
  18961. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18962. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18963. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18964. var source = new SourceImpl({
  18965. data: sourceData,
  18966. sourceFormat: sourceFormat,
  18967. seriesLayoutBy: seriesLayoutBy,
  18968. dimensionsDefine: determined.dimensionsDefine,
  18969. startIndex: determined.startIndex,
  18970. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18971. metaRawOption: clone(thisMetaRawOption)
  18972. });
  18973. return source;
  18974. }
  18975. /**
  18976. * Wrap original series data for some compatibility cases.
  18977. */
  18978. function createSourceFromSeriesDataOption(data) {
  18979. return new SourceImpl({
  18980. data: data,
  18981. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18982. });
  18983. }
  18984. /**
  18985. * Clone source but excludes source data.
  18986. */
  18987. function cloneSourceShallow(source) {
  18988. return new SourceImpl({
  18989. data: source.data,
  18990. sourceFormat: source.sourceFormat,
  18991. seriesLayoutBy: source.seriesLayoutBy,
  18992. dimensionsDefine: clone(source.dimensionsDefine),
  18993. startIndex: source.startIndex,
  18994. dimensionsDetectedCount: source.dimensionsDetectedCount
  18995. });
  18996. }
  18997. /**
  18998. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18999. */
  19000. function detectSourceFormat(data) {
  19001. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  19002. if (isTypedArray(data)) {
  19003. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  19004. } else if (isArray(data)) {
  19005. // FIXME Whether tolerate null in top level array?
  19006. if (data.length === 0) {
  19007. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19008. }
  19009. for (var i = 0, len = data.length; i < len; i++) {
  19010. var item = data[i];
  19011. if (item == null) {
  19012. continue;
  19013. } else if (isArray(item)) {
  19014. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  19015. break;
  19016. } else if (isObject(item)) {
  19017. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  19018. break;
  19019. }
  19020. }
  19021. } else if (isObject(data)) {
  19022. for (var key in data) {
  19023. if (hasOwn(data, key) && isArrayLike(data[key])) {
  19024. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  19025. break;
  19026. }
  19027. }
  19028. }
  19029. return sourceFormat;
  19030. }
  19031. /**
  19032. * Determine the source definitions from data standalone dimensions definitions
  19033. * are not specified.
  19034. */
  19035. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  19036. // {
  19037. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  19038. // }
  19039. // in `dataset` or `series`
  19040. dimensionsDefine) {
  19041. var dimensionsDetectedCount;
  19042. var startIndex; // PENDING: Could data be null/undefined here?
  19043. // currently, if `dataset.source` not specified, error thrown.
  19044. // if `series.data` not specified, nothing rendered without error thrown.
  19045. // Should test these cases.
  19046. if (!data) {
  19047. return {
  19048. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19049. startIndex: startIndex,
  19050. dimensionsDetectedCount: dimensionsDetectedCount
  19051. };
  19052. }
  19053. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19054. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  19055. // Caution: consider a line with 5 string and 1 number,
  19056. // it still can not be sure it is a head, because the
  19057. // 5 string may be 5 values of category columns.
  19058. if (sourceHeader === 'auto' || sourceHeader == null) {
  19059. arrayRowsTravelFirst(function (val) {
  19060. // '-' is regarded as null/undefined.
  19061. if (val != null && val !== '-') {
  19062. if (isString(val)) {
  19063. startIndex == null && (startIndex = 1);
  19064. } else {
  19065. startIndex = 0;
  19066. }
  19067. } // 10 is an experience number, avoid long loop.
  19068. }, seriesLayoutBy, dataArrayRows, 10);
  19069. } else {
  19070. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  19071. }
  19072. if (!dimensionsDefine && startIndex === 1) {
  19073. dimensionsDefine = [];
  19074. arrayRowsTravelFirst(function (val, index) {
  19075. dimensionsDefine[index] = val != null ? val + '' : '';
  19076. }, seriesLayoutBy, dataArrayRows, Infinity);
  19077. }
  19078. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  19079. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19080. if (!dimensionsDefine) {
  19081. dimensionsDefine = objectRowsCollectDimensions(data);
  19082. }
  19083. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  19084. if (!dimensionsDefine) {
  19085. dimensionsDefine = [];
  19086. each(data, function (colArr, key) {
  19087. dimensionsDefine.push(key);
  19088. });
  19089. }
  19090. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19091. var value0 = getDataItemValue(data[0]);
  19092. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  19093. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19094. if ("development" !== 'production') {
  19095. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  19096. }
  19097. }
  19098. return {
  19099. startIndex: startIndex,
  19100. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  19101. dimensionsDetectedCount: dimensionsDetectedCount
  19102. };
  19103. }
  19104. function objectRowsCollectDimensions(data) {
  19105. var firstIndex = 0;
  19106. var obj;
  19107. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  19108. if (obj) {
  19109. return keys(obj);
  19110. }
  19111. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  19112. // which is reasonable. But dimension name is duplicated.
  19113. // Returns undefined or an array contains only object without null/undefined or string.
  19114. function normalizeDimensionsOption(dimensionsDefine) {
  19115. if (!dimensionsDefine) {
  19116. // The meaning of null/undefined is different from empty array.
  19117. return;
  19118. }
  19119. var nameMap = createHashMap();
  19120. return map(dimensionsDefine, function (rawItem, index) {
  19121. rawItem = isObject(rawItem) ? rawItem : {
  19122. name: rawItem
  19123. }; // Other fields will be discarded.
  19124. var item = {
  19125. name: rawItem.name,
  19126. displayName: rawItem.displayName,
  19127. type: rawItem.type
  19128. }; // User can set null in dimensions.
  19129. // We don't auto specify name, otherwise a given name may
  19130. // cause it to be referred unexpectedly.
  19131. if (item.name == null) {
  19132. return item;
  19133. } // Also consider number form like 2012.
  19134. item.name += ''; // User may also specify displayName.
  19135. // displayName will always exists except user not
  19136. // specified or dim name is not specified or detected.
  19137. // (A auto generated dim name will not be used as
  19138. // displayName).
  19139. if (item.displayName == null) {
  19140. item.displayName = item.name;
  19141. }
  19142. var exist = nameMap.get(item.name);
  19143. if (!exist) {
  19144. nameMap.set(item.name, {
  19145. count: 1
  19146. });
  19147. } else {
  19148. item.name += '-' + exist.count++;
  19149. }
  19150. return item;
  19151. });
  19152. }
  19153. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  19154. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  19155. for (var i = 0; i < data.length && i < maxLoop; i++) {
  19156. cb(data[i] ? data[i][0] : null, i);
  19157. }
  19158. } else {
  19159. var value0 = data[0] || [];
  19160. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  19161. cb(value0[i], i);
  19162. }
  19163. }
  19164. }
  19165. function shouldRetrieveDataByName(source) {
  19166. var sourceFormat = source.sourceFormat;
  19167. return sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS;
  19168. }
  19169. /*
  19170. * Licensed to the Apache Software Foundation (ASF) under one
  19171. * or more contributor license agreements. See the NOTICE file
  19172. * distributed with this work for additional information
  19173. * regarding copyright ownership. The ASF licenses this file
  19174. * to you under the Apache License, Version 2.0 (the
  19175. * "License"); you may not use this file except in compliance
  19176. * with the License. You may obtain a copy of the License at
  19177. *
  19178. * http://www.apache.org/licenses/LICENSE-2.0
  19179. *
  19180. * Unless required by applicable law or agreed to in writing,
  19181. * software distributed under the License is distributed on an
  19182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19183. * KIND, either express or implied. See the License for the
  19184. * specific language governing permissions and limitations
  19185. * under the License.
  19186. */
  19187. /**
  19188. * AUTO-GENERATED FILE. DO NOT MODIFY.
  19189. */
  19190. /*
  19191. * Licensed to the Apache Software Foundation (ASF) under one
  19192. * or more contributor license agreements. See the NOTICE file
  19193. * distributed with this work for additional information
  19194. * regarding copyright ownership. The ASF licenses this file
  19195. * to you under the Apache License, Version 2.0 (the
  19196. * "License"); you may not use this file except in compliance
  19197. * with the License. You may obtain a copy of the License at
  19198. *
  19199. * http://www.apache.org/licenses/LICENSE-2.0
  19200. *
  19201. * Unless required by applicable law or agreed to in writing,
  19202. * software distributed under the License is distributed on an
  19203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19204. * KIND, either express or implied. See the License for the
  19205. * specific language governing permissions and limitations
  19206. * under the License.
  19207. */
  19208. var _a, _b, _c; // TODO
  19209. var providerMethods;
  19210. var mountMethods;
  19211. /**
  19212. * If normal array used, mutable chunk size is supported.
  19213. * If typed array used, chunk size must be fixed.
  19214. */
  19215. var DefaultDataProvider =
  19216. /** @class */
  19217. function () {
  19218. function DefaultDataProvider(sourceParam, dimSize) {
  19219. // let source: Source;
  19220. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  19221. this._source = source;
  19222. var data = this._data = source.data; // Typed array. TODO IE10+?
  19223. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19224. if ("development" !== 'production') {
  19225. if (dimSize == null) {
  19226. throw new Error('Typed array data must specify dimension size');
  19227. }
  19228. }
  19229. this._offset = 0;
  19230. this._dimSize = dimSize;
  19231. this._data = data;
  19232. }
  19233. mountMethods(this, data, source);
  19234. }
  19235. DefaultDataProvider.prototype.getSource = function () {
  19236. return this._source;
  19237. };
  19238. DefaultDataProvider.prototype.count = function () {
  19239. return 0;
  19240. };
  19241. DefaultDataProvider.prototype.getItem = function (idx, out) {
  19242. return;
  19243. };
  19244. DefaultDataProvider.prototype.appendData = function (newData) {};
  19245. DefaultDataProvider.prototype.clean = function () {};
  19246. DefaultDataProvider.protoInitialize = function () {
  19247. // PENDING: To avoid potential incompat (e.g., prototype
  19248. // is visited somewhere), still init them on prototype.
  19249. var proto = DefaultDataProvider.prototype;
  19250. proto.pure = false;
  19251. proto.persistent = true;
  19252. }();
  19253. DefaultDataProvider.internalField = function () {
  19254. var _a;
  19255. mountMethods = function (provider, data, source) {
  19256. var sourceFormat = source.sourceFormat;
  19257. var seriesLayoutBy = source.seriesLayoutBy;
  19258. var startIndex = source.startIndex;
  19259. var dimsDef = source.dimensionsDefine;
  19260. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19261. if ("development" !== 'production') {
  19262. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19263. }
  19264. extend(provider, methods);
  19265. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19266. provider.getItem = getItemForTypedArray;
  19267. provider.count = countForTypedArray;
  19268. provider.fillStorage = fillStorageForTypedArray;
  19269. } else {
  19270. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  19271. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  19272. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  19273. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  19274. }
  19275. };
  19276. var getItemForTypedArray = function (idx, out) {
  19277. idx = idx - this._offset;
  19278. out = out || [];
  19279. var data = this._data;
  19280. var dimSize = this._dimSize;
  19281. var offset = dimSize * idx;
  19282. for (var i = 0; i < dimSize; i++) {
  19283. out[i] = data[offset + i];
  19284. }
  19285. return out;
  19286. };
  19287. var fillStorageForTypedArray = function (start, end, storage, extent) {
  19288. var data = this._data;
  19289. var dimSize = this._dimSize;
  19290. for (var dim = 0; dim < dimSize; dim++) {
  19291. var dimExtent = extent[dim];
  19292. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  19293. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  19294. var count = end - start;
  19295. var arr = storage[dim];
  19296. for (var i = 0; i < count; i++) {
  19297. // appendData with TypedArray will always do replace in provider.
  19298. var val = data[i * dimSize + dim];
  19299. arr[start + i] = val;
  19300. val < min && (min = val);
  19301. val > max && (max = val);
  19302. }
  19303. dimExtent[0] = min;
  19304. dimExtent[1] = max;
  19305. }
  19306. };
  19307. var countForTypedArray = function () {
  19308. return this._data ? this._data.length / this._dimSize : 0;
  19309. };
  19310. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  19311. pure: true,
  19312. appendData: appendDataSimply
  19313. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  19314. pure: true,
  19315. appendData: function () {
  19316. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19317. }
  19318. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  19319. pure: true,
  19320. appendData: appendDataSimply
  19321. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  19322. pure: true,
  19323. appendData: function (newData) {
  19324. var data = this._data;
  19325. each(newData, function (newCol, key) {
  19326. var oldCol = data[key] || (data[key] = []);
  19327. for (var i = 0; i < (newCol || []).length; i++) {
  19328. oldCol.push(newCol[i]);
  19329. }
  19330. });
  19331. }
  19332. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  19333. appendData: appendDataSimply
  19334. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  19335. persistent: false,
  19336. pure: true,
  19337. appendData: function (newData) {
  19338. if ("development" !== 'production') {
  19339. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  19340. }
  19341. this._data = newData;
  19342. },
  19343. // Clean self if data is already used.
  19344. clean: function () {
  19345. // PENDING
  19346. this._offset += this.count();
  19347. this._data = null;
  19348. }
  19349. }, _a);
  19350. function appendDataSimply(newData) {
  19351. for (var i = 0; i < newData.length; i++) {
  19352. this._data.push(newData[i]);
  19353. }
  19354. }
  19355. }();
  19356. return DefaultDataProvider;
  19357. }();
  19358. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  19359. return rawData[idx];
  19360. };
  19361. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  19362. return rawData[idx + startIndex];
  19363. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx, out) {
  19364. idx += startIndex;
  19365. var item = out || [];
  19366. var data = rawData;
  19367. for (var i = 0; i < data.length; i++) {
  19368. var row = data[i];
  19369. item[i] = row ? row[idx] : null;
  19370. }
  19371. return item;
  19372. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx, out) {
  19373. var item = out || [];
  19374. for (var i = 0; i < dimsDef.length; i++) {
  19375. var dimName = dimsDef[i].name;
  19376. if ("development" !== 'production') {
  19377. if (dimName == null) {
  19378. throw new Error();
  19379. }
  19380. }
  19381. var col = rawData[dimName];
  19382. item[i] = col ? col[idx] : null;
  19383. }
  19384. return item;
  19385. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  19386. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  19387. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19388. if ("development" !== 'production') {
  19389. assert(method, 'Do not support get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19390. }
  19391. return method;
  19392. }
  19393. var countSimply = function (rawData, startIndex, dimsDef) {
  19394. return rawData.length;
  19395. };
  19396. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  19397. return Math.max(0, rawData.length - startIndex);
  19398. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  19399. var row = rawData[0];
  19400. return row ? Math.max(0, row.length - startIndex) : 0;
  19401. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  19402. var dimName = dimsDef[0].name;
  19403. if ("development" !== 'production') {
  19404. if (dimName == null) {
  19405. throw new Error();
  19406. }
  19407. }
  19408. var col = rawData[dimName];
  19409. return col ? col.length : 0;
  19410. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  19411. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  19412. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  19413. if ("development" !== 'production') {
  19414. assert(method, 'Do not support count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  19415. }
  19416. return method;
  19417. }
  19418. var getRawValueSimply = function (dataItem, dimIndex, property) {
  19419. return dataItem[dimIndex];
  19420. };
  19421. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, property) {
  19422. return dataItem[property];
  19423. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, property) {
  19424. // FIXME: In some case (markpoint in geo (geo-map.html)),
  19425. // dataItem is {coord: [...]}
  19426. var value = getDataItemValue(dataItem);
  19427. return !(value instanceof Array) ? value : value[dimIndex];
  19428. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  19429. function getRawSourceValueGetter(sourceFormat) {
  19430. var method = rawSourceValueGetterMap[sourceFormat];
  19431. if ("development" !== 'production') {
  19432. assert(method, 'Do not support get value on "' + sourceFormat + '".');
  19433. }
  19434. return method;
  19435. }
  19436. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  19437. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  19438. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19439. // Consider persistent.
  19440. // Caution: why use raw value to display on label or tooltip?
  19441. // A reason is to avoid format. For example time value we do not know
  19442. // how to format is expected. More over, if stack is used, calculated
  19443. // value may be 0.91000000001, which have brings trouble to display.
  19444. // TODO: consider how to treat null/undefined/NaN when display?
  19445. function retrieveRawValue(data, dataIndex, // If dimIndex is null/undefined, return OptionDataItem.
  19446. // Otherwise, return OptionDataValue.
  19447. dim) {
  19448. if (!data) {
  19449. return;
  19450. } // Consider data may be not persistent.
  19451. var dataItem = data.getRawDataItem(dataIndex);
  19452. if (dataItem == null) {
  19453. return;
  19454. }
  19455. var store = data.getStore();
  19456. var sourceFormat = store.getSource().sourceFormat;
  19457. if (dim != null) {
  19458. var dimIndex = data.getDimensionIndex(dim);
  19459. var property = store.getDimensionProperty(dimIndex);
  19460. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, property);
  19461. } else {
  19462. var result = dataItem;
  19463. if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  19464. result = getDataItemValue(dataItem);
  19465. }
  19466. return result;
  19467. }
  19468. }
  19469. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19470. var DataFormatMixin =
  19471. /** @class */
  19472. function () {
  19473. function DataFormatMixin() {}
  19474. /**
  19475. * Get params for formatter
  19476. */
  19477. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  19478. var data = this.getData(dataType);
  19479. var rawValue = this.getRawValue(dataIndex, dataType);
  19480. var rawDataIndex = data.getRawIndex(dataIndex);
  19481. var name = data.getName(dataIndex);
  19482. var itemOpt = data.getRawDataItem(dataIndex);
  19483. var style = data.getItemVisual(dataIndex, 'style');
  19484. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  19485. var borderColor = style && style.stroke;
  19486. var mainType = this.mainType;
  19487. var isSeries = mainType === 'series';
  19488. var userOutput = data.userOutput && data.userOutput.get();
  19489. return {
  19490. componentType: mainType,
  19491. componentSubType: this.subType,
  19492. componentIndex: this.componentIndex,
  19493. seriesType: isSeries ? this.subType : null,
  19494. seriesIndex: this.seriesIndex,
  19495. seriesId: isSeries ? this.id : null,
  19496. seriesName: isSeries ? this.name : null,
  19497. name: name,
  19498. dataIndex: rawDataIndex,
  19499. data: itemOpt,
  19500. dataType: dataType,
  19501. value: rawValue,
  19502. color: color,
  19503. borderColor: borderColor,
  19504. dimensionNames: userOutput ? userOutput.fullDimensions : null,
  19505. encode: userOutput ? userOutput.encode : null,
  19506. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19507. $vars: ['seriesName', 'name', 'value']
  19508. };
  19509. };
  19510. /**
  19511. * Format label
  19512. * @param dataIndex
  19513. * @param status 'normal' by default
  19514. * @param dataType
  19515. * @param labelDimIndex Only used in some chart that
  19516. * use formatter in different dimensions, like radar.
  19517. * @param formatter Formatter given outside.
  19518. * @return return null/undefined if no formatter
  19519. */
  19520. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  19521. status = status || 'normal';
  19522. var data = this.getData(dataType);
  19523. var params = this.getDataParams(dataIndex, dataType);
  19524. if (extendParams) {
  19525. params.value = extendParams.interpolatedValue;
  19526. }
  19527. if (labelDimIndex != null && isArray(params.value)) {
  19528. params.value = params.value[labelDimIndex];
  19529. }
  19530. if (!formatter) {
  19531. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  19532. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  19533. }
  19534. if (isFunction(formatter)) {
  19535. params.status = status;
  19536. params.dimensionIndex = labelDimIndex;
  19537. return formatter(params);
  19538. } else if (isString(formatter)) {
  19539. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19540. // Do not support '}' in dim name util have to.
  19541. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  19542. var len = dimStr.length;
  19543. var dimLoose = dimStr;
  19544. if (dimLoose.charAt(0) === '[' && dimLoose.charAt(len - 1) === ']') {
  19545. dimLoose = +dimLoose.slice(1, len - 1); // Also support: '[]' => 0
  19546. if ("development" !== 'production') {
  19547. if (isNaN(dimLoose)) {
  19548. error("Invalide label formatter: @" + dimStr + ", only support @[0], @[1], @[2], ...");
  19549. }
  19550. }
  19551. }
  19552. var val = retrieveRawValue(data, dataIndex, dimLoose);
  19553. if (extendParams && isArray(extendParams.interpolatedValue)) {
  19554. var dimIndex = data.getDimensionIndex(dimLoose);
  19555. if (dimIndex >= 0) {
  19556. val = extendParams.interpolatedValue[dimIndex];
  19557. }
  19558. }
  19559. return val != null ? val + '' : '';
  19560. });
  19561. }
  19562. };
  19563. /**
  19564. * Get raw value in option
  19565. */
  19566. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  19567. return retrieveRawValue(this.getData(dataType), idx);
  19568. };
  19569. /**
  19570. * Should be implemented.
  19571. * @param {number} dataIndex
  19572. * @param {boolean} [multipleSeries=false]
  19573. * @param {string} [dataType]
  19574. */
  19575. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  19576. // Empty function
  19577. return;
  19578. };
  19579. return DataFormatMixin;
  19580. }();
  19581. // but guess little chance has been used outside. Do we need to backward
  19582. // compat it?
  19583. // type TooltipFormatResultLegacyObject = {
  19584. // // `html` means the markup language text, either in 'html' or 'richText'.
  19585. // // The name `html` is not appropriate because in 'richText' it is not a HTML
  19586. // // string. But still support it for backward compatibility.
  19587. // html: string;
  19588. // markers: Dictionary<ColorString>;
  19589. // };
  19590. /**
  19591. * For backward compat, normalize the return from `formatTooltip`.
  19592. */
  19593. function normalizeTooltipFormatResult(result) {
  19594. var markupText; // let markers: Dictionary<ColorString>;
  19595. var markupFragment;
  19596. if (isObject(result)) {
  19597. if (result.type) {
  19598. markupFragment = result;
  19599. } else {
  19600. if ("development" !== 'production') {
  19601. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  19602. }
  19603. } // else {
  19604. // markupText = (result as TooltipFormatResultLegacyObject).html;
  19605. // markers = (result as TooltipFormatResultLegacyObject).markers;
  19606. // if (markersExisting) {
  19607. // markers = zrUtil.merge(markersExisting, markers);
  19608. // }
  19609. // }
  19610. } else {
  19611. markupText = result;
  19612. }
  19613. return {
  19614. text: markupText,
  19615. // markers: markers || markersExisting,
  19616. frag: markupFragment
  19617. };
  19618. }
  19619. /**
  19620. * @param {Object} define
  19621. * @return See the return of `createTask`.
  19622. */
  19623. function createTask(define) {
  19624. return new Task(define);
  19625. }
  19626. var Task =
  19627. /** @class */
  19628. function () {
  19629. function Task(define) {
  19630. define = define || {};
  19631. this._reset = define.reset;
  19632. this._plan = define.plan;
  19633. this._count = define.count;
  19634. this._onDirty = define.onDirty;
  19635. this._dirty = true;
  19636. }
  19637. /**
  19638. * @param step Specified step.
  19639. * @param skip Skip customer perform call.
  19640. * @param modBy Sampling window size.
  19641. * @param modDataCount Sampling count.
  19642. * @return whether unfinished.
  19643. */
  19644. Task.prototype.perform = function (performArgs) {
  19645. var upTask = this._upstream;
  19646. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19647. // Pull data. Must pull data each time, because context.data
  19648. // may be updated by Series.setData.
  19649. if (this._dirty && upTask) {
  19650. var context = this.context;
  19651. context.data = context.outputData = upTask.context.outputData;
  19652. }
  19653. if (this.__pipeline) {
  19654. this.__pipeline.currentTask = this;
  19655. }
  19656. var planResult;
  19657. if (this._plan && !skip) {
  19658. planResult = this._plan(this.context);
  19659. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19660. // elements uniformed distributed when progress, especially when moving or zooming.
  19661. var lastModBy = normalizeModBy(this._modBy);
  19662. var lastModDataCount = this._modDataCount || 0;
  19663. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19664. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19665. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19666. planResult = 'reset';
  19667. }
  19668. function normalizeModBy(val) {
  19669. !(val >= 1) && (val = 1); // jshint ignore:line
  19670. return val;
  19671. }
  19672. var forceFirstProgress;
  19673. if (this._dirty || planResult === 'reset') {
  19674. this._dirty = false;
  19675. forceFirstProgress = this._doReset(skip);
  19676. }
  19677. this._modBy = modBy;
  19678. this._modDataCount = modDataCount;
  19679. var step = performArgs && performArgs.step;
  19680. if (upTask) {
  19681. if ("development" !== 'production') {
  19682. assert(upTask._outputDueEnd != null);
  19683. }
  19684. this._dueEnd = upTask._outputDueEnd;
  19685. } // DataTask or overallTask
  19686. else {
  19687. if ("development" !== 'production') {
  19688. assert(!this._progress || this._count);
  19689. }
  19690. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19691. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19692. // If no progress, pass index from upstream to downstream each time plan called.
  19693. if (this._progress) {
  19694. var start = this._dueIndex;
  19695. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19696. if (!skip && (forceFirstProgress || start < end)) {
  19697. var progress = this._progress;
  19698. if (isArray(progress)) {
  19699. for (var i = 0; i < progress.length; i++) {
  19700. this._doProgress(progress[i], start, end, modBy, modDataCount);
  19701. }
  19702. } else {
  19703. this._doProgress(progress, start, end, modBy, modDataCount);
  19704. }
  19705. }
  19706. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19707. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19708. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19709. if ("development" !== 'production') {
  19710. // ??? Can not rollback.
  19711. assert(outputDueEnd >= this._outputDueEnd);
  19712. }
  19713. this._outputDueEnd = outputDueEnd;
  19714. } else {
  19715. // (1) Some overall task has no progress.
  19716. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19717. // This should always be performed so it can be passed to downstream.
  19718. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19719. }
  19720. return this.unfinished();
  19721. };
  19722. Task.prototype.dirty = function () {
  19723. this._dirty = true;
  19724. this._onDirty && this._onDirty(this.context);
  19725. };
  19726. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19727. iterator.reset(start, end, modBy, modDataCount);
  19728. this._callingProgress = progress;
  19729. this._callingProgress({
  19730. start: start,
  19731. end: end,
  19732. count: end - start,
  19733. next: iterator.next
  19734. }, this.context);
  19735. };
  19736. Task.prototype._doReset = function (skip) {
  19737. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19738. this._settedOutputEnd = null;
  19739. var progress;
  19740. var forceFirstProgress;
  19741. if (!skip && this._reset) {
  19742. progress = this._reset(this.context);
  19743. if (progress && progress.progress) {
  19744. forceFirstProgress = progress.forceFirstProgress;
  19745. progress = progress.progress;
  19746. } // To simplify no progress checking, array must has item.
  19747. if (isArray(progress) && !progress.length) {
  19748. progress = null;
  19749. }
  19750. }
  19751. this._progress = progress;
  19752. this._modBy = this._modDataCount = null;
  19753. var downstream = this._downstream;
  19754. downstream && downstream.dirty();
  19755. return forceFirstProgress;
  19756. };
  19757. Task.prototype.unfinished = function () {
  19758. return this._progress && this._dueIndex < this._dueEnd;
  19759. };
  19760. /**
  19761. * @param downTask The downstream task.
  19762. * @return The downstream task.
  19763. */
  19764. Task.prototype.pipe = function (downTask) {
  19765. if ("development" !== 'production') {
  19766. assert(downTask && !downTask._disposed && downTask !== this);
  19767. } // If already downstream, do not dirty downTask.
  19768. if (this._downstream !== downTask || this._dirty) {
  19769. this._downstream = downTask;
  19770. downTask._upstream = this;
  19771. downTask.dirty();
  19772. }
  19773. };
  19774. Task.prototype.dispose = function () {
  19775. if (this._disposed) {
  19776. return;
  19777. }
  19778. this._upstream && (this._upstream._downstream = null);
  19779. this._downstream && (this._downstream._upstream = null);
  19780. this._dirty = false;
  19781. this._disposed = true;
  19782. };
  19783. Task.prototype.getUpstream = function () {
  19784. return this._upstream;
  19785. };
  19786. Task.prototype.getDownstream = function () {
  19787. return this._downstream;
  19788. };
  19789. Task.prototype.setOutputEnd = function (end) {
  19790. // This only happens in dataTask, dataZoom, map, currently.
  19791. // where dataZoom do not set end each time, but only set
  19792. // when reset. So we should record the set end, in case
  19793. // that the stub of dataZoom perform again and earse the
  19794. // set end by upstream.
  19795. this._outputDueEnd = this._settedOutputEnd = end;
  19796. };
  19797. return Task;
  19798. }();
  19799. var iterator = function () {
  19800. var end;
  19801. var current;
  19802. var modBy;
  19803. var modDataCount;
  19804. var winCount;
  19805. var it = {
  19806. reset: function (s, e, sStep, sCount) {
  19807. current = s;
  19808. end = e;
  19809. modBy = sStep;
  19810. modDataCount = sCount;
  19811. winCount = Math.ceil(modDataCount / modBy);
  19812. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19813. }
  19814. };
  19815. return it;
  19816. function sequentialNext() {
  19817. return current < end ? current++ : null;
  19818. }
  19819. function modNext() {
  19820. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19821. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19822. // Use normal linear rendering mode.
  19823. : current;
  19824. current++;
  19825. return result;
  19826. }
  19827. }(); // -----------------------------------------------------------------------------
  19828. // For stream debug (Should be commented out after used!)
  19829. // @usage: printTask(this, 'begin');
  19830. // @usage: printTask(this, null, {someExtraProp});
  19831. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19832. //
  19833. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19834. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19835. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19836. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19837. // let props = [];
  19838. // if (task.__pipeline) {
  19839. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19840. // props.push({text: '__idxInPipeline/total', value: val});
  19841. // } else {
  19842. // let stubCount = 0;
  19843. // task.agentStubMap.each(() => stubCount++);
  19844. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19845. // }
  19846. // props.push({text: 'uid', value: task.uidDebug});
  19847. // if (task.__pipeline) {
  19848. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19849. // task.agent && props.push(
  19850. // {text: 'stubFor', value: task.agent.uidDebug}
  19851. // );
  19852. // }
  19853. // props.push(
  19854. // {text: 'dirty', value: task._dirty},
  19855. // {text: 'dueIndex', value: task._dueIndex},
  19856. // {text: 'dueEnd', value: task._dueEnd},
  19857. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19858. // );
  19859. // if (extra) {
  19860. // Object.keys(extra).forEach(key => {
  19861. // props.push({text: key, value: extra[key]});
  19862. // });
  19863. // }
  19864. // let args = ['color: blue'];
  19865. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19866. // args.push('color: green', 'color: red'),
  19867. // `${item.text}: %c${item.value}`
  19868. // )).join('%c, ');
  19869. // console.log.apply(console, [msg].concat(args));
  19870. // // console.log(this);
  19871. // };
  19872. // window.printPipeline = function (task: any, prefix: string) {
  19873. // const pipeline = task.__pipeline;
  19874. // let currTask = pipeline.head;
  19875. // while (currTask) {
  19876. // window.printTask(currTask, prefix);
  19877. // currTask = currTask._downstream;
  19878. // }
  19879. // };
  19880. // window.showChain = function (chainHeadTask) {
  19881. // var chain = [];
  19882. // var task = chainHeadTask;
  19883. // while (task) {
  19884. // chain.push({
  19885. // task: task,
  19886. // up: task._upstream,
  19887. // down: task._downstream,
  19888. // idxInPipeline: task.__idxInPipeline
  19889. // });
  19890. // task = task._downstream;
  19891. // }
  19892. // return chain;
  19893. // };
  19894. // window.findTaskInChain = function (task, chainHeadTask) {
  19895. // let chain = window.showChain(chainHeadTask);
  19896. // let result = [];
  19897. // for (let i = 0; i < chain.length; i++) {
  19898. // let chainItem = chain[i];
  19899. // if (chainItem.task === task) {
  19900. // result.push(i);
  19901. // }
  19902. // }
  19903. // return result;
  19904. // };
  19905. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19906. // let chainA = window.showChain(chainHeadTaskA);
  19907. // for (let i = 0; i < chainA.length; i++) {
  19908. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19909. // }
  19910. // };
  19911. /**
  19912. * Convert raw the value in to inner value in List.
  19913. *
  19914. * [Performance sensitive]
  19915. *
  19916. * [Caution]: this is the key logic of user value parser.
  19917. * For backward compatibility, do not modify it until you have to!
  19918. */
  19919. function parseDataValue(value, // For high performance, do not omit the second param.
  19920. opt) {
  19921. // Performance sensitive.
  19922. var dimType = opt && opt.type;
  19923. if (dimType === 'ordinal') {
  19924. // If given value is a category string
  19925. return value;
  19926. }
  19927. if (dimType === 'time' // spead up when using timestamp
  19928. && !isNumber(value) && value != null && value !== '-') {
  19929. value = +parseDate(value);
  19930. } // dimType defaults 'number'.
  19931. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19932. // parse to NaN.
  19933. // number-like string (like ' 123 ') can be converted to a number.
  19934. // where null/undefined or other string will be converted to NaN.
  19935. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19936. // If object, also parse to NaN
  19937. : +value;
  19938. }
  19939. var valueParserMap = createHashMap({
  19940. 'number': function (val) {
  19941. // Do not use `numericToNumber` here. We have `numericToNumber` by default.
  19942. // Here the number parser can have loose rule:
  19943. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19944. return parseFloat(val);
  19945. },
  19946. 'time': function (val) {
  19947. // return timestamp.
  19948. return +parseDate(val);
  19949. },
  19950. 'trim': function (val) {
  19951. return isString(val) ? trim(val) : val;
  19952. }
  19953. });
  19954. function getRawValueParser(type) {
  19955. return valueParserMap.get(type);
  19956. }
  19957. var ORDER_COMPARISON_OP_MAP = {
  19958. lt: function (lval, rval) {
  19959. return lval < rval;
  19960. },
  19961. lte: function (lval, rval) {
  19962. return lval <= rval;
  19963. },
  19964. gt: function (lval, rval) {
  19965. return lval > rval;
  19966. },
  19967. gte: function (lval, rval) {
  19968. return lval >= rval;
  19969. }
  19970. };
  19971. var FilterOrderComparator =
  19972. /** @class */
  19973. function () {
  19974. function FilterOrderComparator(op, rval) {
  19975. if (!isNumber(rval)) {
  19976. var errMsg = '';
  19977. if ("development" !== 'production') {
  19978. errMsg = 'rvalue of "<", ">", "<=", ">=" can only be number in filter.';
  19979. }
  19980. throwError(errMsg);
  19981. }
  19982. this._opFn = ORDER_COMPARISON_OP_MAP[op];
  19983. this._rvalFloat = numericToNumber(rval);
  19984. } // Performance sensitive.
  19985. FilterOrderComparator.prototype.evaluate = function (lval) {
  19986. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19987. return isNumber(lval) ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat);
  19988. };
  19989. return FilterOrderComparator;
  19990. }();
  19991. var SortOrderComparator =
  19992. /** @class */
  19993. function () {
  19994. /**
  19995. * @param order by default: 'asc'
  19996. * @param incomparable by default: Always on the tail.
  19997. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19998. * See the definition of "incomparable" in [SORT_COMPARISON_RULE].
  19999. */
  20000. function SortOrderComparator(order, incomparable) {
  20001. var isDesc = order === 'desc';
  20002. this._resultLT = isDesc ? 1 : -1;
  20003. if (incomparable == null) {
  20004. incomparable = isDesc ? 'min' : 'max';
  20005. }
  20006. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  20007. } // See [SORT_COMPARISON_RULE].
  20008. // Performance sensitive.
  20009. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  20010. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  20011. var lvalFloat = isNumber(lval) ? lval : numericToNumber(lval);
  20012. var rvalFloat = isNumber(rval) ? rval : numericToNumber(rval);
  20013. var lvalNotNumeric = isNaN(lvalFloat);
  20014. var rvalNotNumeric = isNaN(rvalFloat);
  20015. if (lvalNotNumeric) {
  20016. lvalFloat = this._incomparable;
  20017. }
  20018. if (rvalNotNumeric) {
  20019. rvalFloat = this._incomparable;
  20020. }
  20021. if (lvalNotNumeric && rvalNotNumeric) {
  20022. var lvalIsStr = isString(lval);
  20023. var rvalIsStr = isString(rval);
  20024. if (lvalIsStr) {
  20025. lvalFloat = rvalIsStr ? lval : 0;
  20026. }
  20027. if (rvalIsStr) {
  20028. rvalFloat = lvalIsStr ? rval : 0;
  20029. }
  20030. }
  20031. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  20032. };
  20033. return SortOrderComparator;
  20034. }();
  20035. var FilterEqualityComparator =
  20036. /** @class */
  20037. function () {
  20038. function FilterEqualityComparator(isEq, rval) {
  20039. this._rval = rval;
  20040. this._isEQ = isEq;
  20041. this._rvalTypeof = typeof rval;
  20042. this._rvalFloat = numericToNumber(rval);
  20043. } // Performance sensitive.
  20044. FilterEqualityComparator.prototype.evaluate = function (lval) {
  20045. var eqResult = lval === this._rval;
  20046. if (!eqResult) {
  20047. var lvalTypeof = typeof lval;
  20048. if (lvalTypeof !== this._rvalTypeof && (lvalTypeof === 'number' || this._rvalTypeof === 'number')) {
  20049. eqResult = numericToNumber(lval) === this._rvalFloat;
  20050. }
  20051. }
  20052. return this._isEQ ? eqResult : !eqResult;
  20053. };
  20054. return FilterEqualityComparator;
  20055. }();
  20056. /**
  20057. * [FILTER_COMPARISON_RULE]
  20058. * `lt`|`lte`|`gt`|`gte`:
  20059. * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare.
  20060. * `eq`:
  20061. * + If same type, compare with `===`.
  20062. * + If there is one number, convert to number (`numericToNumber`) to compare.
  20063. * + Else return `false`.
  20064. * `ne`:
  20065. * + Not `eq`.
  20066. *
  20067. *
  20068. * [SORT_COMPARISON_RULE]
  20069. * All the values are grouped into three categories:
  20070. * + "numeric" (number and numeric string)
  20071. * + "non-numeric-string" (string that excluding numeric string)
  20072. * + "others"
  20073. * "numeric" vs "numeric": values are ordered by number order.
  20074. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison).
  20075. * "others" vs "others": do not change order (always return 0).
  20076. * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable".
  20077. * "number" vs "others": "others" is treated as "incomparable".
  20078. * "non-numeric-string" vs "others": "others" is treated as "incomparable".
  20079. * "incomparable" will be seen as -Infinity or Infinity (depends on the settings).
  20080. * MEMO:
  20081. * Non-numeric string sort makes sense when we need to put the items with the same tag together.
  20082. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`,
  20083. * So we treat "numeric-string" sorted by number order rather than string comparison.
  20084. *
  20085. *
  20086. * [CHECK_LIST_OF_THE_RULE_DESIGN]
  20087. * + Do not support string comparison until required. And also need to
  20088. * avoid the misleading of "2" > "12".
  20089. * + Should avoid the misleading case:
  20090. * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`.
  20091. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ...
  20092. * + Only "numeric" can be converted to comparable number, otherwise converted to NaN.
  20093. * See `util/number.ts#numericToNumber`.
  20094. *
  20095. * @return If `op` is not `RelationalOperator`, return null;
  20096. */
  20097. function createFilterComparator(op, rval) {
  20098. return op === 'eq' || op === 'ne' ? new FilterEqualityComparator(op === 'eq', rval) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, rval) : null;
  20099. }
  20100. /**
  20101. * TODO: disable writable.
  20102. * This structure will be exposed to users.
  20103. */
  20104. var ExternalSource =
  20105. /** @class */
  20106. function () {
  20107. function ExternalSource() {}
  20108. ExternalSource.prototype.getRawData = function () {
  20109. // Only built-in transform available.
  20110. throw new Error('not supported');
  20111. };
  20112. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  20113. // Only built-in transform available.
  20114. throw new Error('not supported');
  20115. };
  20116. ExternalSource.prototype.cloneRawData = function () {
  20117. return;
  20118. };
  20119. /**
  20120. * @return If dimension not found, return null/undefined.
  20121. */
  20122. ExternalSource.prototype.getDimensionInfo = function (dim) {
  20123. return;
  20124. };
  20125. /**
  20126. * dimensions defined if and only if either:
  20127. * (a) dataset.dimensions are declared.
  20128. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  20129. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  20130. * the defined dimensions.
  20131. * Otherwise, `dimensionInfoAll` is determined by data columns.
  20132. * @return Always return an array (even empty array).
  20133. */
  20134. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  20135. return;
  20136. };
  20137. ExternalSource.prototype.count = function () {
  20138. return;
  20139. };
  20140. /**
  20141. * Only support by dimension index.
  20142. * No need to support by dimension name in transform function,
  20143. * because transform function is not case-specific, no need to use name literally.
  20144. */
  20145. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  20146. return;
  20147. };
  20148. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  20149. return;
  20150. };
  20151. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  20152. return parseDataValue(rawVal, dimInfo);
  20153. };
  20154. return ExternalSource;
  20155. }();
  20156. function createExternalSource(internalSource, externalTransform) {
  20157. var extSource = new ExternalSource();
  20158. var data = internalSource.data;
  20159. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  20160. var sourceHeaderCount = internalSource.startIndex;
  20161. var errMsg = '';
  20162. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  20163. // For the logic simplicity in transformer, only 'culumn' is
  20164. // supported in data transform. Otherwise, the `dimensionsDefine`
  20165. // might be detected by 'row', which probably confuses users.
  20166. if ("development" !== 'production') {
  20167. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  20168. }
  20169. throwError(errMsg);
  20170. } // [MEMO]
  20171. // Create a new dimensions structure for exposing.
  20172. // Do not expose all dimension info to users directly.
  20173. // Because the dimension is probably auto detected from data and not might reliable.
  20174. // Should not lead the transformers to think that is reliable and return it.
  20175. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20176. var dimensions = [];
  20177. var dimsByName = {};
  20178. var dimsDef = internalSource.dimensionsDefine;
  20179. if (dimsDef) {
  20180. each(dimsDef, function (dimDef, idx) {
  20181. var name = dimDef.name;
  20182. var dimDefExt = {
  20183. index: idx,
  20184. name: name,
  20185. displayName: dimDef.displayName
  20186. };
  20187. dimensions.push(dimDefExt); // Users probably do not specify dimension name. For simplicity, data transform
  20188. // does not generate dimension name.
  20189. if (name != null) {
  20190. // Dimension name should not be duplicated.
  20191. // For simplicity, data transform forbids name duplication, do not generate
  20192. // new name like module `completeDimensions.ts` did, but just tell users.
  20193. var errMsg_1 = '';
  20194. if (hasOwn(dimsByName, name)) {
  20195. if ("development" !== 'production') {
  20196. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  20197. }
  20198. throwError(errMsg_1);
  20199. }
  20200. dimsByName[name] = dimDefExt;
  20201. }
  20202. });
  20203. } // If dimension definitions are not defined and can not be detected.
  20204. // e.g., pure data `[[11, 22], ...]`.
  20205. else {
  20206. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  20207. // Do not generete name or anything others. The consequence process in
  20208. // `transform` or `series` probably have there own name generation strategry.
  20209. dimensions.push({
  20210. index: i
  20211. });
  20212. }
  20213. } // Implement public methods:
  20214. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20215. if (externalTransform.__isBuiltIn) {
  20216. extSource.getRawDataItem = function (dataIndex) {
  20217. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20218. };
  20219. extSource.getRawData = bind(getRawData, null, internalSource);
  20220. }
  20221. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  20222. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  20223. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  20224. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  20225. extSource.retrieveValue = function (dataIndex, dimIndex) {
  20226. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  20227. return retrieveValueFromItem(rawItem, dimIndex);
  20228. };
  20229. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  20230. if (dataItem == null) {
  20231. return;
  20232. }
  20233. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  20234. if (dimDef) {
  20235. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  20236. }
  20237. };
  20238. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  20239. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  20240. return extSource;
  20241. }
  20242. function getRawData(upstream) {
  20243. var sourceFormat = upstream.sourceFormat;
  20244. if (!isSupportedSourceFormat(sourceFormat)) {
  20245. var errMsg = '';
  20246. if ("development" !== 'production') {
  20247. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  20248. }
  20249. throwError(errMsg);
  20250. }
  20251. return upstream.data;
  20252. }
  20253. function cloneRawData(upstream) {
  20254. var sourceFormat = upstream.sourceFormat;
  20255. var data = upstream.data;
  20256. if (!isSupportedSourceFormat(sourceFormat)) {
  20257. var errMsg = '';
  20258. if ("development" !== 'production') {
  20259. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  20260. }
  20261. throwError(errMsg);
  20262. }
  20263. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  20264. var result = [];
  20265. for (var i = 0, len = data.length; i < len; i++) {
  20266. // Not strictly clone for performance
  20267. result.push(data[i].slice());
  20268. }
  20269. return result;
  20270. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  20271. var result = [];
  20272. for (var i = 0, len = data.length; i < len; i++) {
  20273. // Not strictly clone for performance
  20274. result.push(extend({}, data[i]));
  20275. }
  20276. return result;
  20277. }
  20278. }
  20279. function getDimensionInfo(dimensions, dimsByName, dim) {
  20280. if (dim == null) {
  20281. return;
  20282. } // Keep the same logic as `List::getDimension` did.
  20283. if (isNumber(dim) // If being a number-like string but not being defined a dimension name.
  20284. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  20285. return dimensions[dim];
  20286. } else if (hasOwn(dimsByName, dim)) {
  20287. return dimsByName[dim];
  20288. }
  20289. }
  20290. function cloneAllDimensionInfo(dimensions) {
  20291. return clone(dimensions);
  20292. }
  20293. var externalTransformMap = createHashMap();
  20294. function registerExternalTransform(externalTransform) {
  20295. externalTransform = clone(externalTransform);
  20296. var type = externalTransform.type;
  20297. var errMsg = '';
  20298. if (!type) {
  20299. if ("development" !== 'production') {
  20300. errMsg = 'Must have a `type` when `registerTransform`.';
  20301. }
  20302. throwError(errMsg);
  20303. }
  20304. var typeParsed = type.split(':');
  20305. if (typeParsed.length !== 2) {
  20306. if ("development" !== 'production') {
  20307. errMsg = 'Name must include namespace like "ns:regression".';
  20308. }
  20309. throwError(errMsg);
  20310. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  20311. // be called directly via 'xxx' rather than 'echarts:xxx'.
  20312. var isBuiltIn = false;
  20313. if (typeParsed[0] === 'echarts') {
  20314. type = typeParsed[1];
  20315. isBuiltIn = true;
  20316. }
  20317. externalTransform.__isBuiltIn = isBuiltIn;
  20318. externalTransformMap.set(type, externalTransform);
  20319. }
  20320. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  20321. var pipedTransOption = normalizeToArray(rawTransOption);
  20322. var pipeLen = pipedTransOption.length;
  20323. var errMsg = '';
  20324. if (!pipeLen) {
  20325. if ("development" !== 'production') {
  20326. errMsg = 'If `transform` declared, it should at least contain one transform.';
  20327. }
  20328. throwError(errMsg);
  20329. }
  20330. for (var i = 0, len = pipeLen; i < len; i++) {
  20331. var transOption = pipedTransOption[i];
  20332. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  20333. // piped transform only support single output, except the last one.
  20334. if (i !== len - 1) {
  20335. sourceList.length = Math.max(sourceList.length, 1);
  20336. }
  20337. }
  20338. return sourceList;
  20339. }
  20340. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  20341. pipeIndex) {
  20342. var errMsg = '';
  20343. if (!upSourceList.length) {
  20344. if ("development" !== 'production') {
  20345. errMsg = 'Must have at least one upstream dataset.';
  20346. }
  20347. throwError(errMsg);
  20348. }
  20349. if (!isObject(transOption)) {
  20350. if ("development" !== 'production') {
  20351. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  20352. }
  20353. throwError(errMsg);
  20354. }
  20355. var transType = transOption.type;
  20356. var externalTransform = externalTransformMap.get(transType);
  20357. if (!externalTransform) {
  20358. if ("development" !== 'production') {
  20359. errMsg = 'Can not find transform on type "' + transType + '".';
  20360. }
  20361. throwError(errMsg);
  20362. } // Prepare source
  20363. var extUpSourceList = map(upSourceList, function (upSource) {
  20364. return createExternalSource(upSource, externalTransform);
  20365. });
  20366. var resultList = normalizeToArray(externalTransform.transform({
  20367. upstream: extUpSourceList[0],
  20368. upstreamList: extUpSourceList,
  20369. config: clone(transOption.config)
  20370. }));
  20371. if ("development" !== 'production') {
  20372. if (transOption.print) {
  20373. var printStrArr = map(resultList, function (extSource) {
  20374. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  20375. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  20376. }).join('\n');
  20377. log(printStrArr);
  20378. }
  20379. }
  20380. return map(resultList, function (result, resultIndex) {
  20381. var errMsg = '';
  20382. if (!isObject(result)) {
  20383. if ("development" !== 'production') {
  20384. errMsg = 'A transform should not return some empty results.';
  20385. }
  20386. throwError(errMsg);
  20387. }
  20388. if (!result.data) {
  20389. if ("development" !== 'production') {
  20390. errMsg = 'Transform result data should be not be null or undefined';
  20391. }
  20392. throwError(errMsg);
  20393. }
  20394. var sourceFormat = detectSourceFormat(result.data);
  20395. if (!isSupportedSourceFormat(sourceFormat)) {
  20396. if ("development" !== 'production') {
  20397. errMsg = 'Transform result data should be array rows or object rows.';
  20398. }
  20399. throwError(errMsg);
  20400. }
  20401. var resultMetaRawOption;
  20402. var firstUpSource = upSourceList[0];
  20403. /**
  20404. * Intuitively, the end users known the content of the original `dataset.source`,
  20405. * calucating the transform result in mind.
  20406. * Suppose the original `dataset.source` is:
  20407. * ```js
  20408. * [
  20409. * ['product', '2012', '2013', '2014', '2015'],
  20410. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  20411. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  20412. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  20413. * ]
  20414. * ```
  20415. * The dimension info have to be detected from the source data.
  20416. * Some of the transformers (like filter, sort) will follow the dimension info
  20417. * of upstream, while others use new dimensions (like aggregate).
  20418. * Transformer can output a field `dimensions` to define the its own output dimensions.
  20419. * We also allow transformers to ignore the output `dimensions` field, and
  20420. * inherit the upstream dimensions definition. It can reduce the burden of handling
  20421. * dimensions in transformers.
  20422. *
  20423. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  20424. */
  20425. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  20426. // dimensions definitions. We do not inherit anything from upstream.
  20427. && !result.dimensions) {
  20428. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result, because:
  20429. // (1) The returned data always does not contain header line and can not be used
  20430. // as dimension-detection. In this case we can not use "detected dimensions" of
  20431. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  20432. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  20433. // So the original detected header should be add to the result, otherwise they can not be read.
  20434. if (startIndex) {
  20435. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  20436. }
  20437. resultMetaRawOption = {
  20438. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20439. sourceHeader: startIndex,
  20440. dimensions: firstUpSource.metaRawOption.dimensions
  20441. };
  20442. } else {
  20443. resultMetaRawOption = {
  20444. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  20445. sourceHeader: 0,
  20446. dimensions: result.dimensions
  20447. };
  20448. }
  20449. return createSource(result.data, resultMetaRawOption, null);
  20450. });
  20451. }
  20452. function isSupportedSourceFormat(sourceFormat) {
  20453. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  20454. }
  20455. var UNDEFINED = 'undefined';
  20456. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  20457. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  20458. // different from the Ctor of typed array.
  20459. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  20460. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  20461. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  20462. var CtorFloat64Array = typeof Float64Array === UNDEFINED ? Array : Float64Array;
  20463. /**
  20464. * Multi dimensional data store
  20465. */
  20466. var dataCtors = {
  20467. 'float': CtorFloat64Array,
  20468. 'int': CtorInt32Array,
  20469. // Ordinal data type can be string or int
  20470. 'ordinal': Array,
  20471. 'number': Array,
  20472. 'time': CtorFloat64Array
  20473. };
  20474. var defaultDimValueGetters;
  20475. function getIndicesCtor(rawCount) {
  20476. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  20477. return rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  20478. }
  20479. function getInitialExtent() {
  20480. return [Infinity, -Infinity];
  20481. }
  20482. function cloneChunk(originalChunk) {
  20483. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  20484. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  20485. }
  20486. function prepareStore(store, dimIdx, dimType, end, append) {
  20487. var DataCtor = dataCtors[dimType || 'float'];
  20488. if (append) {
  20489. var oldStore = store[dimIdx];
  20490. var oldLen = oldStore && oldStore.length;
  20491. if (!(oldLen === end)) {
  20492. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  20493. // within the initial chunkSize.
  20494. for (var j = 0; j < oldLen; j++) {
  20495. newStore[j] = oldStore[j];
  20496. }
  20497. store[dimIdx] = newStore;
  20498. }
  20499. } else {
  20500. store[dimIdx] = new DataCtor(end);
  20501. }
  20502. }
  20503. /**
  20504. * Basically, DataStore API keep immutable.
  20505. */
  20506. var DataStore =
  20507. /** @class */
  20508. function () {
  20509. function DataStore() {
  20510. this._chunks = []; // It will not be calculated until needed.
  20511. this._rawExtent = [];
  20512. this._extent = [];
  20513. this._count = 0;
  20514. this._rawCount = 0;
  20515. this._calcDimNameToIdx = createHashMap();
  20516. }
  20517. /**
  20518. * Initialize from data
  20519. */
  20520. DataStore.prototype.initData = function (provider, inputDimensions, dimValueGetter) {
  20521. if ("development" !== 'production') {
  20522. assert(isFunction(provider.getItem) && isFunction(provider.count), 'Invalid data provider.');
  20523. }
  20524. this._provider = provider; // Clear
  20525. this._chunks = [];
  20526. this._indices = null;
  20527. this.getRawIndex = this._getRawIdxIdentity;
  20528. var source = provider.getSource();
  20529. var defaultGetter = this.defaultDimValueGetter = defaultDimValueGetters[source.sourceFormat]; // Default dim value getter
  20530. this._dimValueGetter = dimValueGetter || defaultGetter; // Reset raw extent.
  20531. this._rawExtent = [];
  20532. var willRetrieveDataByName = shouldRetrieveDataByName(source);
  20533. this._dimensions = map(inputDimensions, function (dim) {
  20534. if ("development" !== 'production') {
  20535. if (willRetrieveDataByName) {
  20536. assert(dim.property != null);
  20537. }
  20538. }
  20539. return {
  20540. // Only pick these two props. Not leak other properties like orderMeta.
  20541. type: dim.type,
  20542. property: dim.property
  20543. };
  20544. });
  20545. this._initDataFromProvider(0, provider.count());
  20546. };
  20547. DataStore.prototype.getProvider = function () {
  20548. return this._provider;
  20549. };
  20550. /**
  20551. * Caution: even when a `source` instance owned by a series, the created data store
  20552. * may still be shared by different sereis (the source hash does not use all `source`
  20553. * props, see `sourceManager`). In this case, the `source` props that are not used in
  20554. * hash (like `source.dimensionDefine`) probably only belongs to a certain series and
  20555. * thus should not be fetch here.
  20556. */
  20557. DataStore.prototype.getSource = function () {
  20558. return this._provider.getSource();
  20559. };
  20560. /**
  20561. * @caution Only used in dataStack.
  20562. */
  20563. DataStore.prototype.ensureCalculationDimension = function (dimName, type) {
  20564. var calcDimNameToIdx = this._calcDimNameToIdx;
  20565. var dimensions = this._dimensions;
  20566. var calcDimIdx = calcDimNameToIdx.get(dimName);
  20567. if (calcDimIdx != null) {
  20568. if (dimensions[calcDimIdx].type === type) {
  20569. return calcDimIdx;
  20570. }
  20571. } else {
  20572. calcDimIdx = dimensions.length;
  20573. }
  20574. dimensions[calcDimIdx] = {
  20575. type: type
  20576. };
  20577. calcDimNameToIdx.set(dimName, calcDimIdx);
  20578. this._chunks[calcDimIdx] = new dataCtors[type || 'float'](this._rawCount);
  20579. this._rawExtent[calcDimIdx] = getInitialExtent();
  20580. return calcDimIdx;
  20581. };
  20582. DataStore.prototype.collectOrdinalMeta = function (dimIdx, ordinalMeta) {
  20583. var chunk = this._chunks[dimIdx];
  20584. var dim = this._dimensions[dimIdx];
  20585. var rawExtents = this._rawExtent;
  20586. var offset = dim.ordinalOffset || 0;
  20587. var len = chunk.length;
  20588. if (offset === 0) {
  20589. // We need to reset the rawExtent if collect is from start.
  20590. // Because this dimension may be guessed as number and calcuating a wrong extent.
  20591. rawExtents[dimIdx] = getInitialExtent();
  20592. }
  20593. var dimRawExtent = rawExtents[dimIdx]; // Parse from previous data offset. len may be changed after appendData
  20594. for (var i = offset; i < len; i++) {
  20595. var val = chunk[i] = ordinalMeta.parseAndCollect(chunk[i]);
  20596. if (!isNaN(val)) {
  20597. dimRawExtent[0] = Math.min(val, dimRawExtent[0]);
  20598. dimRawExtent[1] = Math.max(val, dimRawExtent[1]);
  20599. }
  20600. }
  20601. dim.ordinalMeta = ordinalMeta;
  20602. dim.ordinalOffset = len;
  20603. dim.type = 'ordinal'; // Force to be ordinal
  20604. };
  20605. DataStore.prototype.getOrdinalMeta = function (dimIdx) {
  20606. var dimInfo = this._dimensions[dimIdx];
  20607. var ordinalMeta = dimInfo.ordinalMeta;
  20608. return ordinalMeta;
  20609. };
  20610. DataStore.prototype.getDimensionProperty = function (dimIndex) {
  20611. var item = this._dimensions[dimIndex];
  20612. return item && item.property;
  20613. };
  20614. /**
  20615. * Caution: Can be only called on raw data (before `this._indices` created).
  20616. */
  20617. DataStore.prototype.appendData = function (data) {
  20618. if ("development" !== 'production') {
  20619. assert(!this._indices, 'appendData can only be called on raw data.');
  20620. }
  20621. var provider = this._provider;
  20622. var start = this.count();
  20623. provider.appendData(data);
  20624. var end = provider.count();
  20625. if (!provider.persistent) {
  20626. end += start;
  20627. }
  20628. if (start < end) {
  20629. this._initDataFromProvider(start, end, true);
  20630. }
  20631. return [start, end];
  20632. };
  20633. DataStore.prototype.appendValues = function (values, minFillLen) {
  20634. var chunks = this._chunks;
  20635. var dimensions = this._dimensions;
  20636. var dimLen = dimensions.length;
  20637. var rawExtent = this._rawExtent;
  20638. var start = this.count();
  20639. var end = start + Math.max(values.length, minFillLen || 0);
  20640. for (var i = 0; i < dimLen; i++) {
  20641. var dim = dimensions[i];
  20642. prepareStore(chunks, i, dim.type, end, true);
  20643. }
  20644. var emptyDataItem = [];
  20645. for (var idx = start; idx < end; idx++) {
  20646. var sourceIdx = idx - start; // Store the data by dimensions
  20647. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20648. var dim = dimensions[dimIdx];
  20649. var val = defaultDimValueGetters.arrayRows.call(this, values[sourceIdx] || emptyDataItem, dim.property, sourceIdx, dimIdx);
  20650. chunks[dimIdx][idx] = val;
  20651. var dimRawExtent = rawExtent[dimIdx];
  20652. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20653. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20654. }
  20655. }
  20656. this._rawCount = this._count = end;
  20657. return {
  20658. start: start,
  20659. end: end
  20660. };
  20661. };
  20662. DataStore.prototype._initDataFromProvider = function (start, end, append) {
  20663. var provider = this._provider;
  20664. var chunks = this._chunks;
  20665. var dimensions = this._dimensions;
  20666. var dimLen = dimensions.length;
  20667. var rawExtent = this._rawExtent;
  20668. var dimNames = map(dimensions, function (dim) {
  20669. return dim.property;
  20670. });
  20671. for (var i = 0; i < dimLen; i++) {
  20672. var dim = dimensions[i];
  20673. if (!rawExtent[i]) {
  20674. rawExtent[i] = getInitialExtent();
  20675. }
  20676. prepareStore(chunks, i, dim.type, end, append);
  20677. }
  20678. if (provider.fillStorage) {
  20679. provider.fillStorage(start, end, chunks, rawExtent);
  20680. } else {
  20681. var dataItem = [];
  20682. for (var idx = start; idx < end; idx++) {
  20683. // NOTICE: Try not to write things into dataItem
  20684. dataItem = provider.getItem(idx, dataItem); // Each data item is value
  20685. // [1, 2]
  20686. // 2
  20687. // Bar chart, line chart which uses category axis
  20688. // only gives the 'y' value. 'x' value is the indices of category
  20689. // Use a tempValue to normalize the value to be a (x, y) value
  20690. // Store the data by dimensions
  20691. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  20692. var dimStorage = chunks[dimIdx]; // PENDING NULL is empty or zero
  20693. var val = this._dimValueGetter(dataItem, dimNames[dimIdx], idx, dimIdx);
  20694. dimStorage[idx] = val;
  20695. var dimRawExtent = rawExtent[dimIdx];
  20696. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  20697. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  20698. }
  20699. }
  20700. }
  20701. if (!provider.persistent && provider.clean) {
  20702. // Clean unused data if data source is typed array.
  20703. provider.clean();
  20704. }
  20705. this._rawCount = this._count = end; // Reset data extent
  20706. this._extent = [];
  20707. };
  20708. DataStore.prototype.count = function () {
  20709. return this._count;
  20710. };
  20711. /**
  20712. * Get value. Return NaN if idx is out of range.
  20713. */
  20714. DataStore.prototype.get = function (dim, idx) {
  20715. if (!(idx >= 0 && idx < this._count)) {
  20716. return NaN;
  20717. }
  20718. var dimStore = this._chunks[dim];
  20719. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  20720. };
  20721. DataStore.prototype.getValues = function (dimensions, idx) {
  20722. var values = [];
  20723. var dimArr = [];
  20724. if (idx == null) {
  20725. idx = dimensions; // TODO get all from store?
  20726. dimensions = []; // All dimensions
  20727. for (var i = 0; i < this._dimensions.length; i++) {
  20728. dimArr.push(i);
  20729. }
  20730. } else {
  20731. dimArr = dimensions;
  20732. }
  20733. for (var i = 0, len = dimArr.length; i < len; i++) {
  20734. values.push(this.get(dimArr[i], idx));
  20735. }
  20736. return values;
  20737. };
  20738. /**
  20739. * @param dim concrete dim
  20740. */
  20741. DataStore.prototype.getByRawIndex = function (dim, rawIdx) {
  20742. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  20743. return NaN;
  20744. }
  20745. var dimStore = this._chunks[dim];
  20746. return dimStore ? dimStore[rawIdx] : NaN;
  20747. };
  20748. /**
  20749. * Get sum of data in one dimension
  20750. */
  20751. DataStore.prototype.getSum = function (dim) {
  20752. var dimData = this._chunks[dim];
  20753. var sum = 0;
  20754. if (dimData) {
  20755. for (var i = 0, len = this.count(); i < len; i++) {
  20756. var value = this.get(dim, i);
  20757. if (!isNaN(value)) {
  20758. sum += value;
  20759. }
  20760. }
  20761. }
  20762. return sum;
  20763. };
  20764. /**
  20765. * Get median of data in one dimension
  20766. */
  20767. DataStore.prototype.getMedian = function (dim) {
  20768. var dimDataArray = []; // map all data of one dimension
  20769. this.each([dim], function (val) {
  20770. if (!isNaN(val)) {
  20771. dimDataArray.push(val);
  20772. }
  20773. }); // TODO
  20774. // Use quick select?
  20775. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  20776. return a - b;
  20777. });
  20778. var len = this.count(); // calculate median
  20779. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  20780. };
  20781. /**
  20782. * Retrieve the index with given raw data index.
  20783. */
  20784. DataStore.prototype.indexOfRawIndex = function (rawIndex) {
  20785. if (rawIndex >= this._rawCount || rawIndex < 0) {
  20786. return -1;
  20787. }
  20788. if (!this._indices) {
  20789. return rawIndex;
  20790. } // Indices are ascending
  20791. var indices = this._indices; // If rawIndex === dataIndex
  20792. var rawDataIndex = indices[rawIndex];
  20793. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  20794. return rawIndex;
  20795. }
  20796. var left = 0;
  20797. var right = this._count - 1;
  20798. while (left <= right) {
  20799. var mid = (left + right) / 2 | 0;
  20800. if (indices[mid] < rawIndex) {
  20801. left = mid + 1;
  20802. } else if (indices[mid] > rawIndex) {
  20803. right = mid - 1;
  20804. } else {
  20805. return mid;
  20806. }
  20807. }
  20808. return -1;
  20809. };
  20810. /**
  20811. * Retrieve the index of nearest value.
  20812. * @param dim
  20813. * @param value
  20814. * @param [maxDistance=Infinity]
  20815. * @return If and only if multiple indices have
  20816. * the same value, they are put to the result.
  20817. */
  20818. DataStore.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  20819. var chunks = this._chunks;
  20820. var dimData = chunks[dim];
  20821. var nearestIndices = [];
  20822. if (!dimData) {
  20823. return nearestIndices;
  20824. }
  20825. if (maxDistance == null) {
  20826. maxDistance = Infinity;
  20827. }
  20828. var minDist = Infinity;
  20829. var minDiff = -1;
  20830. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/SeriesData.js`.
  20831. for (var i = 0, len = this.count(); i < len; i++) {
  20832. var dataIndex = this.getRawIndex(i);
  20833. var diff = value - dimData[dataIndex];
  20834. var dist = Math.abs(diff);
  20835. if (dist <= maxDistance) {
  20836. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  20837. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  20838. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  20839. // So we choose the one that `diff >= 0` in this case.
  20840. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  20841. // should be push to `nearestIndices`.
  20842. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  20843. minDist = dist;
  20844. minDiff = diff;
  20845. nearestIndicesLen = 0;
  20846. }
  20847. if (diff === minDiff) {
  20848. nearestIndices[nearestIndicesLen++] = i;
  20849. }
  20850. }
  20851. }
  20852. nearestIndices.length = nearestIndicesLen;
  20853. return nearestIndices;
  20854. };
  20855. DataStore.prototype.getIndices = function () {
  20856. var newIndices;
  20857. var indices = this._indices;
  20858. if (indices) {
  20859. var Ctor = indices.constructor;
  20860. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  20861. if (Ctor === Array) {
  20862. newIndices = new Ctor(thisCount);
  20863. for (var i = 0; i < thisCount; i++) {
  20864. newIndices[i] = indices[i];
  20865. }
  20866. } else {
  20867. newIndices = new Ctor(indices.buffer, 0, thisCount);
  20868. }
  20869. } else {
  20870. var Ctor = getIndicesCtor(this._rawCount);
  20871. newIndices = new Ctor(this.count());
  20872. for (var i = 0; i < newIndices.length; i++) {
  20873. newIndices[i] = i;
  20874. }
  20875. }
  20876. return newIndices;
  20877. };
  20878. /**
  20879. * Data filter.
  20880. */
  20881. DataStore.prototype.filter = function (dims, cb) {
  20882. if (!this._count) {
  20883. return this;
  20884. }
  20885. var newStore = this.clone();
  20886. var count = newStore.count();
  20887. var Ctor = getIndicesCtor(newStore._rawCount);
  20888. var newIndices = new Ctor(count);
  20889. var value = [];
  20890. var dimSize = dims.length;
  20891. var offset = 0;
  20892. var dim0 = dims[0];
  20893. var chunks = newStore._chunks;
  20894. for (var i = 0; i < count; i++) {
  20895. var keep = void 0;
  20896. var rawIdx = newStore.getRawIndex(i); // Simple optimization
  20897. if (dimSize === 0) {
  20898. keep = cb(i);
  20899. } else if (dimSize === 1) {
  20900. var val = chunks[dim0][rawIdx];
  20901. keep = cb(val, i);
  20902. } else {
  20903. var k = 0;
  20904. for (; k < dimSize; k++) {
  20905. value[k] = chunks[dims[k]][rawIdx];
  20906. }
  20907. value[k] = i;
  20908. keep = cb.apply(null, value);
  20909. }
  20910. if (keep) {
  20911. newIndices[offset++] = rawIdx;
  20912. }
  20913. } // Set indices after filtered.
  20914. if (offset < count) {
  20915. newStore._indices = newIndices;
  20916. }
  20917. newStore._count = offset; // Reset data extent
  20918. newStore._extent = [];
  20919. newStore._updateGetRawIdx();
  20920. return newStore;
  20921. };
  20922. /**
  20923. * Select data in range. (For optimization of filter)
  20924. * (Manually inline code, support 5 million data filtering in data zoom.)
  20925. */
  20926. DataStore.prototype.selectRange = function (range) {
  20927. var newStore = this.clone();
  20928. var len = newStore._count;
  20929. if (!len) {
  20930. return this;
  20931. }
  20932. var dims = keys(range);
  20933. var dimSize = dims.length;
  20934. if (!dimSize) {
  20935. return this;
  20936. }
  20937. var originalCount = newStore.count();
  20938. var Ctor = getIndicesCtor(newStore._rawCount);
  20939. var newIndices = new Ctor(originalCount);
  20940. var offset = 0;
  20941. var dim0 = dims[0];
  20942. var min = range[dim0][0];
  20943. var max = range[dim0][1];
  20944. var storeArr = newStore._chunks;
  20945. var quickFinished = false;
  20946. if (!newStore._indices) {
  20947. // Extreme optimization for common case. About 2x faster in chrome.
  20948. var idx = 0;
  20949. if (dimSize === 1) {
  20950. var dimStorage = storeArr[dims[0]];
  20951. for (var i = 0; i < len; i++) {
  20952. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  20953. // value indicates the line should be broken. But for the case like
  20954. // scatter plot, a data item with empty value will not be rendered,
  20955. // but the axis extent may be effected if some other dim of the data
  20956. // item has value. Fortunately it is not a significant negative effect.
  20957. if (val >= min && val <= max || isNaN(val)) {
  20958. newIndices[offset++] = idx;
  20959. }
  20960. idx++;
  20961. }
  20962. quickFinished = true;
  20963. } else if (dimSize === 2) {
  20964. var dimStorage = storeArr[dims[0]];
  20965. var dimStorage2 = storeArr[dims[1]];
  20966. var min2 = range[dims[1]][0];
  20967. var max2 = range[dims[1]][1];
  20968. for (var i = 0; i < len; i++) {
  20969. var val = dimStorage[i];
  20970. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  20971. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  20972. newIndices[offset++] = idx;
  20973. }
  20974. idx++;
  20975. }
  20976. quickFinished = true;
  20977. }
  20978. }
  20979. if (!quickFinished) {
  20980. if (dimSize === 1) {
  20981. for (var i = 0; i < originalCount; i++) {
  20982. var rawIndex = newStore.getRawIndex(i);
  20983. var val = storeArr[dims[0]][rawIndex]; // Do not filter NaN, see comment above.
  20984. if (val >= min && val <= max || isNaN(val)) {
  20985. newIndices[offset++] = rawIndex;
  20986. }
  20987. }
  20988. } else {
  20989. for (var i = 0; i < originalCount; i++) {
  20990. var keep = true;
  20991. var rawIndex = newStore.getRawIndex(i);
  20992. for (var k = 0; k < dimSize; k++) {
  20993. var dimk = dims[k];
  20994. var val = storeArr[dimk][rawIndex]; // Do not filter NaN, see comment above.
  20995. if (val < range[dimk][0] || val > range[dimk][1]) {
  20996. keep = false;
  20997. }
  20998. }
  20999. if (keep) {
  21000. newIndices[offset++] = newStore.getRawIndex(i);
  21001. }
  21002. }
  21003. }
  21004. } // Set indices after filtered.
  21005. if (offset < originalCount) {
  21006. newStore._indices = newIndices;
  21007. }
  21008. newStore._count = offset; // Reset data extent
  21009. newStore._extent = [];
  21010. newStore._updateGetRawIdx();
  21011. return newStore;
  21012. }; // /**
  21013. // * Data mapping to a plain array
  21014. // */
  21015. // mapArray(dims: DimensionIndex[], cb: MapArrayCb): any[] {
  21016. // const result: any[] = [];
  21017. // this.each(dims, function () {
  21018. // result.push(cb && (cb as MapArrayCb).apply(null, arguments));
  21019. // });
  21020. // return result;
  21021. // }
  21022. /**
  21023. * Data mapping to a new List with given dimensions
  21024. */
  21025. DataStore.prototype.map = function (dims, cb) {
  21026. // TODO only clone picked chunks.
  21027. var target = this.clone(dims);
  21028. this._updateDims(target, dims, cb);
  21029. return target;
  21030. };
  21031. /**
  21032. * @caution Danger!! Only used in dataStack.
  21033. */
  21034. DataStore.prototype.modify = function (dims, cb) {
  21035. this._updateDims(this, dims, cb);
  21036. };
  21037. DataStore.prototype._updateDims = function (target, dims, cb) {
  21038. var targetChunks = target._chunks;
  21039. var tmpRetValue = [];
  21040. var dimSize = dims.length;
  21041. var dataCount = target.count();
  21042. var values = [];
  21043. var rawExtent = target._rawExtent;
  21044. for (var i = 0; i < dims.length; i++) {
  21045. rawExtent[dims[i]] = getInitialExtent();
  21046. }
  21047. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  21048. var rawIndex = target.getRawIndex(dataIndex);
  21049. for (var k = 0; k < dimSize; k++) {
  21050. values[k] = targetChunks[dims[k]][rawIndex];
  21051. }
  21052. values[dimSize] = dataIndex;
  21053. var retValue = cb && cb.apply(null, values);
  21054. if (retValue != null) {
  21055. // a number or string (in oridinal dimension)?
  21056. if (typeof retValue !== 'object') {
  21057. tmpRetValue[0] = retValue;
  21058. retValue = tmpRetValue;
  21059. }
  21060. for (var i = 0; i < retValue.length; i++) {
  21061. var dim = dims[i];
  21062. var val = retValue[i];
  21063. var rawExtentOnDim = rawExtent[dim];
  21064. var dimStore = targetChunks[dim];
  21065. if (dimStore) {
  21066. dimStore[rawIndex] = val;
  21067. }
  21068. if (val < rawExtentOnDim[0]) {
  21069. rawExtentOnDim[0] = val;
  21070. }
  21071. if (val > rawExtentOnDim[1]) {
  21072. rawExtentOnDim[1] = val;
  21073. }
  21074. }
  21075. }
  21076. }
  21077. };
  21078. /**
  21079. * Large data down sampling using largest-triangle-three-buckets
  21080. * @param {string} valueDimension
  21081. * @param {number} targetCount
  21082. */
  21083. DataStore.prototype.lttbDownSample = function (valueDimension, rate) {
  21084. var target = this.clone([valueDimension], true);
  21085. var targetStorage = target._chunks;
  21086. var dimStore = targetStorage[valueDimension];
  21087. var len = this.count();
  21088. var sampledIndex = 0;
  21089. var frameSize = Math.floor(1 / rate);
  21090. var currentRawIndex = this.getRawIndex(0);
  21091. var maxArea;
  21092. var area;
  21093. var nextRawIndex;
  21094. var newIndices = new (getIndicesCtor(this._rawCount))(Math.min((Math.ceil(len / frameSize) + 2) * 2, len)); // First frame use the first data.
  21095. newIndices[sampledIndex++] = currentRawIndex;
  21096. for (var i = 1; i < len - 1; i += frameSize) {
  21097. var nextFrameStart = Math.min(i + frameSize, len - 1);
  21098. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  21099. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  21100. var avgY = 0;
  21101. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  21102. var rawIndex = this.getRawIndex(idx);
  21103. var y = dimStore[rawIndex];
  21104. if (isNaN(y)) {
  21105. continue;
  21106. }
  21107. avgY += y;
  21108. }
  21109. avgY /= nextFrameEnd - nextFrameStart;
  21110. var frameStart = i;
  21111. var frameEnd = Math.min(i + frameSize, len);
  21112. var pointAX = i - 1;
  21113. var pointAY = dimStore[currentRawIndex];
  21114. maxArea = -1;
  21115. nextRawIndex = frameStart;
  21116. var firstNaNIndex = -1;
  21117. var countNaN = 0; // Find a point from current frame that construct a triangle with largest area with previous selected point
  21118. // And the average of next frame.
  21119. for (var idx = frameStart; idx < frameEnd; idx++) {
  21120. var rawIndex = this.getRawIndex(idx);
  21121. var y = dimStore[rawIndex];
  21122. if (isNaN(y)) {
  21123. countNaN++;
  21124. if (firstNaNIndex < 0) {
  21125. firstNaNIndex = rawIndex;
  21126. }
  21127. continue;
  21128. } // Calculate triangle area over three buckets
  21129. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  21130. if (area > maxArea) {
  21131. maxArea = area;
  21132. nextRawIndex = rawIndex; // Next a is this b
  21133. }
  21134. }
  21135. if (countNaN > 0 && countNaN < frameEnd - frameStart) {
  21136. // Append first NaN point in every bucket.
  21137. // It is necessary to ensure the correct order of indices.
  21138. newIndices[sampledIndex++] = Math.min(firstNaNIndex, nextRawIndex);
  21139. nextRawIndex = Math.max(firstNaNIndex, nextRawIndex);
  21140. }
  21141. newIndices[sampledIndex++] = nextRawIndex;
  21142. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  21143. } // First frame use the last data.
  21144. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  21145. target._count = sampledIndex;
  21146. target._indices = newIndices;
  21147. target.getRawIndex = this._getRawIdx;
  21148. return target;
  21149. };
  21150. /**
  21151. * Large data down sampling on given dimension
  21152. * @param sampleIndex Sample index for name and id
  21153. */
  21154. DataStore.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  21155. var target = this.clone([dimension], true);
  21156. var targetStorage = target._chunks;
  21157. var frameValues = [];
  21158. var frameSize = Math.floor(1 / rate);
  21159. var dimStore = targetStorage[dimension];
  21160. var len = this.count();
  21161. var rawExtentOnDim = target._rawExtent[dimension] = getInitialExtent();
  21162. var newIndices = new (getIndicesCtor(this._rawCount))(Math.ceil(len / frameSize));
  21163. var offset = 0;
  21164. for (var i = 0; i < len; i += frameSize) {
  21165. // Last frame
  21166. if (frameSize > len - i) {
  21167. frameSize = len - i;
  21168. frameValues.length = frameSize;
  21169. }
  21170. for (var k = 0; k < frameSize; k++) {
  21171. var dataIdx = this.getRawIndex(i + k);
  21172. frameValues[k] = dimStore[dataIdx];
  21173. }
  21174. var value = sampleValue(frameValues);
  21175. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  21176. dimStore[sampleFrameIdx] = value;
  21177. if (value < rawExtentOnDim[0]) {
  21178. rawExtentOnDim[0] = value;
  21179. }
  21180. if (value > rawExtentOnDim[1]) {
  21181. rawExtentOnDim[1] = value;
  21182. }
  21183. newIndices[offset++] = sampleFrameIdx;
  21184. }
  21185. target._count = offset;
  21186. target._indices = newIndices;
  21187. target._updateGetRawIdx();
  21188. return target;
  21189. };
  21190. /**
  21191. * Data iteration
  21192. * @param ctx default this
  21193. * @example
  21194. * list.each('x', function (x, idx) {});
  21195. * list.each(['x', 'y'], function (x, y, idx) {});
  21196. * list.each(function (idx) {})
  21197. */
  21198. DataStore.prototype.each = function (dims, cb) {
  21199. if (!this._count) {
  21200. return;
  21201. }
  21202. var dimSize = dims.length;
  21203. var chunks = this._chunks;
  21204. for (var i = 0, len = this.count(); i < len; i++) {
  21205. var rawIdx = this.getRawIndex(i); // Simple optimization
  21206. switch (dimSize) {
  21207. case 0:
  21208. cb(i);
  21209. break;
  21210. case 1:
  21211. cb(chunks[dims[0]][rawIdx], i);
  21212. break;
  21213. case 2:
  21214. cb(chunks[dims[0]][rawIdx], chunks[dims[1]][rawIdx], i);
  21215. break;
  21216. default:
  21217. var k = 0;
  21218. var value = [];
  21219. for (; k < dimSize; k++) {
  21220. value[k] = chunks[dims[k]][rawIdx];
  21221. } // Index
  21222. value[k] = i;
  21223. cb.apply(null, value);
  21224. }
  21225. }
  21226. };
  21227. /**
  21228. * Get extent of data in one dimension
  21229. */
  21230. DataStore.prototype.getDataExtent = function (dim) {
  21231. // Make sure use concrete dim as cache name.
  21232. var dimData = this._chunks[dim];
  21233. var initialExtent = getInitialExtent();
  21234. if (!dimData) {
  21235. return initialExtent;
  21236. } // Make more strict checkings to ensure hitting cache.
  21237. var currEnd = this.count(); // Consider the most cases when using data zoom, `getDataExtent`
  21238. // happened before filtering. We cache raw extent, which is not
  21239. // necessary to be cleared and recalculated when restore data.
  21240. var useRaw = !this._indices;
  21241. var dimExtent;
  21242. if (useRaw) {
  21243. return this._rawExtent[dim].slice();
  21244. }
  21245. dimExtent = this._extent[dim];
  21246. if (dimExtent) {
  21247. return dimExtent.slice();
  21248. }
  21249. dimExtent = initialExtent;
  21250. var min = dimExtent[0];
  21251. var max = dimExtent[1];
  21252. for (var i = 0; i < currEnd; i++) {
  21253. var rawIdx = this.getRawIndex(i);
  21254. var value = dimData[rawIdx];
  21255. value < min && (min = value);
  21256. value > max && (max = value);
  21257. }
  21258. dimExtent = [min, max];
  21259. this._extent[dim] = dimExtent;
  21260. return dimExtent;
  21261. };
  21262. /**
  21263. * Get raw data item
  21264. */
  21265. DataStore.prototype.getRawDataItem = function (idx) {
  21266. var rawIdx = this.getRawIndex(idx);
  21267. if (!this._provider.persistent) {
  21268. var val = [];
  21269. var chunks = this._chunks;
  21270. for (var i = 0; i < chunks.length; i++) {
  21271. val.push(chunks[i][rawIdx]);
  21272. }
  21273. return val;
  21274. } else {
  21275. return this._provider.getItem(rawIdx);
  21276. }
  21277. };
  21278. /**
  21279. * Clone shallow.
  21280. *
  21281. * @param clonedDims Determine which dims to clone. Will share the data if not specified.
  21282. */
  21283. DataStore.prototype.clone = function (clonedDims, ignoreIndices) {
  21284. var target = new DataStore();
  21285. var chunks = this._chunks;
  21286. var clonedDimsMap = clonedDims && reduce(clonedDims, function (obj, dimIdx) {
  21287. obj[dimIdx] = true;
  21288. return obj;
  21289. }, {});
  21290. if (clonedDimsMap) {
  21291. for (var i = 0; i < chunks.length; i++) {
  21292. // Not clone if dim is not picked.
  21293. target._chunks[i] = !clonedDimsMap[i] ? chunks[i] : cloneChunk(chunks[i]);
  21294. }
  21295. } else {
  21296. target._chunks = chunks;
  21297. }
  21298. this._copyCommonProps(target);
  21299. if (!ignoreIndices) {
  21300. target._indices = this._cloneIndices();
  21301. }
  21302. target._updateGetRawIdx();
  21303. return target;
  21304. };
  21305. DataStore.prototype._copyCommonProps = function (target) {
  21306. target._count = this._count;
  21307. target._rawCount = this._rawCount;
  21308. target._provider = this._provider;
  21309. target._dimensions = this._dimensions;
  21310. target._extent = clone(this._extent);
  21311. target._rawExtent = clone(this._rawExtent);
  21312. };
  21313. DataStore.prototype._cloneIndices = function () {
  21314. if (this._indices) {
  21315. var Ctor = this._indices.constructor;
  21316. var indices = void 0;
  21317. if (Ctor === Array) {
  21318. var thisCount = this._indices.length;
  21319. indices = new Ctor(thisCount);
  21320. for (var i = 0; i < thisCount; i++) {
  21321. indices[i] = this._indices[i];
  21322. }
  21323. } else {
  21324. indices = new Ctor(this._indices);
  21325. }
  21326. return indices;
  21327. }
  21328. return null;
  21329. };
  21330. DataStore.prototype._getRawIdxIdentity = function (idx) {
  21331. return idx;
  21332. };
  21333. DataStore.prototype._getRawIdx = function (idx) {
  21334. if (idx < this._count && idx >= 0) {
  21335. return this._indices[idx];
  21336. }
  21337. return -1;
  21338. };
  21339. DataStore.prototype._updateGetRawIdx = function () {
  21340. this.getRawIndex = this._indices ? this._getRawIdx : this._getRawIdxIdentity;
  21341. };
  21342. DataStore.internalField = function () {
  21343. function getDimValueSimply(dataItem, property, dataIndex, dimIndex) {
  21344. return parseDataValue(dataItem[dimIndex], this._dimensions[dimIndex]);
  21345. }
  21346. defaultDimValueGetters = {
  21347. arrayRows: getDimValueSimply,
  21348. objectRows: function (dataItem, property, dataIndex, dimIndex) {
  21349. return parseDataValue(dataItem[property], this._dimensions[dimIndex]);
  21350. },
  21351. keyedColumns: getDimValueSimply,
  21352. original: function (dataItem, property, dataIndex, dimIndex) {
  21353. // Performance sensitive, do not use modelUtil.getDataItemValue.
  21354. // If dataItem is an plain object with no value field, the let `value`
  21355. // will be assigned with the object, but it will be tread correctly
  21356. // in the `convertValue`.
  21357. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  21358. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  21359. : value, this._dimensions[dimIndex]);
  21360. },
  21361. typedArray: function (dataItem, property, dataIndex, dimIndex) {
  21362. return dataItem[dimIndex];
  21363. }
  21364. };
  21365. }();
  21366. return DataStore;
  21367. }();
  21368. /**
  21369. * [REQUIREMENT_MEMO]:
  21370. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  21371. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  21372. * `root-dataset`. Them on `series` has higher priority.
  21373. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  21374. * confuse users: whether those props indicate how to visit the upstream source or visit
  21375. * the transform result source, and some transforms has nothing to do with these props,
  21376. * and some transforms might have multiple upstream.
  21377. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  21378. * declared in `root-dataset`.
  21379. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  21380. * That is for reducing complexity in transforms.
  21381. * PENDING: Whether to provide transposition transform?
  21382. *
  21383. * [IMPLEMENTAION_MEMO]:
  21384. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  21385. * They will not be calculated until `source` is about to be visited (to prevent from
  21386. * duplicate calcuation). `source` is visited only in series and input to transforms.
  21387. *
  21388. * [DIMENSION_INHERIT_RULE]:
  21389. * By default the dimensions are inherited from ancestors, unless a transform return
  21390. * a new dimensions definition.
  21391. * Consider the case:
  21392. * ```js
  21393. * dataset: [{
  21394. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  21395. * }, {
  21396. * transform: { type: 'filter', ... }
  21397. * }]
  21398. * dataset: [{
  21399. * dimension: ['Product', 'Sales', 'Prise'],
  21400. * source: [ ['Cookies', 321, 44.21], ...]
  21401. * }, {
  21402. * transform: { type: 'filter', ... }
  21403. * }]
  21404. * ```
  21405. * The two types of option should have the same behavior after transform.
  21406. *
  21407. *
  21408. * [SCENARIO]:
  21409. * (1) Provide source data directly:
  21410. * ```js
  21411. * series: {
  21412. * encode: {...},
  21413. * dimensions: [...]
  21414. * seriesLayoutBy: 'row',
  21415. * data: [[...]]
  21416. * }
  21417. * ```
  21418. * (2) Series refer to dataset.
  21419. * ```js
  21420. * series: [{
  21421. * encode: {...}
  21422. * // Ignore datasetIndex means `datasetIndex: 0`
  21423. * // and the dimensions defination in dataset is used
  21424. * }, {
  21425. * encode: {...},
  21426. * seriesLayoutBy: 'column',
  21427. * datasetIndex: 1
  21428. * }]
  21429. * ```
  21430. * (3) dataset transform
  21431. * ```js
  21432. * dataset: [{
  21433. * source: [...]
  21434. * }, {
  21435. * source: [...]
  21436. * }, {
  21437. * // By default from 0.
  21438. * transform: { type: 'filter', config: {...} }
  21439. * }, {
  21440. * // Piped.
  21441. * transform: [
  21442. * { type: 'filter', config: {...} },
  21443. * { type: 'sort', config: {...} }
  21444. * ]
  21445. * }, {
  21446. * id: 'regressionData',
  21447. * fromDatasetIndex: 1,
  21448. * // Third-party transform
  21449. * transform: { type: 'ecStat:regression', config: {...} }
  21450. * }, {
  21451. * // retrieve the extra result.
  21452. * id: 'regressionFormula',
  21453. * fromDatasetId: 'regressionData',
  21454. * fromTransformResult: 1
  21455. * }]
  21456. * ```
  21457. */
  21458. var SourceManager =
  21459. /** @class */
  21460. function () {
  21461. function SourceManager(sourceHost) {
  21462. // Cached source. Do not repeat calculating if not dirty.
  21463. this._sourceList = [];
  21464. this._storeList = []; // version sign of each upstream source manager.
  21465. this._upstreamSignList = [];
  21466. this._versionSignBase = 0;
  21467. this._dirty = true;
  21468. this._sourceHost = sourceHost;
  21469. }
  21470. /**
  21471. * Mark dirty.
  21472. */
  21473. SourceManager.prototype.dirty = function () {
  21474. this._setLocalSource([], []);
  21475. this._storeList = [];
  21476. this._dirty = true;
  21477. };
  21478. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  21479. this._sourceList = sourceList;
  21480. this._upstreamSignList = upstreamSignList;
  21481. this._versionSignBase++;
  21482. if (this._versionSignBase > 9e10) {
  21483. this._versionSignBase = 0;
  21484. }
  21485. };
  21486. /**
  21487. * For detecting whether the upstream source is dirty, so that
  21488. * the local cached source (in `_sourceList`) should be discarded.
  21489. */
  21490. SourceManager.prototype._getVersionSign = function () {
  21491. return this._sourceHost.uid + '_' + this._versionSignBase;
  21492. };
  21493. /**
  21494. * Always return a source instance. Otherwise throw error.
  21495. */
  21496. SourceManager.prototype.prepareSource = function () {
  21497. // For the case that call `setOption` multiple time but no data changed,
  21498. // cache the result source to prevent from repeating transform.
  21499. if (this._isDirty()) {
  21500. this._createSource();
  21501. this._dirty = false;
  21502. }
  21503. };
  21504. SourceManager.prototype._createSource = function () {
  21505. this._setLocalSource([], []);
  21506. var sourceHost = this._sourceHost;
  21507. var upSourceMgrList = this._getUpstreamSourceManagers();
  21508. var hasUpstream = !!upSourceMgrList.length;
  21509. var resultSourceList;
  21510. var upstreamSignList;
  21511. if (isSeries(sourceHost)) {
  21512. var seriesModel = sourceHost;
  21513. var data = void 0;
  21514. var sourceFormat = void 0;
  21515. var upSource = void 0; // Has upstream dataset
  21516. if (hasUpstream) {
  21517. var upSourceMgr = upSourceMgrList[0];
  21518. upSourceMgr.prepareSource();
  21519. upSource = upSourceMgr.getSource();
  21520. data = upSource.data;
  21521. sourceFormat = upSource.sourceFormat;
  21522. upstreamSignList = [upSourceMgr._getVersionSign()];
  21523. } // Series data is from own.
  21524. else {
  21525. data = seriesModel.get('data', true);
  21526. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  21527. upstreamSignList = [];
  21528. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  21529. var newMetaRawOption = this._getSourceMetaRawOption() || {};
  21530. var upMetaRawOption = upSource && upSource.metaRawOption || {};
  21531. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption.seriesLayoutBy) || null;
  21532. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption.sourceHeader); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  21533. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  21534. // but series need `seriesLayoutBy: 'row'`.
  21535. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption.dimensions); // We share source with dataset as much as possible
  21536. // to avoid extra memory cost of high dimensional data.
  21537. var needsCreateSource = seriesLayoutBy !== upMetaRawOption.seriesLayoutBy || !!sourceHeader !== !!upMetaRawOption.sourceHeader || dimensions;
  21538. resultSourceList = needsCreateSource ? [createSource(data, {
  21539. seriesLayoutBy: seriesLayoutBy,
  21540. sourceHeader: sourceHeader,
  21541. dimensions: dimensions
  21542. }, sourceFormat)] : [];
  21543. } else {
  21544. var datasetModel = sourceHost; // Has upstream dataset.
  21545. if (hasUpstream) {
  21546. var result = this._applyTransform(upSourceMgrList);
  21547. resultSourceList = result.sourceList;
  21548. upstreamSignList = result.upstreamSignList;
  21549. } // Is root dataset.
  21550. else {
  21551. var sourceData = datasetModel.get('source', true);
  21552. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null)];
  21553. upstreamSignList = [];
  21554. }
  21555. }
  21556. if ("development" !== 'production') {
  21557. assert(resultSourceList && upstreamSignList);
  21558. }
  21559. this._setLocalSource(resultSourceList, upstreamSignList);
  21560. };
  21561. SourceManager.prototype._applyTransform = function (upMgrList) {
  21562. var datasetModel = this._sourceHost;
  21563. var transformOption = datasetModel.get('transform', true);
  21564. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  21565. if ("development" !== 'production') {
  21566. assert(fromTransformResult != null || transformOption != null);
  21567. }
  21568. if (fromTransformResult != null) {
  21569. var errMsg = '';
  21570. if (upMgrList.length !== 1) {
  21571. if ("development" !== 'production') {
  21572. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  21573. }
  21574. doThrow(errMsg);
  21575. }
  21576. }
  21577. var sourceList;
  21578. var upSourceList = [];
  21579. var upstreamSignList = [];
  21580. each(upMgrList, function (upMgr) {
  21581. upMgr.prepareSource();
  21582. var upSource = upMgr.getSource(fromTransformResult || 0);
  21583. var errMsg = '';
  21584. if (fromTransformResult != null && !upSource) {
  21585. if ("development" !== 'production') {
  21586. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  21587. }
  21588. doThrow(errMsg);
  21589. }
  21590. upSourceList.push(upSource);
  21591. upstreamSignList.push(upMgr._getVersionSign());
  21592. });
  21593. if (transformOption) {
  21594. sourceList = applyDataTransform(transformOption, upSourceList, {
  21595. datasetIndex: datasetModel.componentIndex
  21596. });
  21597. } else if (fromTransformResult != null) {
  21598. sourceList = [cloneSourceShallow(upSourceList[0])];
  21599. }
  21600. return {
  21601. sourceList: sourceList,
  21602. upstreamSignList: upstreamSignList
  21603. };
  21604. };
  21605. SourceManager.prototype._isDirty = function () {
  21606. if (this._dirty) {
  21607. return true;
  21608. } // All sourceList is from the some upstream.
  21609. var upSourceMgrList = this._getUpstreamSourceManagers();
  21610. for (var i = 0; i < upSourceMgrList.length; i++) {
  21611. var upSrcMgr = upSourceMgrList[i];
  21612. if ( // Consider the case that there is ancestor diry, call it recursively.
  21613. // The performance is probably not an issue because usually the chain is not long.
  21614. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  21615. return true;
  21616. }
  21617. }
  21618. };
  21619. /**
  21620. * @param sourceIndex By default 0, means "main source".
  21621. * In most cases there is only one source.
  21622. */
  21623. SourceManager.prototype.getSource = function (sourceIndex) {
  21624. sourceIndex = sourceIndex || 0;
  21625. var source = this._sourceList[sourceIndex];
  21626. if (!source) {
  21627. // Series may share source instance with dataset.
  21628. var upSourceMgrList = this._getUpstreamSourceManagers();
  21629. return upSourceMgrList[0] && upSourceMgrList[0].getSource(sourceIndex);
  21630. }
  21631. return source;
  21632. };
  21633. /**
  21634. *
  21635. * Get a data store which can be shared across series.
  21636. * Only available for series.
  21637. *
  21638. * @param seriesDimRequest Dimensions that are generated in series.
  21639. * Should have been sorted by `storeDimIndex` asc.
  21640. */
  21641. SourceManager.prototype.getSharedDataStore = function (seriesDimRequest) {
  21642. if ("development" !== 'production') {
  21643. assert(isSeries(this._sourceHost), 'Can only call getDataStore on series source manager.');
  21644. }
  21645. var schema = seriesDimRequest.makeStoreSchema();
  21646. return this._innerGetDataStore(schema.dimensions, seriesDimRequest.source, schema.hash);
  21647. };
  21648. SourceManager.prototype._innerGetDataStore = function (storeDims, seriesSource, sourceReadKey) {
  21649. // TODO Can use other sourceIndex?
  21650. var sourceIndex = 0;
  21651. var storeList = this._storeList;
  21652. var cachedStoreMap = storeList[sourceIndex];
  21653. if (!cachedStoreMap) {
  21654. cachedStoreMap = storeList[sourceIndex] = {};
  21655. }
  21656. var cachedStore = cachedStoreMap[sourceReadKey];
  21657. if (!cachedStore) {
  21658. var upSourceMgr = this._getUpstreamSourceManagers()[0];
  21659. if (isSeries(this._sourceHost) && upSourceMgr) {
  21660. cachedStore = upSourceMgr._innerGetDataStore(storeDims, seriesSource, sourceReadKey);
  21661. } else {
  21662. cachedStore = new DataStore(); // Always create store from source of series.
  21663. cachedStore.initData(new DefaultDataProvider(seriesSource, storeDims.length), storeDims);
  21664. }
  21665. cachedStoreMap[sourceReadKey] = cachedStore;
  21666. }
  21667. return cachedStore;
  21668. };
  21669. /**
  21670. * PENDING: Is it fast enough?
  21671. * If no upstream, return empty array.
  21672. */
  21673. SourceManager.prototype._getUpstreamSourceManagers = function () {
  21674. // Always get the relationship from the raw option.
  21675. // Do not cache the link of the dependency graph, so that
  21676. // there is no need to update them when change happens.
  21677. var sourceHost = this._sourceHost;
  21678. if (isSeries(sourceHost)) {
  21679. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  21680. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  21681. } else {
  21682. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  21683. return datasetModel.getSourceManager();
  21684. });
  21685. }
  21686. };
  21687. SourceManager.prototype._getSourceMetaRawOption = function () {
  21688. var sourceHost = this._sourceHost;
  21689. var seriesLayoutBy;
  21690. var sourceHeader;
  21691. var dimensions;
  21692. if (isSeries(sourceHost)) {
  21693. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  21694. sourceHeader = sourceHost.get('sourceHeader', true);
  21695. dimensions = sourceHost.get('dimensions', true);
  21696. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  21697. else if (!this._getUpstreamSourceManagers().length) {
  21698. var model = sourceHost;
  21699. seriesLayoutBy = model.get('seriesLayoutBy', true);
  21700. sourceHeader = model.get('sourceHeader', true);
  21701. dimensions = model.get('dimensions', true);
  21702. }
  21703. return {
  21704. seriesLayoutBy: seriesLayoutBy,
  21705. sourceHeader: sourceHeader,
  21706. dimensions: dimensions
  21707. };
  21708. };
  21709. return SourceManager;
  21710. }();
  21711. // disable the transform merge, but do not disable transform clone from rawOption.
  21712. function disableTransformOptionMerge(datasetModel) {
  21713. var transformOption = datasetModel.option.transform;
  21714. transformOption && setAsPrimitive(datasetModel.option.transform);
  21715. }
  21716. function isSeries(sourceHost) {
  21717. // Avoid circular dependency with Series.ts
  21718. return sourceHost.mainType === 'series';
  21719. }
  21720. function doThrow(errMsg) {
  21721. throw new Error(errMsg);
  21722. }
  21723. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  21724. function getTooltipTextStyle(textStyle, renderMode) {
  21725. var nameFontColor = textStyle.color || '#6e7079';
  21726. var nameFontSize = textStyle.fontSize || 12;
  21727. var nameFontWeight = textStyle.fontWeight || '400';
  21728. var valueFontColor = textStyle.color || '#464646';
  21729. var valueFontSize = textStyle.fontSize || 14;
  21730. var valueFontWeight = textStyle.fontWeight || '900';
  21731. if (renderMode === 'html') {
  21732. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  21733. return {
  21734. // eslint-disable-next-line max-len
  21735. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  21736. // eslint-disable-next-line max-len
  21737. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  21738. };
  21739. } else {
  21740. return {
  21741. nameStyle: {
  21742. fontSize: nameFontSize,
  21743. fill: nameFontColor,
  21744. fontWeight: nameFontWeight
  21745. },
  21746. valueStyle: {
  21747. fontSize: valueFontSize,
  21748. fill: valueFontColor,
  21749. fontWeight: valueFontWeight
  21750. }
  21751. };
  21752. }
  21753. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  21754. // (value from UI design)
  21755. var HTML_GAPS = [0, 10, 20, 30];
  21756. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  21757. function createTooltipMarkup(type, option) {
  21758. option.type = type;
  21759. return option;
  21760. }
  21761. function isSectionFragment(frag) {
  21762. return frag.type === 'section';
  21763. }
  21764. function getBuilder(frag) {
  21765. return isSectionFragment(frag) ? buildSection : buildNameValue;
  21766. }
  21767. function getBlockGapLevel(frag) {
  21768. if (isSectionFragment(frag)) {
  21769. var gapLevel_1 = 0;
  21770. var subBlockLen = frag.blocks.length;
  21771. var hasInnerGap_1 = subBlockLen > 1 || subBlockLen > 0 && !frag.noHeader;
  21772. each(frag.blocks, function (subBlock) {
  21773. var subGapLevel = getBlockGapLevel(subBlock); // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  21774. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  21775. if (subGapLevel >= gapLevel_1) {
  21776. gapLevel_1 = subGapLevel + +(hasInnerGap_1 && ( // 0 always can not be readable gap level.
  21777. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  21778. // look weird in case `multipleSeries`.
  21779. || isSectionFragment(subBlock) && !subBlock.noHeader));
  21780. }
  21781. });
  21782. return gapLevel_1;
  21783. }
  21784. return 0;
  21785. }
  21786. function buildSection(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21787. var noHeader = fragment.noHeader;
  21788. var gaps = getGap(getBlockGapLevel(fragment));
  21789. var subMarkupTextList = [];
  21790. var subBlocks = fragment.blocks || [];
  21791. assert(!subBlocks || isArray(subBlocks));
  21792. subBlocks = subBlocks || [];
  21793. var orderMode = ctx.orderMode;
  21794. if (fragment.sortBlocks && orderMode) {
  21795. subBlocks = subBlocks.slice();
  21796. var orderMap = {
  21797. valueAsc: 'asc',
  21798. valueDesc: 'desc'
  21799. };
  21800. if (hasOwn(orderMap, orderMode)) {
  21801. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  21802. subBlocks.sort(function (a, b) {
  21803. return comparator_1.evaluate(a.sortParam, b.sortParam);
  21804. });
  21805. } // FIXME 'seriesDesc' necessary?
  21806. else if (orderMode === 'seriesDesc') {
  21807. subBlocks.reverse();
  21808. }
  21809. }
  21810. each(subBlocks, function (subBlock, idx) {
  21811. var valueFormatter = fragment.valueFormatter;
  21812. var subMarkupText = getBuilder(subBlock)( // Inherit valueFormatter
  21813. valueFormatter ? extend(extend({}, ctx), {
  21814. valueFormatter: valueFormatter
  21815. }) : ctx, subBlock, idx > 0 ? gaps.html : 0, toolTipTextStyle);
  21816. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  21817. });
  21818. var subMarkupText = ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), noHeader ? topMarginForOuterGap : gaps.html);
  21819. if (noHeader) {
  21820. return subMarkupText;
  21821. }
  21822. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  21823. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  21824. if (ctx.renderMode === 'richText') {
  21825. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  21826. } else {
  21827. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  21828. }
  21829. }
  21830. function buildNameValue(ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  21831. var renderMode = ctx.renderMode;
  21832. var noName = fragment.noName;
  21833. var noValue = fragment.noValue;
  21834. var noMarker = !fragment.markerType;
  21835. var name = fragment.name;
  21836. var useUTC = ctx.useUTC;
  21837. var valueFormatter = fragment.valueFormatter || ctx.valueFormatter || function (value) {
  21838. value = isArray(value) ? value : [value];
  21839. return map(value, function (val, idx) {
  21840. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  21841. });
  21842. };
  21843. if (noName && noValue) {
  21844. return;
  21845. }
  21846. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  21847. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  21848. var valueTypeOption = fragment.valueType;
  21849. var readableValueList = noValue ? [] : valueFormatter(fragment.value);
  21850. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  21851. var valueCloseToMarker = !noMarker && noName;
  21852. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  21853. nameStyle = _a.nameStyle,
  21854. valueStyle = _a.valueStyle;
  21855. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  21856. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  21857. }
  21858. /**
  21859. * @return markupText. null/undefined means no content.
  21860. */
  21861. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  21862. if (!fragment) {
  21863. return;
  21864. }
  21865. var builder = getBuilder(fragment);
  21866. var ctx = {
  21867. useUTC: useUTC,
  21868. renderMode: renderMode,
  21869. orderMode: orderMode,
  21870. markupStyleCreator: markupStyleCreator,
  21871. valueFormatter: fragment.valueFormatter
  21872. };
  21873. return builder(ctx, fragment, 0, toolTipTextStyle);
  21874. }
  21875. function getGap(gapLevel) {
  21876. return {
  21877. html: HTML_GAPS[gapLevel],
  21878. richText: RICH_TEXT_GAPS[gapLevel]
  21879. };
  21880. }
  21881. function wrapBlockHTML(encodedContent, topGap) {
  21882. var clearfix = '<div style="clear:both"></div>';
  21883. var marginCSS = "margin: " + topGap + "px 0 0";
  21884. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  21885. }
  21886. function wrapInlineNameHTML(name, leftHasMarker, style) {
  21887. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  21888. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  21889. }
  21890. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  21891. // Do not too close to marker, considering there are multiple values separated by spaces.
  21892. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  21893. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  21894. valueList = isArray(valueList) ? valueList : [valueList];
  21895. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  21896. + map(valueList, function (value) {
  21897. return encodeHTML(value);
  21898. }).join('&nbsp;&nbsp;') + '</span>';
  21899. }
  21900. function wrapInlineNameRichText(ctx, name, style) {
  21901. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  21902. }
  21903. function wrapInlineValueRichText(ctx, values, alignRight, valueCloseToMarker, style) {
  21904. var styles = [style];
  21905. var paddingLeft = valueCloseToMarker ? 10 : 20;
  21906. alignRight && styles.push({
  21907. padding: [0, 0, 0, paddingLeft],
  21908. align: 'right'
  21909. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  21910. return ctx.markupStyleCreator.wrapRichTextStyle(isArray(values) ? values.join(' ') : values, styles);
  21911. }
  21912. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  21913. var style = series.getData().getItemVisual(dataIndex, 'style');
  21914. var color = style[series.visualDrawType];
  21915. return convertToColorString(color);
  21916. }
  21917. function getPaddingFromTooltipModel(model, renderMode) {
  21918. var padding = model.get('padding');
  21919. return padding != null ? padding // We give slightly different to look pretty.
  21920. : renderMode === 'richText' ? [8, 10] : 10;
  21921. }
  21922. /**
  21923. * The major feature is generate styles for `renderMode: 'richText'`.
  21924. * But it also serves `renderMode: 'html'` to provide
  21925. * "renderMode-independent" API.
  21926. */
  21927. var TooltipMarkupStyleCreator =
  21928. /** @class */
  21929. function () {
  21930. function TooltipMarkupStyleCreator() {
  21931. this.richTextStyles = {}; // Notice that "generate a style name" usually happens repeatedly when mouse is moving and
  21932. // a tooltip is displayed. So we put the `_nextStyleNameId` as a member of each creator
  21933. // rather than static shared by all creators (which will cause it increase to fast).
  21934. this._nextStyleNameId = getRandomIdBase();
  21935. }
  21936. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  21937. return '__EC_aUTo_' + this._nextStyleNameId++;
  21938. };
  21939. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  21940. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  21941. var marker = getTooltipMarker({
  21942. color: colorStr,
  21943. type: markerType,
  21944. renderMode: renderMode,
  21945. markerId: markerId
  21946. });
  21947. if (isString(marker)) {
  21948. return marker;
  21949. } else {
  21950. if ("development" !== 'production') {
  21951. assert(markerId);
  21952. }
  21953. this.richTextStyles[markerId] = marker.style;
  21954. return marker.content;
  21955. }
  21956. };
  21957. /**
  21958. * @usage
  21959. * ```ts
  21960. * const styledText = markupStyleCreator.wrapRichTextStyle([
  21961. * // The styles will be auto merged.
  21962. * {
  21963. * fontSize: 12,
  21964. * color: 'blue'
  21965. * },
  21966. * {
  21967. * padding: 20
  21968. * }
  21969. * ]);
  21970. * ```
  21971. */
  21972. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  21973. var finalStl = {};
  21974. if (isArray(styles)) {
  21975. each(styles, function (stl) {
  21976. return extend(finalStl, stl);
  21977. });
  21978. } else {
  21979. extend(finalStl, styles);
  21980. }
  21981. var styleName = this._generateStyleName();
  21982. this.richTextStyles[styleName] = finalStl;
  21983. return "{" + styleName + "|" + text + "}";
  21984. };
  21985. return TooltipMarkupStyleCreator;
  21986. }();
  21987. function defaultSeriesFormatTooltip(opt) {
  21988. var series = opt.series;
  21989. var dataIndex = opt.dataIndex;
  21990. var multipleSeries = opt.multipleSeries;
  21991. var data = series.getData();
  21992. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  21993. var tooltipDimLen = tooltipDims.length;
  21994. var value = series.getRawValue(dataIndex);
  21995. var isValueArr = isArray(value);
  21996. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  21997. var inlineValue;
  21998. var inlineValueType;
  21999. var subBlocks;
  22000. var sortParam;
  22001. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  22002. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  22003. inlineValue = formatArrResult.inlineValues;
  22004. inlineValueType = formatArrResult.inlineValueTypes;
  22005. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  22006. sortParam = formatArrResult.inlineValues[0];
  22007. } else if (tooltipDimLen) {
  22008. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  22009. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  22010. inlineValueType = dimInfo.type;
  22011. } else {
  22012. sortParam = inlineValue = isValueArr ? value[0] : value;
  22013. } // Do not show generated series name. It might not be readable.
  22014. var seriesNameSpecified = isNameSpecified(series);
  22015. var seriesName = seriesNameSpecified && series.name || '';
  22016. var itemName = data.getName(dataIndex);
  22017. var inlineName = multipleSeries ? seriesName : itemName;
  22018. return createTooltipMarkup('section', {
  22019. header: seriesName,
  22020. // When series name is not specified, do not show a header line with only '-'.
  22021. // This case always happens in tooltip.trigger: 'item'.
  22022. noHeader: multipleSeries || !seriesNameSpecified,
  22023. sortParam: sortParam,
  22024. blocks: [createTooltipMarkup('nameValue', {
  22025. markerType: 'item',
  22026. markerColor: markerColor,
  22027. // Do not mix display seriesName and itemName in one tooltip,
  22028. // which might confuses users.
  22029. name: inlineName,
  22030. // name dimension might be auto assigned, where the name might
  22031. // be not readable. So we check trim here.
  22032. noName: !trim(inlineName),
  22033. value: inlineValue,
  22034. valueType: inlineValueType
  22035. })].concat(subBlocks || [])
  22036. });
  22037. }
  22038. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  22039. // check: category-no-encode-has-axis-data in dataset.html
  22040. var data = series.getData();
  22041. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  22042. var dimItem = data.getDimensionInfo(idx);
  22043. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  22044. }, false);
  22045. var inlineValues = [];
  22046. var inlineValueTypes = [];
  22047. var blocks = [];
  22048. tooltipDims.length ? each(tooltipDims, function (dim) {
  22049. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  22050. }) // By default, all dims is used on tooltip.
  22051. : each(value, setEachItem);
  22052. function setEachItem(val, dim) {
  22053. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  22054. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  22055. return;
  22056. }
  22057. if (isValueMultipleLine) {
  22058. blocks.push(createTooltipMarkup('nameValue', {
  22059. markerType: 'subItem',
  22060. markerColor: colorStr,
  22061. name: dimInfo.displayName,
  22062. value: val,
  22063. valueType: dimInfo.type
  22064. }));
  22065. } else {
  22066. inlineValues.push(val);
  22067. inlineValueTypes.push(dimInfo.type);
  22068. }
  22069. }
  22070. return {
  22071. inlineValues: inlineValues,
  22072. inlineValueTypes: inlineValueTypes,
  22073. blocks: blocks
  22074. };
  22075. }
  22076. var inner$1 = makeInner();
  22077. function getSelectionKey(data, dataIndex) {
  22078. return data.getName(dataIndex) || data.getId(dataIndex);
  22079. }
  22080. var SERIES_UNIVERSAL_TRANSITION_PROP = '__universalTransitionEnabled';
  22081. var SeriesModel =
  22082. /** @class */
  22083. function (_super) {
  22084. __extends(SeriesModel, _super);
  22085. function SeriesModel() {
  22086. // [Caution]: Because this class or desecendants can be used as `XXX.extend(subProto)`,
  22087. // the class members must not be initialized in constructor or declaration place.
  22088. // Otherwise there is bad case:
  22089. // class A {xxx = 1;}
  22090. // enableClassExtend(A);
  22091. // class B extends A {}
  22092. // var C = B.extend({xxx: 5});
  22093. // var c = new C();
  22094. // console.log(c.xxx); // expect 5 but always 1.
  22095. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  22096. // Props about data selection
  22097. // ---------------------------------------
  22098. _this._selectedDataIndicesMap = {};
  22099. return _this;
  22100. }
  22101. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  22102. this.seriesIndex = this.componentIndex;
  22103. this.dataTask = createTask({
  22104. count: dataTaskCount,
  22105. reset: dataTaskReset
  22106. });
  22107. this.dataTask.context = {
  22108. model: this
  22109. };
  22110. this.mergeDefaultAndTheme(option, ecModel);
  22111. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  22112. sourceManager.prepareSource();
  22113. var data = this.getInitialData(option, ecModel);
  22114. wrapData(data, this);
  22115. this.dataTask.context.data = data;
  22116. if ("development" !== 'production') {
  22117. assert(data, 'getInitialData returned invalid data.');
  22118. }
  22119. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  22120. // dataBeforeProcessed by cloneShallow), cloneShallow will
  22121. // cause data.graph.data !== data when using
  22122. // module:echarts/data/Graph or module:echarts/data/Tree.
  22123. // See module:echarts/data/helper/linkSeriesData
  22124. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  22125. // init or merge stage, because the data can be restored. So we do not `restoreData`
  22126. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  22127. // Call `seriesModel.getRawData()` instead.
  22128. // this.restoreData();
  22129. autoSeriesName(this);
  22130. this._initSelectedMapFromData(data);
  22131. };
  22132. /**
  22133. * Util for merge default and theme to option
  22134. */
  22135. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  22136. var layoutMode = fetchLayoutMode(this);
  22137. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  22138. // But if name duplicate between series subType
  22139. // (for example: parallel) add component mainType,
  22140. // add suffix 'Series'.
  22141. var themeSubType = this.subType;
  22142. if (ComponentModel.hasClass(themeSubType)) {
  22143. themeSubType += 'Series';
  22144. }
  22145. merge(option, ecModel.getTheme().get(this.subType));
  22146. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  22147. defaultEmphasis(option, 'label', ['show']);
  22148. this.fillDataTextStyle(option.data);
  22149. if (layoutMode) {
  22150. mergeLayoutParam(option, inputPositionParams, layoutMode);
  22151. }
  22152. };
  22153. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  22154. // this.settingTask.dirty();
  22155. newSeriesOption = merge(this.option, newSeriesOption, true);
  22156. this.fillDataTextStyle(newSeriesOption.data);
  22157. var layoutMode = fetchLayoutMode(this);
  22158. if (layoutMode) {
  22159. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  22160. }
  22161. var sourceManager = inner$1(this).sourceManager;
  22162. sourceManager.dirty();
  22163. sourceManager.prepareSource();
  22164. var data = this.getInitialData(newSeriesOption, ecModel);
  22165. wrapData(data, this);
  22166. this.dataTask.dirty();
  22167. this.dataTask.context.data = data;
  22168. inner$1(this).dataBeforeProcessed = data;
  22169. autoSeriesName(this);
  22170. this._initSelectedMapFromData(data);
  22171. };
  22172. SeriesModel.prototype.fillDataTextStyle = function (data) {
  22173. // Default data label emphasis `show`
  22174. // FIXME Tree structure data ?
  22175. // FIXME Performance ?
  22176. if (data && !isTypedArray(data)) {
  22177. var props = ['show'];
  22178. for (var i = 0; i < data.length; i++) {
  22179. if (data[i] && data[i].label) {
  22180. defaultEmphasis(data[i], 'label', props);
  22181. }
  22182. }
  22183. }
  22184. };
  22185. /**
  22186. * Init a data structure from data related option in series
  22187. * Must be overridden.
  22188. */
  22189. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  22190. return;
  22191. };
  22192. /**
  22193. * Append data to list
  22194. */
  22195. SeriesModel.prototype.appendData = function (params) {
  22196. // FIXME ???
  22197. // (1) If data from dataset, forbidden append.
  22198. // (2) support append data of dataset.
  22199. var data = this.getRawData();
  22200. data.appendData(params.data);
  22201. };
  22202. /**
  22203. * Consider some method like `filter`, `map` need make new data,
  22204. * We should make sure that `seriesModel.getData()` get correct
  22205. * data in the stream procedure. So we fetch data from upstream
  22206. * each time `task.perform` called.
  22207. */
  22208. SeriesModel.prototype.getData = function (dataType) {
  22209. var task = getCurrentTask(this);
  22210. if (task) {
  22211. var data = task.context.data;
  22212. return dataType == null ? data : data.getLinkedData(dataType);
  22213. } else {
  22214. // When series is not alive (that may happen when click toolbox
  22215. // restore or setOption with not merge mode), series data may
  22216. // be still need to judge animation or something when graphic
  22217. // elements want to know whether fade out.
  22218. return inner$1(this).data;
  22219. }
  22220. };
  22221. SeriesModel.prototype.getAllData = function () {
  22222. var mainData = this.getData();
  22223. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  22224. data: mainData
  22225. }];
  22226. };
  22227. SeriesModel.prototype.setData = function (data) {
  22228. var task = getCurrentTask(this);
  22229. if (task) {
  22230. var context = task.context; // Consider case: filter, data sample.
  22231. // FIXME:TS never used, so comment it
  22232. // if (context.data !== data && task.modifyOutputEnd) {
  22233. // task.setOutputEnd(data.count());
  22234. // }
  22235. context.outputData = data; // Caution: setData should update context.data,
  22236. // Because getData may be called multiply in a
  22237. // single stage and expect to get the data just
  22238. // set. (For example, AxisProxy, x y both call
  22239. // getData and setDate sequentially).
  22240. // So the context.data should be fetched from
  22241. // upstream each time when a stage starts to be
  22242. // performed.
  22243. if (task !== this.dataTask) {
  22244. context.data = data;
  22245. }
  22246. }
  22247. inner$1(this).data = data;
  22248. };
  22249. SeriesModel.prototype.getEncode = function () {
  22250. var encode = this.get('encode', true);
  22251. if (encode) {
  22252. return createHashMap(encode);
  22253. }
  22254. };
  22255. SeriesModel.prototype.getSourceManager = function () {
  22256. return inner$1(this).sourceManager;
  22257. };
  22258. SeriesModel.prototype.getSource = function () {
  22259. return this.getSourceManager().getSource();
  22260. };
  22261. /**
  22262. * Get data before processed
  22263. */
  22264. SeriesModel.prototype.getRawData = function () {
  22265. return inner$1(this).dataBeforeProcessed;
  22266. };
  22267. SeriesModel.prototype.getColorBy = function () {
  22268. var colorBy = this.get('colorBy');
  22269. return colorBy || 'series';
  22270. };
  22271. SeriesModel.prototype.isColorBySeries = function () {
  22272. return this.getColorBy() === 'series';
  22273. };
  22274. /**
  22275. * Get base axis if has coordinate system and has axis.
  22276. * By default use coordSys.getBaseAxis();
  22277. * Can be overridden for some chart.
  22278. * @return {type} description
  22279. */
  22280. SeriesModel.prototype.getBaseAxis = function () {
  22281. var coordSys = this.coordinateSystem; // @ts-ignore
  22282. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  22283. };
  22284. /**
  22285. * Default tooltip formatter
  22286. *
  22287. * @param dataIndex
  22288. * @param multipleSeries
  22289. * @param dataType
  22290. * @param renderMode valid values: 'html'(by default) and 'richText'.
  22291. * 'html' is used for rendering tooltip in extra DOM form, and the result
  22292. * string is used as DOM HTML content.
  22293. * 'richText' is used for rendering tooltip in rich text form, for those where
  22294. * DOM operation is not supported.
  22295. * @return formatted tooltip with `html` and `markers`
  22296. * Notice: The override method can also return string
  22297. */
  22298. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  22299. return defaultSeriesFormatTooltip({
  22300. series: this,
  22301. dataIndex: dataIndex,
  22302. multipleSeries: multipleSeries
  22303. });
  22304. };
  22305. SeriesModel.prototype.isAnimationEnabled = function () {
  22306. var ecModel = this.ecModel; // Disable animation if using echarts in node but not give ssr flag.
  22307. // In ssr mode, renderToString will generate svg with css animation.
  22308. if (env.node && !(ecModel && ecModel.ssr)) {
  22309. return false;
  22310. }
  22311. var animationEnabled = this.getShallow('animation');
  22312. if (animationEnabled) {
  22313. if (this.getData().count() > this.getShallow('animationThreshold')) {
  22314. animationEnabled = false;
  22315. }
  22316. }
  22317. return !!animationEnabled;
  22318. };
  22319. SeriesModel.prototype.restoreData = function () {
  22320. this.dataTask.dirty();
  22321. };
  22322. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  22323. var ecModel = this.ecModel; // PENDING
  22324. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  22325. if (!color) {
  22326. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  22327. }
  22328. return color;
  22329. };
  22330. /**
  22331. * Use `data.mapDimensionsAll(coordDim)` instead.
  22332. * @deprecated
  22333. */
  22334. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  22335. return this.getRawData().mapDimensionsAll(coordDim);
  22336. };
  22337. /**
  22338. * Get progressive rendering count each step
  22339. */
  22340. SeriesModel.prototype.getProgressive = function () {
  22341. return this.get('progressive');
  22342. };
  22343. /**
  22344. * Get progressive rendering count each step
  22345. */
  22346. SeriesModel.prototype.getProgressiveThreshold = function () {
  22347. return this.get('progressiveThreshold');
  22348. }; // PENGING If selectedMode is null ?
  22349. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  22350. this._innerSelect(this.getData(dataType), innerDataIndices);
  22351. };
  22352. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  22353. var selectedMap = this.option.selectedMap;
  22354. if (!selectedMap) {
  22355. return;
  22356. }
  22357. var selectedMode = this.option.selectedMode;
  22358. var data = this.getData(dataType);
  22359. if (selectedMode === 'series' || selectedMap === 'all') {
  22360. this.option.selectedMap = {};
  22361. this._selectedDataIndicesMap = {};
  22362. return;
  22363. }
  22364. for (var i = 0; i < innerDataIndices.length; i++) {
  22365. var dataIndex = innerDataIndices[i];
  22366. var nameOrId = getSelectionKey(data, dataIndex);
  22367. selectedMap[nameOrId] = false;
  22368. this._selectedDataIndicesMap[nameOrId] = -1;
  22369. }
  22370. };
  22371. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  22372. var tmpArr = [];
  22373. for (var i = 0; i < innerDataIndices.length; i++) {
  22374. tmpArr[0] = innerDataIndices[i];
  22375. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  22376. }
  22377. };
  22378. SeriesModel.prototype.getSelectedDataIndices = function () {
  22379. if (this.option.selectedMap === 'all') {
  22380. return [].slice.call(this.getData().getIndices());
  22381. }
  22382. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  22383. var nameOrIds = keys(selectedDataIndicesMap);
  22384. var dataIndices = [];
  22385. for (var i = 0; i < nameOrIds.length; i++) {
  22386. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  22387. if (dataIndex >= 0) {
  22388. dataIndices.push(dataIndex);
  22389. }
  22390. }
  22391. return dataIndices;
  22392. };
  22393. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  22394. var selectedMap = this.option.selectedMap;
  22395. if (!selectedMap) {
  22396. return false;
  22397. }
  22398. var data = this.getData(dataType);
  22399. return (selectedMap === 'all' || selectedMap[getSelectionKey(data, dataIndex)]) && !data.getItemModel(dataIndex).get(['select', 'disabled']);
  22400. };
  22401. SeriesModel.prototype.isUniversalTransitionEnabled = function () {
  22402. if (this[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  22403. return true;
  22404. }
  22405. var universalTransitionOpt = this.option.universalTransition; // Quick reject
  22406. if (!universalTransitionOpt) {
  22407. return false;
  22408. }
  22409. if (universalTransitionOpt === true) {
  22410. return true;
  22411. } // Can be simply 'universalTransition: true'
  22412. return universalTransitionOpt && universalTransitionOpt.enabled;
  22413. };
  22414. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  22415. var _a, _b;
  22416. var option = this.option;
  22417. var selectedMode = option.selectedMode;
  22418. var len = innerDataIndices.length;
  22419. if (!selectedMode || !len) {
  22420. return;
  22421. }
  22422. if (selectedMode === 'series') {
  22423. option.selectedMap = 'all';
  22424. } else if (selectedMode === 'multiple') {
  22425. if (!isObject(option.selectedMap)) {
  22426. option.selectedMap = {};
  22427. }
  22428. var selectedMap = option.selectedMap;
  22429. for (var i = 0; i < len; i++) {
  22430. var dataIndex = innerDataIndices[i]; // TODO different types of data share same object.
  22431. var nameOrId = getSelectionKey(data, dataIndex);
  22432. selectedMap[nameOrId] = true;
  22433. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  22434. }
  22435. } else if (selectedMode === 'single' || selectedMode === true) {
  22436. var lastDataIndex = innerDataIndices[len - 1];
  22437. var nameOrId = getSelectionKey(data, lastDataIndex);
  22438. option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  22439. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  22440. }
  22441. };
  22442. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  22443. // Ignore select info in data if selectedMap exists.
  22444. // NOTE It's only for legacy usage. edge data is not supported.
  22445. if (this.option.selectedMap) {
  22446. return;
  22447. }
  22448. var dataIndices = [];
  22449. if (data.hasItemOption) {
  22450. data.each(function (idx) {
  22451. var rawItem = data.getRawDataItem(idx);
  22452. if (rawItem && rawItem.selected) {
  22453. dataIndices.push(idx);
  22454. }
  22455. });
  22456. }
  22457. if (dataIndices.length > 0) {
  22458. this._innerSelect(data, dataIndices);
  22459. }
  22460. }; // /**
  22461. // * @see {module:echarts/stream/Scheduler}
  22462. // */
  22463. // abstract pipeTask: null
  22464. SeriesModel.registerClass = function (clz) {
  22465. return ComponentModel.registerClass(clz);
  22466. };
  22467. SeriesModel.protoInitialize = function () {
  22468. var proto = SeriesModel.prototype;
  22469. proto.type = 'series.__base__';
  22470. proto.seriesIndex = 0;
  22471. proto.ignoreStyleOnData = false;
  22472. proto.hasSymbolVisual = false;
  22473. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  22474. proto.visualStyleAccessPath = 'itemStyle';
  22475. proto.visualDrawType = 'fill';
  22476. }();
  22477. return SeriesModel;
  22478. }(ComponentModel);
  22479. mixin(SeriesModel, DataFormatMixin);
  22480. mixin(SeriesModel, PaletteMixin);
  22481. mountExtend(SeriesModel, ComponentModel);
  22482. /**
  22483. * MUST be called after `prepareSource` called
  22484. * Here we need to make auto series, especially for auto legend. But we
  22485. * do not modify series.name in option to avoid side effects.
  22486. */
  22487. function autoSeriesName(seriesModel) {
  22488. // User specified name has higher priority, otherwise it may cause
  22489. // series can not be queried unexpectedly.
  22490. var name = seriesModel.name;
  22491. if (!isNameSpecified(seriesModel)) {
  22492. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  22493. }
  22494. }
  22495. function getSeriesAutoName(seriesModel) {
  22496. var data = seriesModel.getRawData();
  22497. var dataDims = data.mapDimensionsAll('seriesName');
  22498. var nameArr = [];
  22499. each(dataDims, function (dataDim) {
  22500. var dimInfo = data.getDimensionInfo(dataDim);
  22501. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  22502. });
  22503. return nameArr.join(' ');
  22504. }
  22505. function dataTaskCount(context) {
  22506. return context.model.getRawData().count();
  22507. }
  22508. function dataTaskReset(context) {
  22509. var seriesModel = context.model;
  22510. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  22511. return dataTaskProgress;
  22512. }
  22513. function dataTaskProgress(param, context) {
  22514. // Avoid repeat cloneShallow when data just created in reset.
  22515. if (context.outputData && param.end > context.outputData.count()) {
  22516. context.model.getRawData().cloneShallow(context.outputData);
  22517. }
  22518. } // TODO refactor
  22519. function wrapData(data, seriesModel) {
  22520. each(concatArray(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  22521. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  22522. });
  22523. }
  22524. function onDataChange(seriesModel, newList) {
  22525. var task = getCurrentTask(seriesModel);
  22526. if (task) {
  22527. // Consider case: filter, selectRange
  22528. task.setOutputEnd((newList || this).count());
  22529. }
  22530. return newList;
  22531. }
  22532. function getCurrentTask(seriesModel) {
  22533. var scheduler = (seriesModel.ecModel || {}).scheduler;
  22534. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  22535. if (pipeline) {
  22536. // When pipline finished, the currrentTask keep the last
  22537. // task (renderTask).
  22538. var task = pipeline.currentTask;
  22539. if (task) {
  22540. var agentStubMap = task.agentStubMap;
  22541. if (agentStubMap) {
  22542. task = agentStubMap.get(seriesModel.uid);
  22543. }
  22544. }
  22545. return task;
  22546. }
  22547. }
  22548. var ComponentView =
  22549. /** @class */
  22550. function () {
  22551. function ComponentView() {
  22552. this.group = new Group();
  22553. this.uid = getUID('viewComponent');
  22554. }
  22555. ComponentView.prototype.init = function (ecModel, api) {};
  22556. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  22557. ComponentView.prototype.dispose = function (ecModel, api) {};
  22558. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  22559. };
  22560. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  22561. };
  22562. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  22563. };
  22564. /**
  22565. * Hook for toggle blur target series.
  22566. * Can be used in marker for blur or leave blur the markers
  22567. */
  22568. ComponentView.prototype.toggleBlurSeries = function (seriesModels, isBlur, ecModel) {// Do nothing;
  22569. };
  22570. /**
  22571. * Traverse the new rendered elements.
  22572. *
  22573. * It will traverse the new added element in progressive rendering.
  22574. * And traverse all in normal rendering.
  22575. */
  22576. ComponentView.prototype.eachRendered = function (cb) {
  22577. var group = this.group;
  22578. if (group) {
  22579. group.traverse(cb);
  22580. }
  22581. };
  22582. return ComponentView;
  22583. }();
  22584. enableClassExtend(ComponentView);
  22585. enableClassManagement(ComponentView);
  22586. /**
  22587. * @return {string} If large mode changed, return string 'reset';
  22588. */
  22589. function createRenderPlanner() {
  22590. var inner = makeInner();
  22591. return function (seriesModel) {
  22592. var fields = inner(seriesModel);
  22593. var pipelineContext = seriesModel.pipelineContext;
  22594. var originalLarge = !!fields.large;
  22595. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  22596. // exists. See #11611 . Probably we need to modify this structure, see the comment
  22597. // on `performRawSeries` in `Schedular.js`.
  22598. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  22599. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  22600. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  22601. };
  22602. }
  22603. var inner$2 = makeInner();
  22604. var renderPlanner = createRenderPlanner();
  22605. var ChartView =
  22606. /** @class */
  22607. function () {
  22608. function ChartView() {
  22609. this.group = new Group();
  22610. this.uid = getUID('viewChart');
  22611. this.renderTask = createTask({
  22612. plan: renderTaskPlan,
  22613. reset: renderTaskReset
  22614. });
  22615. this.renderTask.context = {
  22616. view: this
  22617. };
  22618. }
  22619. ChartView.prototype.init = function (ecModel, api) {};
  22620. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {
  22621. if ("development" !== 'production') {
  22622. throw new Error('render method must been implemented');
  22623. }
  22624. };
  22625. /**
  22626. * Highlight series or specified data item.
  22627. */
  22628. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  22629. var data = seriesModel.getData(payload && payload.dataType);
  22630. if (!data) {
  22631. if ("development" !== 'production') {
  22632. error("Unknown dataType " + payload.dataType);
  22633. }
  22634. return;
  22635. }
  22636. toggleHighlight(data, payload, 'emphasis');
  22637. };
  22638. /**
  22639. * Downplay series or specified data item.
  22640. */
  22641. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  22642. var data = seriesModel.getData(payload && payload.dataType);
  22643. if (!data) {
  22644. if ("development" !== 'production') {
  22645. error("Unknown dataType " + payload.dataType);
  22646. }
  22647. return;
  22648. }
  22649. toggleHighlight(data, payload, 'normal');
  22650. };
  22651. /**
  22652. * Remove self.
  22653. */
  22654. ChartView.prototype.remove = function (ecModel, api) {
  22655. this.group.removeAll();
  22656. };
  22657. /**
  22658. * Dispose self.
  22659. */
  22660. ChartView.prototype.dispose = function (ecModel, api) {};
  22661. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  22662. this.render(seriesModel, ecModel, api, payload);
  22663. }; // FIXME never used?
  22664. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  22665. this.render(seriesModel, ecModel, api, payload);
  22666. }; // FIXME never used?
  22667. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  22668. this.render(seriesModel, ecModel, api, payload);
  22669. };
  22670. /**
  22671. * Traverse the new rendered elements.
  22672. *
  22673. * It will traverse the new added element in progressive rendering.
  22674. * And traverse all in normal rendering.
  22675. */
  22676. ChartView.prototype.eachRendered = function (cb) {
  22677. traverseElements(this.group, cb);
  22678. };
  22679. ChartView.markUpdateMethod = function (payload, methodName) {
  22680. inner$2(payload).updateMethod = methodName;
  22681. };
  22682. ChartView.protoInitialize = function () {
  22683. var proto = ChartView.prototype;
  22684. proto.type = 'chart';
  22685. }();
  22686. return ChartView;
  22687. }();
  22688. /**
  22689. * Set state of single element
  22690. */
  22691. function elSetState(el, state, highlightDigit) {
  22692. if (el && isHighDownDispatcher(el)) {
  22693. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  22694. }
  22695. }
  22696. function toggleHighlight(data, payload, state) {
  22697. var dataIndex = queryDataIndex(data, payload);
  22698. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  22699. if (dataIndex != null) {
  22700. each(normalizeToArray(dataIndex), function (dataIdx) {
  22701. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  22702. });
  22703. } else {
  22704. data.eachItemGraphicEl(function (el) {
  22705. elSetState(el, state, highlightDigit);
  22706. });
  22707. }
  22708. }
  22709. enableClassExtend(ChartView, ['dispose']);
  22710. enableClassManagement(ChartView);
  22711. function renderTaskPlan(context) {
  22712. return renderPlanner(context.model);
  22713. }
  22714. function renderTaskReset(context) {
  22715. var seriesModel = context.model;
  22716. var ecModel = context.ecModel;
  22717. var api = context.api;
  22718. var payload = context.payload; // FIXME: remove updateView updateVisual
  22719. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  22720. var view = context.view;
  22721. var updateMethod = payload && inner$2(payload).updateMethod;
  22722. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  22723. // is less than progressive threshold.
  22724. : 'render';
  22725. if (methodName !== 'render') {
  22726. view[methodName](seriesModel, ecModel, api, payload);
  22727. }
  22728. return progressMethodMap[methodName];
  22729. }
  22730. var progressMethodMap = {
  22731. incrementalPrepareRender: {
  22732. progress: function (params, context) {
  22733. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  22734. }
  22735. },
  22736. render: {
  22737. // Put view.render in `progress` to support appendData. But in this case
  22738. // view.render should not be called in reset, otherwise it will be called
  22739. // twise. Use `forceFirstProgress` to make sure that view.render is called
  22740. // in any cases.
  22741. forceFirstProgress: true,
  22742. progress: function (params, context) {
  22743. context.view.render(context.model, context.ecModel, context.api, context.payload);
  22744. }
  22745. }
  22746. };
  22747. /*
  22748. * Licensed to the Apache Software Foundation (ASF) under one
  22749. * or more contributor license agreements. See the NOTICE file
  22750. * distributed with this work for additional information
  22751. * regarding copyright ownership. The ASF licenses this file
  22752. * to you under the Apache License, Version 2.0 (the
  22753. * "License"); you may not use this file except in compliance
  22754. * with the License. You may obtain a copy of the License at
  22755. *
  22756. * http://www.apache.org/licenses/LICENSE-2.0
  22757. *
  22758. * Unless required by applicable law or agreed to in writing,
  22759. * software distributed under the License is distributed on an
  22760. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22761. * KIND, either express or implied. See the License for the
  22762. * specific language governing permissions and limitations
  22763. * under the License.
  22764. */
  22765. /**
  22766. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22767. */
  22768. /*
  22769. * Licensed to the Apache Software Foundation (ASF) under one
  22770. * or more contributor license agreements. See the NOTICE file
  22771. * distributed with this work for additional information
  22772. * regarding copyright ownership. The ASF licenses this file
  22773. * to you under the Apache License, Version 2.0 (the
  22774. * "License"); you may not use this file except in compliance
  22775. * with the License. You may obtain a copy of the License at
  22776. *
  22777. * http://www.apache.org/licenses/LICENSE-2.0
  22778. *
  22779. * Unless required by applicable law or agreed to in writing,
  22780. * software distributed under the License is distributed on an
  22781. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22782. * KIND, either express or implied. See the License for the
  22783. * specific language governing permissions and limitations
  22784. * under the License.
  22785. */
  22786. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  22787. var RATE = '\0__throttleRate';
  22788. var THROTTLE_TYPE = '\0__throttleType';
  22789. /**
  22790. * @public
  22791. * @param {(Function)} fn
  22792. * @param {number} [delay=0] Unit: ms.
  22793. * @param {boolean} [debounce=false]
  22794. * true: If call interval less than `delay`, only the last call works.
  22795. * false: If call interval less than `delay, call works on fixed rate.
  22796. * @return {(Function)} throttled fn.
  22797. */
  22798. function throttle(fn, delay, debounce) {
  22799. var currCall;
  22800. var lastCall = 0;
  22801. var lastExec = 0;
  22802. var timer = null;
  22803. var diff;
  22804. var scope;
  22805. var args;
  22806. var debounceNextCall;
  22807. delay = delay || 0;
  22808. function exec() {
  22809. lastExec = new Date().getTime();
  22810. timer = null;
  22811. fn.apply(scope, args || []);
  22812. }
  22813. var cb = function () {
  22814. var cbArgs = [];
  22815. for (var _i = 0; _i < arguments.length; _i++) {
  22816. cbArgs[_i] = arguments[_i];
  22817. }
  22818. currCall = new Date().getTime();
  22819. scope = this;
  22820. args = cbArgs;
  22821. var thisDelay = debounceNextCall || delay;
  22822. var thisDebounce = debounceNextCall || debounce;
  22823. debounceNextCall = null;
  22824. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  22825. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  22826. // than a new call of `cb`, that is, preserving the command order. Consider
  22827. // calculating "scale rate" when roaming as an example. When a call of `cb`
  22828. // happens, either the `exec` is called dierectly, or the call is delayed.
  22829. // But the delayed call should never be later than next call of `cb`. Under
  22830. // this assurance, we can simply update view state each time `dispatchAction`
  22831. // triggered by user roaming, but not need to add extra code to avoid the
  22832. // state being "rolled-back".
  22833. if (thisDebounce) {
  22834. timer = setTimeout(exec, thisDelay);
  22835. } else {
  22836. if (diff >= 0) {
  22837. exec();
  22838. } else {
  22839. timer = setTimeout(exec, -diff);
  22840. }
  22841. }
  22842. lastCall = currCall;
  22843. };
  22844. /**
  22845. * Clear throttle.
  22846. * @public
  22847. */
  22848. cb.clear = function () {
  22849. if (timer) {
  22850. clearTimeout(timer);
  22851. timer = null;
  22852. }
  22853. };
  22854. /**
  22855. * Enable debounce once.
  22856. */
  22857. cb.debounceNextCall = function (debounceDelay) {
  22858. debounceNextCall = debounceDelay;
  22859. };
  22860. return cb;
  22861. }
  22862. /**
  22863. * Create throttle method or update throttle rate.
  22864. *
  22865. * @example
  22866. * ComponentView.prototype.render = function () {
  22867. * ...
  22868. * throttle.createOrUpdate(
  22869. * this,
  22870. * '_dispatchAction',
  22871. * this.model.get('throttle'),
  22872. * 'fixRate'
  22873. * );
  22874. * };
  22875. * ComponentView.prototype.remove = function () {
  22876. * throttle.clear(this, '_dispatchAction');
  22877. * };
  22878. * ComponentView.prototype.dispose = function () {
  22879. * throttle.clear(this, '_dispatchAction');
  22880. * };
  22881. *
  22882. */
  22883. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  22884. var fn = obj[fnAttr];
  22885. if (!fn) {
  22886. return;
  22887. }
  22888. var originFn = fn[ORIGIN_METHOD] || fn;
  22889. var lastThrottleType = fn[THROTTLE_TYPE];
  22890. var lastRate = fn[RATE];
  22891. if (lastRate !== rate || lastThrottleType !== throttleType) {
  22892. if (rate == null || !throttleType) {
  22893. return obj[fnAttr] = originFn;
  22894. }
  22895. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  22896. fn[ORIGIN_METHOD] = originFn;
  22897. fn[THROTTLE_TYPE] = throttleType;
  22898. fn[RATE] = rate;
  22899. }
  22900. return fn;
  22901. }
  22902. /**
  22903. * Clear throttle. Example see throttle.createOrUpdate.
  22904. */
  22905. function clear(obj, fnAttr) {
  22906. var fn = obj[fnAttr];
  22907. if (fn && fn[ORIGIN_METHOD]) {
  22908. // Clear throttle
  22909. fn.clear && fn.clear();
  22910. obj[fnAttr] = fn[ORIGIN_METHOD];
  22911. }
  22912. }
  22913. var inner$3 = makeInner();
  22914. var defaultStyleMappers = {
  22915. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  22916. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  22917. };
  22918. var defaultColorKey = {
  22919. lineStyle: 'stroke',
  22920. itemStyle: 'fill'
  22921. };
  22922. function getStyleMapper(seriesModel, stylePath) {
  22923. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  22924. if (!styleMapper) {
  22925. console.warn("Unknown style type '" + stylePath + "'.");
  22926. return defaultStyleMappers.itemStyle;
  22927. }
  22928. return styleMapper;
  22929. }
  22930. function getDefaultColorKey(seriesModel, stylePath) {
  22931. // return defaultColorKey[stylePath] ||
  22932. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  22933. if (!colorKey) {
  22934. console.warn("Unknown style type '" + stylePath + "'.");
  22935. return 'fill';
  22936. }
  22937. return colorKey;
  22938. }
  22939. var seriesStyleTask = {
  22940. createOnAllSeries: true,
  22941. performRawSeries: true,
  22942. reset: function (seriesModel, ecModel) {
  22943. var data = seriesModel.getData();
  22944. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22945. var styleModel = seriesModel.getModel(stylePath);
  22946. var getStyle = getStyleMapper(seriesModel, stylePath);
  22947. var globalStyle = getStyle(styleModel);
  22948. var decalOption = styleModel.getShallow('decal');
  22949. if (decalOption) {
  22950. data.setVisual('decal', decalOption);
  22951. decalOption.dirty = true;
  22952. } // TODO
  22953. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  22954. var color = globalStyle[colorKey]; // TODO style callback
  22955. var colorCallback = isFunction(color) ? color : null;
  22956. var hasAutoColor = globalStyle.fill === 'auto' || globalStyle.stroke === 'auto'; // Get from color palette by default.
  22957. if (!globalStyle[colorKey] || colorCallback || hasAutoColor) {
  22958. // Note: If some series has color specified (e.g., by itemStyle.color), we DO NOT
  22959. // make it effect palette. Because some scenarios users need to make some series
  22960. // transparent or as background, which should better not effect the palette.
  22961. var colorPalette = seriesModel.getColorFromPalette( // TODO series count changed.
  22962. seriesModel.name, null, ecModel.getSeriesCount());
  22963. if (!globalStyle[colorKey]) {
  22964. globalStyle[colorKey] = colorPalette;
  22965. data.setVisual('colorFromPalette', true);
  22966. }
  22967. globalStyle.fill = globalStyle.fill === 'auto' || isFunction(globalStyle.fill) ? colorPalette : globalStyle.fill;
  22968. globalStyle.stroke = globalStyle.stroke === 'auto' || isFunction(globalStyle.stroke) ? colorPalette : globalStyle.stroke;
  22969. }
  22970. data.setVisual('style', globalStyle);
  22971. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  22972. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  22973. data.setVisual('colorFromPalette', false);
  22974. return {
  22975. dataEach: function (data, idx) {
  22976. var dataParams = seriesModel.getDataParams(idx);
  22977. var itemStyle = extend({}, globalStyle);
  22978. itemStyle[colorKey] = colorCallback(dataParams);
  22979. data.setItemVisual(idx, 'style', itemStyle);
  22980. }
  22981. };
  22982. }
  22983. }
  22984. };
  22985. var sharedModel = new Model();
  22986. var dataStyleTask = {
  22987. createOnAllSeries: true,
  22988. performRawSeries: true,
  22989. reset: function (seriesModel, ecModel) {
  22990. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  22991. return;
  22992. }
  22993. var data = seriesModel.getData();
  22994. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  22995. var getStyle = getStyleMapper(seriesModel, stylePath);
  22996. var colorKey = data.getVisual('drawType');
  22997. return {
  22998. dataEach: data.hasItemOption ? function (data, idx) {
  22999. // Not use getItemModel for performance considuration
  23000. var rawItem = data.getRawDataItem(idx);
  23001. if (rawItem && rawItem[stylePath]) {
  23002. sharedModel.option = rawItem[stylePath];
  23003. var style = getStyle(sharedModel);
  23004. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  23005. extend(existsStyle, style);
  23006. if (sharedModel.option.decal) {
  23007. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  23008. sharedModel.option.decal.dirty = true;
  23009. }
  23010. if (colorKey in style) {
  23011. data.setItemVisual(idx, 'colorFromPalette', false);
  23012. }
  23013. }
  23014. } : null
  23015. };
  23016. }
  23017. }; // Pick color from palette for the data which has not been set with color yet.
  23018. // Note: do not support stream rendering. No such cases yet.
  23019. var dataColorPaletteTask = {
  23020. performRawSeries: true,
  23021. overallReset: function (ecModel) {
  23022. // Each type of series uses one scope.
  23023. // Pie and funnel are using different scopes.
  23024. var paletteScopeGroupByType = createHashMap();
  23025. ecModel.eachSeries(function (seriesModel) {
  23026. var colorBy = seriesModel.getColorBy();
  23027. if (seriesModel.isColorBySeries()) {
  23028. return;
  23029. }
  23030. var key = seriesModel.type + '-' + colorBy;
  23031. var colorScope = paletteScopeGroupByType.get(key);
  23032. if (!colorScope) {
  23033. colorScope = {};
  23034. paletteScopeGroupByType.set(key, colorScope);
  23035. }
  23036. inner$3(seriesModel).scope = colorScope;
  23037. });
  23038. ecModel.eachSeries(function (seriesModel) {
  23039. if (seriesModel.isColorBySeries() || ecModel.isSeriesFiltered(seriesModel)) {
  23040. return;
  23041. }
  23042. var dataAll = seriesModel.getRawData();
  23043. var idxMap = {};
  23044. var data = seriesModel.getData();
  23045. var colorScope = inner$3(seriesModel).scope;
  23046. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  23047. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  23048. data.each(function (idx) {
  23049. var rawIdx = data.getRawIndex(idx);
  23050. idxMap[rawIdx] = idx;
  23051. }); // Iterate on data before filtered. To make sure color from palette can be
  23052. // Consistent when toggling legend.
  23053. dataAll.each(function (rawIdx) {
  23054. var idx = idxMap[rawIdx];
  23055. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  23056. // also picked from color palette. So following situation is not in the case:
  23057. // 1. series.itemStyle.color is set
  23058. // 2. color is encoded by visualMap
  23059. if (fromPalette) {
  23060. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  23061. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  23062. var dataCount = dataAll.count();
  23063. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  23064. }
  23065. });
  23066. });
  23067. }
  23068. };
  23069. var PI$3 = Math.PI;
  23070. /**
  23071. * @param {module:echarts/ExtensionAPI} api
  23072. * @param {Object} [opts]
  23073. * @param {string} [opts.text]
  23074. * @param {string} [opts.color]
  23075. * @param {string} [opts.textColor]
  23076. * @return {module:zrender/Element}
  23077. */
  23078. function defaultLoading(api, opts) {
  23079. opts = opts || {};
  23080. defaults(opts, {
  23081. text: 'loading',
  23082. textColor: '#000',
  23083. fontSize: 12,
  23084. fontWeight: 'normal',
  23085. fontStyle: 'normal',
  23086. fontFamily: 'sans-serif',
  23087. maskColor: 'rgba(255, 255, 255, 0.8)',
  23088. showSpinner: true,
  23089. color: '#5470c6',
  23090. spinnerRadius: 10,
  23091. lineWidth: 5,
  23092. zlevel: 0
  23093. });
  23094. var group = new Group();
  23095. var mask = new Rect({
  23096. style: {
  23097. fill: opts.maskColor
  23098. },
  23099. zlevel: opts.zlevel,
  23100. z: 10000
  23101. });
  23102. group.add(mask);
  23103. var textContent = new ZRText({
  23104. style: {
  23105. text: opts.text,
  23106. fill: opts.textColor,
  23107. fontSize: opts.fontSize,
  23108. fontWeight: opts.fontWeight,
  23109. fontStyle: opts.fontStyle,
  23110. fontFamily: opts.fontFamily
  23111. },
  23112. zlevel: opts.zlevel,
  23113. z: 10001
  23114. });
  23115. var labelRect = new Rect({
  23116. style: {
  23117. fill: 'none'
  23118. },
  23119. textContent: textContent,
  23120. textConfig: {
  23121. position: 'right',
  23122. distance: 10
  23123. },
  23124. zlevel: opts.zlevel,
  23125. z: 10001
  23126. });
  23127. group.add(labelRect);
  23128. var arc;
  23129. if (opts.showSpinner) {
  23130. arc = new Arc({
  23131. shape: {
  23132. startAngle: -PI$3 / 2,
  23133. endAngle: -PI$3 / 2 + 0.1,
  23134. r: opts.spinnerRadius
  23135. },
  23136. style: {
  23137. stroke: opts.color,
  23138. lineCap: 'round',
  23139. lineWidth: opts.lineWidth
  23140. },
  23141. zlevel: opts.zlevel,
  23142. z: 10001
  23143. });
  23144. arc.animateShape(true).when(1000, {
  23145. endAngle: PI$3 * 3 / 2
  23146. }).start('circularInOut');
  23147. arc.animateShape(true).when(1000, {
  23148. startAngle: PI$3 * 3 / 2
  23149. }).delay(300).start('circularInOut');
  23150. group.add(arc);
  23151. } // Inject resize
  23152. group.resize = function () {
  23153. var textWidth = textContent.getBoundingRect().width;
  23154. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  23155. // textDistance needs to be calculated when both animation and text exist
  23156. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  23157. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  23158. + (textWidth ? 0 : r);
  23159. var cy = api.getHeight() / 2;
  23160. opts.showSpinner && arc.setShape({
  23161. cx: cx,
  23162. cy: cy
  23163. });
  23164. labelRect.setShape({
  23165. x: cx - r,
  23166. y: cy - r,
  23167. width: r * 2,
  23168. height: r * 2
  23169. });
  23170. mask.setShape({
  23171. x: 0,
  23172. y: 0,
  23173. width: api.getWidth(),
  23174. height: api.getHeight()
  23175. });
  23176. };
  23177. group.resize();
  23178. return group;
  23179. }
  23180. var Scheduler =
  23181. /** @class */
  23182. function () {
  23183. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  23184. // key: handlerUID
  23185. this._stageTaskMap = createHashMap();
  23186. this.ecInstance = ecInstance;
  23187. this.api = api; // Fix current processors in case that in some rear cases that
  23188. // processors might be registered after echarts instance created.
  23189. // Register processors incrementally for a echarts instance is
  23190. // not supported by this stream architecture.
  23191. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  23192. visualHandlers = this._visualHandlers = visualHandlers.slice();
  23193. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  23194. }
  23195. Scheduler.prototype.restoreData = function (ecModel, payload) {
  23196. // TODO: Only restore needed series and components, but not all components.
  23197. // Currently `restoreData` of all of the series and component will be called.
  23198. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  23199. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  23200. // and some components like coordinate system, axes, dataZoom, visualMap only
  23201. // need their target series refresh.
  23202. // (1) If we are implementing this feature some day, we should consider these cases:
  23203. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  23204. // on the settings of `dataZoom`), it should be re-performed if the component
  23205. // is modified by `setOption`.
  23206. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  23207. // it should be re-performed when the result array of `getTargetSeries` changed.
  23208. // We use `dependencies` to cover these issues.
  23209. // (3) How to update target series when coordinate system related components modified.
  23210. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  23211. // and this case all of the tasks will be set as dirty.
  23212. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  23213. // depends on all of the series.
  23214. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  23215. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  23216. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  23217. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  23218. // probably cause state chaos (consider `dataZoomProcessor`).
  23219. this._stageTaskMap.each(function (taskRecord) {
  23220. var overallTask = taskRecord.overallTask;
  23221. overallTask && overallTask.dirty();
  23222. });
  23223. }; // If seriesModel provided, incremental threshold is check by series data.
  23224. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  23225. // For overall task
  23226. if (!task.__pipeline) {
  23227. return;
  23228. }
  23229. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  23230. var pCtx = pipeline.context;
  23231. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  23232. var step = incremental ? pipeline.step : null;
  23233. var modDataCount = pCtx && pCtx.modDataCount;
  23234. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  23235. return {
  23236. step: step,
  23237. modBy: modBy,
  23238. modDataCount: modDataCount
  23239. };
  23240. };
  23241. Scheduler.prototype.getPipeline = function (pipelineId) {
  23242. return this._pipelineMap.get(pipelineId);
  23243. };
  23244. /**
  23245. * Current, progressive rendering starts from visual and layout.
  23246. * Always detect render mode in the same stage, avoiding that incorrect
  23247. * detection caused by data filtering.
  23248. * Caution:
  23249. * `updateStreamModes` use `seriesModel.getData()`.
  23250. */
  23251. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  23252. var pipeline = this._pipelineMap.get(seriesModel.uid);
  23253. var data = seriesModel.getData();
  23254. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  23255. // animation frame. Note that some types of series do not provide
  23256. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  23257. // use the term `incremental` but not `progressive` to describe the
  23258. // case that `chart.appendData`.
  23259. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  23260. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  23261. // see `test/candlestick-large3.html`
  23262. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  23263. seriesModel.pipelineContext = pipeline.context = {
  23264. progressiveRender: progressiveRender,
  23265. modDataCount: modDataCount,
  23266. large: large
  23267. };
  23268. };
  23269. Scheduler.prototype.restorePipelines = function (ecModel) {
  23270. var scheduler = this;
  23271. var pipelineMap = scheduler._pipelineMap = createHashMap();
  23272. ecModel.eachSeries(function (seriesModel) {
  23273. var progressive = seriesModel.getProgressive();
  23274. var pipelineId = seriesModel.uid;
  23275. pipelineMap.set(pipelineId, {
  23276. id: pipelineId,
  23277. head: null,
  23278. tail: null,
  23279. threshold: seriesModel.getProgressiveThreshold(),
  23280. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  23281. blockIndex: -1,
  23282. step: Math.round(progressive || 700),
  23283. count: 0
  23284. });
  23285. scheduler._pipe(seriesModel, seriesModel.dataTask);
  23286. });
  23287. };
  23288. Scheduler.prototype.prepareStageTasks = function () {
  23289. var stageTaskMap = this._stageTaskMap;
  23290. var ecModel = this.api.getModel();
  23291. var api = this.api;
  23292. each(this._allHandlers, function (handler) {
  23293. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  23294. var errMsg = '';
  23295. if ("development" !== 'production') {
  23296. // Currently do not need to support to sepecify them both.
  23297. errMsg = '"reset" and "overallReset" must not be both specified.';
  23298. }
  23299. assert(!(handler.reset && handler.overallReset), errMsg);
  23300. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  23301. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  23302. }, this);
  23303. };
  23304. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  23305. var renderTask = view.renderTask;
  23306. var context = renderTask.context;
  23307. context.model = model;
  23308. context.ecModel = ecModel;
  23309. context.api = api;
  23310. renderTask.__block = !view.incrementalPrepareRender;
  23311. this._pipe(model, renderTask);
  23312. };
  23313. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  23314. // If we do not use `block` here, it should be considered when to update modes.
  23315. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  23316. block: true
  23317. });
  23318. };
  23319. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  23320. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  23321. };
  23322. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  23323. opt = opt || {};
  23324. var unfinished = false;
  23325. var scheduler = this;
  23326. each(stageHandlers, function (stageHandler, idx) {
  23327. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  23328. return;
  23329. }
  23330. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  23331. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  23332. var overallTask = stageHandlerRecord.overallTask;
  23333. if (overallTask) {
  23334. var overallNeedDirty_1;
  23335. var agentStubMap = overallTask.agentStubMap;
  23336. agentStubMap.each(function (stub) {
  23337. if (needSetDirty(opt, stub)) {
  23338. stub.dirty();
  23339. overallNeedDirty_1 = true;
  23340. }
  23341. });
  23342. overallNeedDirty_1 && overallTask.dirty();
  23343. scheduler.updatePayload(overallTask, payload);
  23344. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  23345. // then execute the overall task. And stub will call seriesModel.setData,
  23346. // which ensures that in the overallTask seriesModel.getData() will not
  23347. // return incorrect data.
  23348. agentStubMap.each(function (stub) {
  23349. stub.perform(performArgs_1);
  23350. });
  23351. if (overallTask.perform(performArgs_1)) {
  23352. unfinished = true;
  23353. }
  23354. } else if (seriesTaskMap) {
  23355. seriesTaskMap.each(function (task, pipelineId) {
  23356. if (needSetDirty(opt, task)) {
  23357. task.dirty();
  23358. }
  23359. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  23360. // if intending to declare `performRawSeries` in handlers, only
  23361. // stream-independent (specifically, data item independent) operations can be
  23362. // performed. Because if a series is filtered, most of the tasks will not
  23363. // be performed. A stream-dependent operation probably cause wrong biz logic.
  23364. // Perhaps we should not provide a separate callback for this case instead
  23365. // of providing the config `performRawSeries`. The stream-dependent operations
  23366. // and stream-independent operations should better not be mixed.
  23367. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  23368. scheduler.updatePayload(task, payload);
  23369. if (task.perform(performArgs)) {
  23370. unfinished = true;
  23371. }
  23372. });
  23373. }
  23374. });
  23375. function needSetDirty(opt, task) {
  23376. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  23377. }
  23378. this.unfinished = unfinished || this.unfinished;
  23379. };
  23380. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  23381. var unfinished;
  23382. ecModel.eachSeries(function (seriesModel) {
  23383. // Progress to the end for dataInit and dataRestore.
  23384. unfinished = seriesModel.dataTask.perform() || unfinished;
  23385. });
  23386. this.unfinished = unfinished || this.unfinished;
  23387. };
  23388. Scheduler.prototype.plan = function () {
  23389. // Travel pipelines, check block.
  23390. this._pipelineMap.each(function (pipeline) {
  23391. var task = pipeline.tail;
  23392. do {
  23393. if (task.__block) {
  23394. pipeline.blockIndex = task.__idxInPipeline;
  23395. break;
  23396. }
  23397. task = task.getUpstream();
  23398. } while (task);
  23399. });
  23400. };
  23401. Scheduler.prototype.updatePayload = function (task, payload) {
  23402. payload !== 'remain' && (task.context.payload = payload);
  23403. };
  23404. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23405. var scheduler = this;
  23406. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  23407. // do not need to reuse the map.
  23408. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  23409. var seriesType = stageHandler.seriesType;
  23410. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  23411. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  23412. // it works but it may cause other irrelevant charts blocked.
  23413. if (stageHandler.createOnAllSeries) {
  23414. ecModel.eachRawSeries(create);
  23415. } else if (seriesType) {
  23416. ecModel.eachRawSeriesByType(seriesType, create);
  23417. } else if (getTargetSeries) {
  23418. getTargetSeries(ecModel, api).each(create);
  23419. }
  23420. function create(seriesModel) {
  23421. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  23422. // Reuse original task instance.
  23423. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  23424. plan: seriesTaskPlan,
  23425. reset: seriesTaskReset,
  23426. count: seriesTaskCount
  23427. }));
  23428. task.context = {
  23429. model: seriesModel,
  23430. ecModel: ecModel,
  23431. api: api,
  23432. // PENDING: `useClearVisual` not used?
  23433. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  23434. plan: stageHandler.plan,
  23435. reset: stageHandler.reset,
  23436. scheduler: scheduler
  23437. };
  23438. scheduler._pipe(seriesModel, task);
  23439. }
  23440. };
  23441. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  23442. var scheduler = this;
  23443. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  23444. || createTask({
  23445. reset: overallTaskReset
  23446. });
  23447. overallTask.context = {
  23448. ecModel: ecModel,
  23449. api: api,
  23450. overallReset: stageHandler.overallReset,
  23451. scheduler: scheduler
  23452. };
  23453. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  23454. // do not need to reuse the map.
  23455. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  23456. var seriesType = stageHandler.seriesType;
  23457. var getTargetSeries = stageHandler.getTargetSeries;
  23458. var overallProgress = true;
  23459. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  23460. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  23461. // An overall task with seriesType detected or has `getTargetSeries`, we add
  23462. // stub in each pipelines, it will set the overall task dirty when the pipeline
  23463. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  23464. // we set the pipeline block.
  23465. var errMsg = '';
  23466. if ("development" !== 'production') {
  23467. errMsg = '"createOnAllSeries" is not supported for "overallReset", ' + 'because it will block all streams.';
  23468. }
  23469. assert(!stageHandler.createOnAllSeries, errMsg);
  23470. if (seriesType) {
  23471. ecModel.eachRawSeriesByType(seriesType, createStub);
  23472. } else if (getTargetSeries) {
  23473. getTargetSeries(ecModel, api).each(createStub);
  23474. } // Otherwise, (usually it is legacy case), the overall task will only be
  23475. // executed when upstream is dirty. Otherwise the progressive rendering of all
  23476. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  23477. // dirty info from upstream.
  23478. else {
  23479. overallProgress = false;
  23480. each(ecModel.getSeries(), createStub);
  23481. }
  23482. function createStub(seriesModel) {
  23483. var pipelineId = seriesModel.uid;
  23484. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  23485. // should be set as dirty and re-performed.
  23486. shouldOverallTaskDirty = true, createTask({
  23487. reset: stubReset,
  23488. onDirty: stubOnDirty
  23489. })));
  23490. stub.context = {
  23491. model: seriesModel,
  23492. overallProgress: overallProgress // FIXME:TS never used, so comment it
  23493. // modifyOutputEnd: modifyOutputEnd
  23494. };
  23495. stub.agent = overallTask;
  23496. stub.__block = overallProgress;
  23497. scheduler._pipe(seriesModel, stub);
  23498. }
  23499. if (shouldOverallTaskDirty) {
  23500. overallTask.dirty();
  23501. }
  23502. };
  23503. Scheduler.prototype._pipe = function (seriesModel, task) {
  23504. var pipelineId = seriesModel.uid;
  23505. var pipeline = this._pipelineMap.get(pipelineId);
  23506. !pipeline.head && (pipeline.head = task);
  23507. pipeline.tail && pipeline.tail.pipe(task);
  23508. pipeline.tail = task;
  23509. task.__idxInPipeline = pipeline.count++;
  23510. task.__pipeline = pipeline;
  23511. };
  23512. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  23513. if (isFunction(stageHandler)) {
  23514. stageHandler = {
  23515. overallReset: stageHandler,
  23516. seriesType: detectSeriseType(stageHandler)
  23517. };
  23518. }
  23519. stageHandler.uid = getUID('stageHandler');
  23520. visualType && (stageHandler.visualType = visualType);
  23521. return stageHandler;
  23522. };
  23523. return Scheduler;
  23524. }();
  23525. function overallTaskReset(context) {
  23526. context.overallReset(context.ecModel, context.api, context.payload);
  23527. }
  23528. function stubReset(context) {
  23529. return context.overallProgress && stubProgress;
  23530. }
  23531. function stubProgress() {
  23532. this.agent.dirty();
  23533. this.getDownstream().dirty();
  23534. }
  23535. function stubOnDirty() {
  23536. this.agent && this.agent.dirty();
  23537. }
  23538. function seriesTaskPlan(context) {
  23539. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  23540. }
  23541. function seriesTaskReset(context) {
  23542. if (context.useClearVisual) {
  23543. context.data.clearAllVisual();
  23544. }
  23545. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  23546. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  23547. return makeSeriesTaskProgress(idx);
  23548. }) : singleSeriesTaskProgress;
  23549. }
  23550. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  23551. function makeSeriesTaskProgress(resetDefineIdx) {
  23552. return function (params, context) {
  23553. var data = context.data;
  23554. var resetDefine = context.resetDefines[resetDefineIdx];
  23555. if (resetDefine && resetDefine.dataEach) {
  23556. for (var i = params.start; i < params.end; i++) {
  23557. resetDefine.dataEach(data, i);
  23558. }
  23559. } else if (resetDefine && resetDefine.progress) {
  23560. resetDefine.progress(params, data);
  23561. }
  23562. };
  23563. }
  23564. function seriesTaskCount(context) {
  23565. return context.data.count();
  23566. }
  23567. /**
  23568. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  23569. * To ensure that they can work normally, they should work in block mode, that is,
  23570. * they should not be started util the previous tasks finished. So they cause the
  23571. * progressive rendering disabled. We try to detect the series type, to narrow down
  23572. * the block range to only the series type they concern, but not all series.
  23573. */
  23574. function detectSeriseType(legacyFunc) {
  23575. seriesType = null;
  23576. try {
  23577. // Assume there is no async when calling `eachSeriesByType`.
  23578. legacyFunc(ecModelMock, apiMock);
  23579. } catch (e) {}
  23580. return seriesType;
  23581. }
  23582. var ecModelMock = {};
  23583. var apiMock = {};
  23584. var seriesType;
  23585. mockMethods(ecModelMock, GlobalModel);
  23586. mockMethods(apiMock, ExtensionAPI);
  23587. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  23588. seriesType = type;
  23589. };
  23590. ecModelMock.eachComponent = function (cond) {
  23591. if (cond.mainType === 'series' && cond.subType) {
  23592. seriesType = cond.subType;
  23593. }
  23594. };
  23595. function mockMethods(target, Clz) {
  23596. /* eslint-disable */
  23597. for (var name_1 in Clz.prototype) {
  23598. // Do not use hasOwnProperty
  23599. target[name_1] = noop;
  23600. }
  23601. /* eslint-enable */
  23602. }
  23603. /*
  23604. * Licensed to the Apache Software Foundation (ASF) under one
  23605. * or more contributor license agreements. See the NOTICE file
  23606. * distributed with this work for additional information
  23607. * regarding copyright ownership. The ASF licenses this file
  23608. * to you under the Apache License, Version 2.0 (the
  23609. * "License"); you may not use this file except in compliance
  23610. * with the License. You may obtain a copy of the License at
  23611. *
  23612. * http://www.apache.org/licenses/LICENSE-2.0
  23613. *
  23614. * Unless required by applicable law or agreed to in writing,
  23615. * software distributed under the License is distributed on an
  23616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23617. * KIND, either express or implied. See the License for the
  23618. * specific language governing permissions and limitations
  23619. * under the License.
  23620. */
  23621. /**
  23622. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23623. */
  23624. /*
  23625. * Licensed to the Apache Software Foundation (ASF) under one
  23626. * or more contributor license agreements. See the NOTICE file
  23627. * distributed with this work for additional information
  23628. * regarding copyright ownership. The ASF licenses this file
  23629. * to you under the Apache License, Version 2.0 (the
  23630. * "License"); you may not use this file except in compliance
  23631. * with the License. You may obtain a copy of the License at
  23632. *
  23633. * http://www.apache.org/licenses/LICENSE-2.0
  23634. *
  23635. * Unless required by applicable law or agreed to in writing,
  23636. * software distributed under the License is distributed on an
  23637. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23638. * KIND, either express or implied. See the License for the
  23639. * specific language governing permissions and limitations
  23640. * under the License.
  23641. */
  23642. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  23643. var lightTheme = {
  23644. color: colorAll,
  23645. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  23646. };
  23647. /*
  23648. * Licensed to the Apache Software Foundation (ASF) under one
  23649. * or more contributor license agreements. See the NOTICE file
  23650. * distributed with this work for additional information
  23651. * regarding copyright ownership. The ASF licenses this file
  23652. * to you under the Apache License, Version 2.0 (the
  23653. * "License"); you may not use this file except in compliance
  23654. * with the License. You may obtain a copy of the License at
  23655. *
  23656. * http://www.apache.org/licenses/LICENSE-2.0
  23657. *
  23658. * Unless required by applicable law or agreed to in writing,
  23659. * software distributed under the License is distributed on an
  23660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23661. * KIND, either express or implied. See the License for the
  23662. * specific language governing permissions and limitations
  23663. * under the License.
  23664. */
  23665. /**
  23666. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23667. */
  23668. /*
  23669. * Licensed to the Apache Software Foundation (ASF) under one
  23670. * or more contributor license agreements. See the NOTICE file
  23671. * distributed with this work for additional information
  23672. * regarding copyright ownership. The ASF licenses this file
  23673. * to you under the Apache License, Version 2.0 (the
  23674. * "License"); you may not use this file except in compliance
  23675. * with the License. You may obtain a copy of the License at
  23676. *
  23677. * http://www.apache.org/licenses/LICENSE-2.0
  23678. *
  23679. * Unless required by applicable law or agreed to in writing,
  23680. * software distributed under the License is distributed on an
  23681. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23682. * KIND, either express or implied. See the License for the
  23683. * specific language governing permissions and limitations
  23684. * under the License.
  23685. */
  23686. var contrastColor = '#B9B8CE';
  23687. var backgroundColor = '#100C2A';
  23688. var axisCommon = function () {
  23689. return {
  23690. axisLine: {
  23691. lineStyle: {
  23692. color: contrastColor
  23693. }
  23694. },
  23695. splitLine: {
  23696. lineStyle: {
  23697. color: '#484753'
  23698. }
  23699. },
  23700. splitArea: {
  23701. areaStyle: {
  23702. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  23703. }
  23704. },
  23705. minorSplitLine: {
  23706. lineStyle: {
  23707. color: '#20203B'
  23708. }
  23709. }
  23710. };
  23711. };
  23712. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  23713. var theme = {
  23714. darkMode: true,
  23715. color: colorPalette,
  23716. backgroundColor: backgroundColor,
  23717. axisPointer: {
  23718. lineStyle: {
  23719. color: '#817f91'
  23720. },
  23721. crossStyle: {
  23722. color: '#817f91'
  23723. },
  23724. label: {
  23725. // TODO Contrast of label backgorundColor
  23726. color: '#fff'
  23727. }
  23728. },
  23729. legend: {
  23730. textStyle: {
  23731. color: contrastColor
  23732. }
  23733. },
  23734. textStyle: {
  23735. color: contrastColor
  23736. },
  23737. title: {
  23738. textStyle: {
  23739. color: '#EEF1FA'
  23740. },
  23741. subtextStyle: {
  23742. color: '#B9B8CE'
  23743. }
  23744. },
  23745. toolbox: {
  23746. iconStyle: {
  23747. borderColor: contrastColor
  23748. }
  23749. },
  23750. dataZoom: {
  23751. borderColor: '#71708A',
  23752. textStyle: {
  23753. color: contrastColor
  23754. },
  23755. brushStyle: {
  23756. color: 'rgba(135,163,206,0.3)'
  23757. },
  23758. handleStyle: {
  23759. color: '#353450',
  23760. borderColor: '#C5CBE3'
  23761. },
  23762. moveHandleStyle: {
  23763. color: '#B0B6C3',
  23764. opacity: 0.3
  23765. },
  23766. fillerColor: 'rgba(135,163,206,0.2)',
  23767. emphasis: {
  23768. handleStyle: {
  23769. borderColor: '#91B7F2',
  23770. color: '#4D587D'
  23771. },
  23772. moveHandleStyle: {
  23773. color: '#636D9A',
  23774. opacity: 0.7
  23775. }
  23776. },
  23777. dataBackground: {
  23778. lineStyle: {
  23779. color: '#71708A',
  23780. width: 1
  23781. },
  23782. areaStyle: {
  23783. color: '#71708A'
  23784. }
  23785. },
  23786. selectedDataBackground: {
  23787. lineStyle: {
  23788. color: '#87A3CE'
  23789. },
  23790. areaStyle: {
  23791. color: '#87A3CE'
  23792. }
  23793. }
  23794. },
  23795. visualMap: {
  23796. textStyle: {
  23797. color: contrastColor
  23798. }
  23799. },
  23800. timeline: {
  23801. lineStyle: {
  23802. color: contrastColor
  23803. },
  23804. label: {
  23805. color: contrastColor
  23806. },
  23807. controlStyle: {
  23808. color: contrastColor,
  23809. borderColor: contrastColor
  23810. }
  23811. },
  23812. calendar: {
  23813. itemStyle: {
  23814. color: backgroundColor
  23815. },
  23816. dayLabel: {
  23817. color: contrastColor
  23818. },
  23819. monthLabel: {
  23820. color: contrastColor
  23821. },
  23822. yearLabel: {
  23823. color: contrastColor
  23824. }
  23825. },
  23826. timeAxis: axisCommon(),
  23827. logAxis: axisCommon(),
  23828. valueAxis: axisCommon(),
  23829. categoryAxis: axisCommon(),
  23830. line: {
  23831. symbol: 'circle'
  23832. },
  23833. graph: {
  23834. color: colorPalette
  23835. },
  23836. gauge: {
  23837. title: {
  23838. color: contrastColor
  23839. },
  23840. axisLine: {
  23841. lineStyle: {
  23842. color: [[1, 'rgba(207,212,219,0.2)']]
  23843. }
  23844. },
  23845. axisLabel: {
  23846. color: contrastColor
  23847. },
  23848. detail: {
  23849. color: '#EEF1FA'
  23850. }
  23851. },
  23852. candlestick: {
  23853. itemStyle: {
  23854. color: '#f64e56',
  23855. color0: '#54ea92',
  23856. borderColor: '#f64e56',
  23857. borderColor0: '#54ea92' // borderColor: '#ca2824',
  23858. // borderColor0: '#09a443'
  23859. }
  23860. }
  23861. };
  23862. theme.categoryAxis.splitLine.show = false;
  23863. /**
  23864. * Usage of query:
  23865. * `chart.on('click', query, handler);`
  23866. * The `query` can be:
  23867. * + The component type query string, only `mainType` or `mainType.subType`,
  23868. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23869. * + The component query object, like:
  23870. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23871. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23872. * + The data query object, like:
  23873. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23874. * + The other query object (cmponent customized query), like:
  23875. * `{element: 'some'}` (only available in custom series).
  23876. *
  23877. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23878. * same as there is no such prop in the `query` object.
  23879. */
  23880. var ECEventProcessor =
  23881. /** @class */
  23882. function () {
  23883. function ECEventProcessor() {}
  23884. ECEventProcessor.prototype.normalizeQuery = function (query) {
  23885. var cptQuery = {};
  23886. var dataQuery = {};
  23887. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23888. if (isString(query)) {
  23889. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23890. cptQuery.mainType = condCptType.main || null;
  23891. cptQuery.subType = condCptType.sub || null;
  23892. } // `query` is an object, convert to {mainType, index, name, id}.
  23893. else {
  23894. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23895. // can not be used in `compomentModel.filterForExposedEvent`.
  23896. var suffixes_1 = ['Index', 'Name', 'Id'];
  23897. var dataKeys_1 = {
  23898. name: 1,
  23899. dataIndex: 1,
  23900. dataType: 1
  23901. };
  23902. each(query, function (val, key) {
  23903. var reserved = false;
  23904. for (var i = 0; i < suffixes_1.length; i++) {
  23905. var propSuffix = suffixes_1[i];
  23906. var suffixPos = key.lastIndexOf(propSuffix);
  23907. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23908. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23909. if (mainType !== 'data') {
  23910. cptQuery.mainType = mainType;
  23911. cptQuery[propSuffix.toLowerCase()] = val;
  23912. reserved = true;
  23913. }
  23914. }
  23915. }
  23916. if (dataKeys_1.hasOwnProperty(key)) {
  23917. dataQuery[key] = val;
  23918. reserved = true;
  23919. }
  23920. if (!reserved) {
  23921. otherQuery[key] = val;
  23922. }
  23923. });
  23924. }
  23925. return {
  23926. cptQuery: cptQuery,
  23927. dataQuery: dataQuery,
  23928. otherQuery: otherQuery
  23929. };
  23930. };
  23931. ECEventProcessor.prototype.filter = function (eventType, query) {
  23932. // They should be assigned before each trigger call.
  23933. var eventInfo = this.eventInfo;
  23934. if (!eventInfo) {
  23935. return true;
  23936. }
  23937. var targetEl = eventInfo.targetEl;
  23938. var packedEvent = eventInfo.packedEvent;
  23939. var model = eventInfo.model;
  23940. var view = eventInfo.view; // For event like 'globalout'.
  23941. if (!model || !view) {
  23942. return true;
  23943. }
  23944. var cptQuery = query.cptQuery;
  23945. var dataQuery = query.dataQuery;
  23946. 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));
  23947. function check(query, host, prop, propOnHost) {
  23948. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23949. }
  23950. };
  23951. ECEventProcessor.prototype.afterTrigger = function () {
  23952. // Make sure the eventInfo won't be used in next trigger.
  23953. this.eventInfo = null;
  23954. };
  23955. return ECEventProcessor;
  23956. }();
  23957. var SYMBOL_PROPS_WITH_CB = ['symbol', 'symbolSize', 'symbolRotate', 'symbolOffset'];
  23958. var SYMBOL_PROPS = SYMBOL_PROPS_WITH_CB.concat(['symbolKeepAspect']); // Encoding visual for all series include which is filtered for legend drawing
  23959. var seriesSymbolTask = {
  23960. createOnAllSeries: true,
  23961. // For legend.
  23962. performRawSeries: true,
  23963. reset: function (seriesModel, ecModel) {
  23964. var data = seriesModel.getData();
  23965. if (seriesModel.legendIcon) {
  23966. data.setVisual('legendIcon', seriesModel.legendIcon);
  23967. }
  23968. if (!seriesModel.hasSymbolVisual) {
  23969. return;
  23970. }
  23971. var symbolOptions = {};
  23972. var symbolOptionsCb = {};
  23973. var hasCallback = false;
  23974. for (var i = 0; i < SYMBOL_PROPS_WITH_CB.length; i++) {
  23975. var symbolPropName = SYMBOL_PROPS_WITH_CB[i];
  23976. var val = seriesModel.get(symbolPropName);
  23977. if (isFunction(val)) {
  23978. hasCallback = true;
  23979. symbolOptionsCb[symbolPropName] = val;
  23980. } else {
  23981. symbolOptions[symbolPropName] = val;
  23982. }
  23983. }
  23984. symbolOptions.symbol = symbolOptions.symbol || seriesModel.defaultSymbol;
  23985. data.setVisual(extend({
  23986. legendIcon: seriesModel.legendIcon || symbolOptions.symbol,
  23987. symbolKeepAspect: seriesModel.get('symbolKeepAspect')
  23988. }, symbolOptions)); // Only visible series has each data be visual encoded
  23989. if (ecModel.isSeriesFiltered(seriesModel)) {
  23990. return;
  23991. }
  23992. var symbolPropsCb = keys(symbolOptionsCb);
  23993. function dataEach(data, idx) {
  23994. var rawValue = seriesModel.getRawValue(idx);
  23995. var params = seriesModel.getDataParams(idx);
  23996. for (var i = 0; i < symbolPropsCb.length; i++) {
  23997. var symbolPropName = symbolPropsCb[i];
  23998. data.setItemVisual(idx, symbolPropName, symbolOptionsCb[symbolPropName](rawValue, params));
  23999. }
  24000. }
  24001. return {
  24002. dataEach: hasCallback ? dataEach : null
  24003. };
  24004. }
  24005. };
  24006. var dataSymbolTask = {
  24007. createOnAllSeries: true,
  24008. // For legend.
  24009. performRawSeries: true,
  24010. reset: function (seriesModel, ecModel) {
  24011. if (!seriesModel.hasSymbolVisual) {
  24012. return;
  24013. } // Only visible series has each data be visual encoded
  24014. if (ecModel.isSeriesFiltered(seriesModel)) {
  24015. return;
  24016. }
  24017. var data = seriesModel.getData();
  24018. function dataEach(data, idx) {
  24019. var itemModel = data.getItemModel(idx);
  24020. for (var i = 0; i < SYMBOL_PROPS.length; i++) {
  24021. var symbolPropName = SYMBOL_PROPS[i];
  24022. var val = itemModel.getShallow(symbolPropName, true);
  24023. if (val != null) {
  24024. data.setItemVisual(idx, symbolPropName, val);
  24025. }
  24026. }
  24027. }
  24028. return {
  24029. dataEach: data.hasItemOption ? dataEach : null
  24030. };
  24031. }
  24032. };
  24033. /*
  24034. * Licensed to the Apache Software Foundation (ASF) under one
  24035. * or more contributor license agreements. See the NOTICE file
  24036. * distributed with this work for additional information
  24037. * regarding copyright ownership. The ASF licenses this file
  24038. * to you under the Apache License, Version 2.0 (the
  24039. * "License"); you may not use this file except in compliance
  24040. * with the License. You may obtain a copy of the License at
  24041. *
  24042. * http://www.apache.org/licenses/LICENSE-2.0
  24043. *
  24044. * Unless required by applicable law or agreed to in writing,
  24045. * software distributed under the License is distributed on an
  24046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24047. * KIND, either express or implied. See the License for the
  24048. * specific language governing permissions and limitations
  24049. * under the License.
  24050. */
  24051. /**
  24052. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24053. */
  24054. /*
  24055. * Licensed to the Apache Software Foundation (ASF) under one
  24056. * or more contributor license agreements. See the NOTICE file
  24057. * distributed with this work for additional information
  24058. * regarding copyright ownership. The ASF licenses this file
  24059. * to you under the Apache License, Version 2.0 (the
  24060. * "License"); you may not use this file except in compliance
  24061. * with the License. You may obtain a copy of the License at
  24062. *
  24063. * http://www.apache.org/licenses/LICENSE-2.0
  24064. *
  24065. * Unless required by applicable law or agreed to in writing,
  24066. * software distributed under the License is distributed on an
  24067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24068. * KIND, either express or implied. See the License for the
  24069. * specific language governing permissions and limitations
  24070. * under the License.
  24071. */
  24072. function getItemVisualFromData(data, dataIndex, key) {
  24073. switch (key) {
  24074. case 'color':
  24075. var style = data.getItemVisual(dataIndex, 'style');
  24076. return style[data.getVisual('drawType')];
  24077. case 'opacity':
  24078. return data.getItemVisual(dataIndex, 'style').opacity;
  24079. case 'symbol':
  24080. case 'symbolSize':
  24081. case 'liftZ':
  24082. return data.getItemVisual(dataIndex, key);
  24083. default:
  24084. if ("development" !== 'production') {
  24085. console.warn("Unknown visual type " + key);
  24086. }
  24087. }
  24088. }
  24089. function getVisualFromData(data, key) {
  24090. switch (key) {
  24091. case 'color':
  24092. var style = data.getVisual('style');
  24093. return style[data.getVisual('drawType')];
  24094. case 'opacity':
  24095. return data.getVisual('style').opacity;
  24096. case 'symbol':
  24097. case 'symbolSize':
  24098. case 'liftZ':
  24099. return data.getVisual(key);
  24100. default:
  24101. if ("development" !== 'production') {
  24102. console.warn("Unknown visual type " + key);
  24103. }
  24104. }
  24105. }
  24106. function setItemVisualFromData(data, dataIndex, key, value) {
  24107. switch (key) {
  24108. case 'color':
  24109. // Make sure not sharing style object.
  24110. var style = data.ensureUniqueItemVisual(dataIndex, 'style');
  24111. style[data.getVisual('drawType')] = value; // Mark the color has been changed, not from palette anymore
  24112. data.setItemVisual(dataIndex, 'colorFromPalette', false);
  24113. break;
  24114. case 'opacity':
  24115. data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value;
  24116. break;
  24117. case 'symbol':
  24118. case 'symbolSize':
  24119. case 'liftZ':
  24120. data.setItemVisual(dataIndex, key, value);
  24121. break;
  24122. default:
  24123. if ("development" !== 'production') {
  24124. console.warn("Unknown visual type " + key);
  24125. }
  24126. }
  24127. }
  24128. // Includes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  24129. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  24130. function getSeriesIndices(ecModel, payload) {
  24131. var seriesIndices = [];
  24132. ecModel.eachComponent({
  24133. mainType: 'series',
  24134. subType: seriesType,
  24135. query: payload
  24136. }, function (seriesModel) {
  24137. seriesIndices.push(seriesModel.seriesIndex);
  24138. });
  24139. return seriesIndices;
  24140. }
  24141. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  24142. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  24143. payload = extend({}, payload);
  24144. if ("development" !== 'production') {
  24145. deprecateReplaceLog(payload.type, eventsMap[1]);
  24146. }
  24147. api.dispatchAction(extend(payload, {
  24148. type: eventsMap[1],
  24149. seriesIndex: getSeriesIndices(ecModel, payload)
  24150. }));
  24151. });
  24152. });
  24153. }
  24154. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  24155. var legacyEventName = type + eventPostfix;
  24156. if (!ecIns.isSilent(legacyEventName)) {
  24157. if ("development" !== 'production') {
  24158. deprecateLog("event " + legacyEventName + " is deprecated.");
  24159. }
  24160. ecModel.eachComponent({
  24161. mainType: 'series',
  24162. subType: 'pie'
  24163. }, function (seriesModel) {
  24164. var seriesIndex = seriesModel.seriesIndex;
  24165. var selectedMap = seriesModel.option.selectedMap;
  24166. var selected = payload.selected;
  24167. for (var i = 0; i < selected.length; i++) {
  24168. if (selected[i].seriesIndex === seriesIndex) {
  24169. var data = seriesModel.getData();
  24170. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  24171. ecIns.trigger(legacyEventName, {
  24172. type: legacyEventName,
  24173. seriesId: seriesModel.id,
  24174. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  24175. selected: isString(selectedMap) ? selectedMap : extend({}, selectedMap)
  24176. });
  24177. }
  24178. }
  24179. });
  24180. }
  24181. }
  24182. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  24183. messageCenter.on('selectchanged', function (params) {
  24184. var ecModel = api.getModel();
  24185. if (params.isFromClick) {
  24186. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  24187. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  24188. } else if (params.fromAction === 'select') {
  24189. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  24190. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  24191. } else if (params.fromAction === 'unselect') {
  24192. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  24193. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  24194. }
  24195. });
  24196. }
  24197. /*
  24198. * Licensed to the Apache Software Foundation (ASF) under one
  24199. * or more contributor license agreements. See the NOTICE file
  24200. * distributed with this work for additional information
  24201. * regarding copyright ownership. The ASF licenses this file
  24202. * to you under the Apache License, Version 2.0 (the
  24203. * "License"); you may not use this file except in compliance
  24204. * with the License. You may obtain a copy of the License at
  24205. *
  24206. * http://www.apache.org/licenses/LICENSE-2.0
  24207. *
  24208. * Unless required by applicable law or agreed to in writing,
  24209. * software distributed under the License is distributed on an
  24210. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24211. * KIND, either express or implied. See the License for the
  24212. * specific language governing permissions and limitations
  24213. * under the License.
  24214. */
  24215. /**
  24216. * AUTO-GENERATED FILE. DO NOT MODIFY.
  24217. */
  24218. /*
  24219. * Licensed to the Apache Software Foundation (ASF) under one
  24220. * or more contributor license agreements. See the NOTICE file
  24221. * distributed with this work for additional information
  24222. * regarding copyright ownership. The ASF licenses this file
  24223. * to you under the Apache License, Version 2.0 (the
  24224. * "License"); you may not use this file except in compliance
  24225. * with the License. You may obtain a copy of the License at
  24226. *
  24227. * http://www.apache.org/licenses/LICENSE-2.0
  24228. *
  24229. * Unless required by applicable law or agreed to in writing,
  24230. * software distributed under the License is distributed on an
  24231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24232. * KIND, either express or implied. See the License for the
  24233. * specific language governing permissions and limitations
  24234. * under the License.
  24235. */
  24236. function findEventDispatcher(target, det, returnFirstMatch) {
  24237. var found;
  24238. while (target) {
  24239. if (det(target)) {
  24240. found = target;
  24241. if (returnFirstMatch) {
  24242. break;
  24243. }
  24244. }
  24245. target = target.__hostTarget || target.parent;
  24246. }
  24247. return found;
  24248. }
  24249. var wmUniqueIndex = Math.round(Math.random() * 9);
  24250. var supportDefineProperty = typeof Object.defineProperty === 'function';
  24251. var WeakMap = (function () {
  24252. function WeakMap() {
  24253. this._id = '__ec_inner_' + wmUniqueIndex++;
  24254. }
  24255. WeakMap.prototype.get = function (key) {
  24256. return this._guard(key)[this._id];
  24257. };
  24258. WeakMap.prototype.set = function (key, value) {
  24259. var target = this._guard(key);
  24260. if (supportDefineProperty) {
  24261. Object.defineProperty(target, this._id, {
  24262. value: value,
  24263. enumerable: false,
  24264. configurable: true
  24265. });
  24266. }
  24267. else {
  24268. target[this._id] = value;
  24269. }
  24270. return this;
  24271. };
  24272. WeakMap.prototype["delete"] = function (key) {
  24273. if (this.has(key)) {
  24274. delete this._guard(key)[this._id];
  24275. return true;
  24276. }
  24277. return false;
  24278. };
  24279. WeakMap.prototype.has = function (key) {
  24280. return !!this._guard(key)[this._id];
  24281. };
  24282. WeakMap.prototype._guard = function (key) {
  24283. if (key !== Object(key)) {
  24284. throw TypeError('Value of WeakMap is not a non-null object.');
  24285. }
  24286. return key;
  24287. };
  24288. return WeakMap;
  24289. }());
  24290. /**
  24291. * Triangle shape
  24292. * @inner
  24293. */
  24294. var Triangle = Path.extend({
  24295. type: 'triangle',
  24296. shape: {
  24297. cx: 0,
  24298. cy: 0,
  24299. width: 0,
  24300. height: 0
  24301. },
  24302. buildPath: function (path, shape) {
  24303. var cx = shape.cx;
  24304. var cy = shape.cy;
  24305. var width = shape.width / 2;
  24306. var height = shape.height / 2;
  24307. path.moveTo(cx, cy - height);
  24308. path.lineTo(cx + width, cy + height);
  24309. path.lineTo(cx - width, cy + height);
  24310. path.closePath();
  24311. }
  24312. });
  24313. /**
  24314. * Diamond shape
  24315. * @inner
  24316. */
  24317. var Diamond = Path.extend({
  24318. type: 'diamond',
  24319. shape: {
  24320. cx: 0,
  24321. cy: 0,
  24322. width: 0,
  24323. height: 0
  24324. },
  24325. buildPath: function (path, shape) {
  24326. var cx = shape.cx;
  24327. var cy = shape.cy;
  24328. var width = shape.width / 2;
  24329. var height = shape.height / 2;
  24330. path.moveTo(cx, cy - height);
  24331. path.lineTo(cx + width, cy);
  24332. path.lineTo(cx, cy + height);
  24333. path.lineTo(cx - width, cy);
  24334. path.closePath();
  24335. }
  24336. });
  24337. /**
  24338. * Pin shape
  24339. * @inner
  24340. */
  24341. var Pin = Path.extend({
  24342. type: 'pin',
  24343. shape: {
  24344. // x, y on the cusp
  24345. x: 0,
  24346. y: 0,
  24347. width: 0,
  24348. height: 0
  24349. },
  24350. buildPath: function (path, shape) {
  24351. var x = shape.x;
  24352. var y = shape.y;
  24353. var w = shape.width / 5 * 3; // Height must be larger than width
  24354. var h = Math.max(w, shape.height);
  24355. var r = w / 2; // Dist on y with tangent point and circle center
  24356. var dy = r * r / (h - r);
  24357. var cy = y - h + r + dy;
  24358. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  24359. var dx = Math.cos(angle) * r;
  24360. var tanX = Math.sin(angle);
  24361. var tanY = Math.cos(angle);
  24362. var cpLen = r * 0.6;
  24363. var cpLen2 = r * 0.7;
  24364. path.moveTo(x - dx, cy + dy);
  24365. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  24366. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  24367. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  24368. path.closePath();
  24369. }
  24370. });
  24371. /**
  24372. * Arrow shape
  24373. * @inner
  24374. */
  24375. var Arrow = Path.extend({
  24376. type: 'arrow',
  24377. shape: {
  24378. x: 0,
  24379. y: 0,
  24380. width: 0,
  24381. height: 0
  24382. },
  24383. buildPath: function (ctx, shape) {
  24384. var height = shape.height;
  24385. var width = shape.width;
  24386. var x = shape.x;
  24387. var y = shape.y;
  24388. var dx = width / 3 * 2;
  24389. ctx.moveTo(x, y);
  24390. ctx.lineTo(x + dx, y + height);
  24391. ctx.lineTo(x, y + height / 4 * 3);
  24392. ctx.lineTo(x - dx, y + height);
  24393. ctx.lineTo(x, y);
  24394. ctx.closePath();
  24395. }
  24396. });
  24397. /**
  24398. * Map of path constructors
  24399. */
  24400. // TODO Use function to build symbol path.
  24401. var symbolCtors = {
  24402. line: Line,
  24403. rect: Rect,
  24404. roundRect: Rect,
  24405. square: Rect,
  24406. circle: Circle,
  24407. diamond: Diamond,
  24408. pin: Pin,
  24409. arrow: Arrow,
  24410. triangle: Triangle
  24411. };
  24412. var symbolShapeMakers = {
  24413. line: function (x, y, w, h, shape) {
  24414. shape.x1 = x;
  24415. shape.y1 = y + h / 2;
  24416. shape.x2 = x + w;
  24417. shape.y2 = y + h / 2;
  24418. },
  24419. rect: function (x, y, w, h, shape) {
  24420. shape.x = x;
  24421. shape.y = y;
  24422. shape.width = w;
  24423. shape.height = h;
  24424. },
  24425. roundRect: function (x, y, w, h, shape) {
  24426. shape.x = x;
  24427. shape.y = y;
  24428. shape.width = w;
  24429. shape.height = h;
  24430. shape.r = Math.min(w, h) / 4;
  24431. },
  24432. square: function (x, y, w, h, shape) {
  24433. var size = Math.min(w, h);
  24434. shape.x = x;
  24435. shape.y = y;
  24436. shape.width = size;
  24437. shape.height = size;
  24438. },
  24439. circle: function (x, y, w, h, shape) {
  24440. // Put circle in the center of square
  24441. shape.cx = x + w / 2;
  24442. shape.cy = y + h / 2;
  24443. shape.r = Math.min(w, h) / 2;
  24444. },
  24445. diamond: function (x, y, w, h, shape) {
  24446. shape.cx = x + w / 2;
  24447. shape.cy = y + h / 2;
  24448. shape.width = w;
  24449. shape.height = h;
  24450. },
  24451. pin: function (x, y, w, h, shape) {
  24452. shape.x = x + w / 2;
  24453. shape.y = y + h / 2;
  24454. shape.width = w;
  24455. shape.height = h;
  24456. },
  24457. arrow: function (x, y, w, h, shape) {
  24458. shape.x = x + w / 2;
  24459. shape.y = y + h / 2;
  24460. shape.width = w;
  24461. shape.height = h;
  24462. },
  24463. triangle: function (x, y, w, h, shape) {
  24464. shape.cx = x + w / 2;
  24465. shape.cy = y + h / 2;
  24466. shape.width = w;
  24467. shape.height = h;
  24468. }
  24469. };
  24470. var symbolBuildProxies = {};
  24471. each(symbolCtors, function (Ctor, name) {
  24472. symbolBuildProxies[name] = new Ctor();
  24473. });
  24474. var SymbolClz = Path.extend({
  24475. type: 'symbol',
  24476. shape: {
  24477. symbolType: '',
  24478. x: 0,
  24479. y: 0,
  24480. width: 0,
  24481. height: 0
  24482. },
  24483. calculateTextPosition: function (out, config, rect) {
  24484. var res = calculateTextPosition(out, config, rect);
  24485. var shape = this.shape;
  24486. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  24487. res.y = rect.y + rect.height * 0.4;
  24488. }
  24489. return res;
  24490. },
  24491. buildPath: function (ctx, shape, inBundle) {
  24492. var symbolType = shape.symbolType;
  24493. if (symbolType !== 'none') {
  24494. var proxySymbol = symbolBuildProxies[symbolType];
  24495. if (!proxySymbol) {
  24496. // Default rect
  24497. symbolType = 'rect';
  24498. proxySymbol = symbolBuildProxies[symbolType];
  24499. }
  24500. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  24501. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  24502. }
  24503. }
  24504. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  24505. function symbolPathSetColor(color, innerColor) {
  24506. if (this.type !== 'image') {
  24507. var symbolStyle = this.style;
  24508. if (this.__isEmptyBrush) {
  24509. symbolStyle.stroke = color;
  24510. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView
  24511. symbolStyle.lineWidth = 2;
  24512. } else if (this.shape.symbolType === 'line') {
  24513. symbolStyle.stroke = color;
  24514. } else {
  24515. symbolStyle.fill = color;
  24516. }
  24517. this.markRedraw();
  24518. }
  24519. }
  24520. /**
  24521. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  24522. */
  24523. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  24524. keepAspect) {
  24525. // TODO Support image object, DynamicImage.
  24526. var isEmpty = symbolType.indexOf('empty') === 0;
  24527. if (isEmpty) {
  24528. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  24529. }
  24530. var symbolPath;
  24531. if (symbolType.indexOf('image://') === 0) {
  24532. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24533. } else if (symbolType.indexOf('path://') === 0) {
  24534. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  24535. } else {
  24536. symbolPath = new SymbolClz({
  24537. shape: {
  24538. symbolType: symbolType,
  24539. x: x,
  24540. y: y,
  24541. width: w,
  24542. height: h
  24543. }
  24544. });
  24545. }
  24546. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  24547. symbolPath.setColor = symbolPathSetColor;
  24548. if (color) {
  24549. symbolPath.setColor(color);
  24550. }
  24551. return symbolPath;
  24552. }
  24553. function normalizeSymbolSize(symbolSize) {
  24554. if (!isArray(symbolSize)) {
  24555. symbolSize = [+symbolSize, +symbolSize];
  24556. }
  24557. return [symbolSize[0] || 0, symbolSize[1] || 0];
  24558. }
  24559. function normalizeSymbolOffset(symbolOffset, symbolSize) {
  24560. if (symbolOffset == null) {
  24561. return;
  24562. }
  24563. if (!isArray(symbolOffset)) {
  24564. symbolOffset = [symbolOffset, symbolOffset];
  24565. }
  24566. return [parsePercent$1(symbolOffset[0], symbolSize[0]) || 0, parsePercent$1(retrieve2(symbolOffset[1], symbolOffset[0]), symbolSize[1]) || 0];
  24567. }
  24568. function isSafeNum(num) {
  24569. return isFinite(num);
  24570. }
  24571. function createLinearGradient(ctx, obj, rect) {
  24572. var x = obj.x == null ? 0 : obj.x;
  24573. var x2 = obj.x2 == null ? 1 : obj.x2;
  24574. var y = obj.y == null ? 0 : obj.y;
  24575. var y2 = obj.y2 == null ? 0 : obj.y2;
  24576. if (!obj.global) {
  24577. x = x * rect.width + rect.x;
  24578. x2 = x2 * rect.width + rect.x;
  24579. y = y * rect.height + rect.y;
  24580. y2 = y2 * rect.height + rect.y;
  24581. }
  24582. x = isSafeNum(x) ? x : 0;
  24583. x2 = isSafeNum(x2) ? x2 : 1;
  24584. y = isSafeNum(y) ? y : 0;
  24585. y2 = isSafeNum(y2) ? y2 : 0;
  24586. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  24587. return canvasGradient;
  24588. }
  24589. function createRadialGradient(ctx, obj, rect) {
  24590. var width = rect.width;
  24591. var height = rect.height;
  24592. var min = Math.min(width, height);
  24593. var x = obj.x == null ? 0.5 : obj.x;
  24594. var y = obj.y == null ? 0.5 : obj.y;
  24595. var r = obj.r == null ? 0.5 : obj.r;
  24596. if (!obj.global) {
  24597. x = x * width + rect.x;
  24598. y = y * height + rect.y;
  24599. r = r * min;
  24600. }
  24601. x = isSafeNum(x) ? x : 0.5;
  24602. y = isSafeNum(y) ? y : 0.5;
  24603. r = r >= 0 && isSafeNum(r) ? r : 0.5;
  24604. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24605. return canvasGradient;
  24606. }
  24607. function getCanvasGradient(ctx, obj, rect) {
  24608. var canvasGradient = obj.type === 'radial'
  24609. ? createRadialGradient(ctx, obj, rect)
  24610. : createLinearGradient(ctx, obj, rect);
  24611. var colorStops = obj.colorStops;
  24612. for (var i = 0; i < colorStops.length; i++) {
  24613. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24614. }
  24615. return canvasGradient;
  24616. }
  24617. function isClipPathChanged(clipPaths, prevClipPaths) {
  24618. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24619. return false;
  24620. }
  24621. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24622. return true;
  24623. }
  24624. for (var i = 0; i < clipPaths.length; i++) {
  24625. if (clipPaths[i] !== prevClipPaths[i]) {
  24626. return true;
  24627. }
  24628. }
  24629. return false;
  24630. }
  24631. function parseInt10(val) {
  24632. return parseInt(val, 10);
  24633. }
  24634. function getSize(root, whIdx, opts) {
  24635. var wh = ['width', 'height'][whIdx];
  24636. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  24637. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  24638. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  24639. if (opts[wh] != null && opts[wh] !== 'auto') {
  24640. return parseFloat(opts[wh]);
  24641. }
  24642. var stl = document.defaultView.getComputedStyle(root);
  24643. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  24644. - (parseInt10(stl[plt]) || 0)
  24645. - (parseInt10(stl[prb]) || 0)) | 0;
  24646. }
  24647. function normalizeLineDash(lineType, lineWidth) {
  24648. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24649. return null;
  24650. }
  24651. return lineType === 'dashed'
  24652. ? [4 * lineWidth, 2 * lineWidth]
  24653. : lineType === 'dotted'
  24654. ? [lineWidth]
  24655. : isNumber(lineType)
  24656. ? [lineType] : isArray(lineType) ? lineType : null;
  24657. }
  24658. function getLineDash(el) {
  24659. var style = el.style;
  24660. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24661. var lineDashOffset = style.lineDashOffset;
  24662. if (lineDash) {
  24663. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24664. if (lineScale_1 && lineScale_1 !== 1) {
  24665. lineDash = map(lineDash, function (rawVal) {
  24666. return rawVal / lineScale_1;
  24667. });
  24668. lineDashOffset /= lineScale_1;
  24669. }
  24670. }
  24671. return [lineDash, lineDashOffset];
  24672. }
  24673. var pathProxyForDraw = new PathProxy(true);
  24674. function styleHasStroke(style) {
  24675. var stroke = style.stroke;
  24676. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24677. }
  24678. function isValidStrokeFillStyle(strokeOrFill) {
  24679. return typeof strokeOrFill === 'string' && strokeOrFill !== 'none';
  24680. }
  24681. function styleHasFill(style) {
  24682. var fill = style.fill;
  24683. return fill != null && fill !== 'none';
  24684. }
  24685. function doFillPath(ctx, style) {
  24686. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24687. var originalGlobalAlpha = ctx.globalAlpha;
  24688. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24689. ctx.fill();
  24690. ctx.globalAlpha = originalGlobalAlpha;
  24691. }
  24692. else {
  24693. ctx.fill();
  24694. }
  24695. }
  24696. function doStrokePath(ctx, style) {
  24697. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24698. var originalGlobalAlpha = ctx.globalAlpha;
  24699. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24700. ctx.stroke();
  24701. ctx.globalAlpha = originalGlobalAlpha;
  24702. }
  24703. else {
  24704. ctx.stroke();
  24705. }
  24706. }
  24707. function createCanvasPattern(ctx, pattern, el) {
  24708. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24709. if (isImageReady(image)) {
  24710. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24711. if (typeof DOMMatrix === 'function'
  24712. && canvasPattern
  24713. && canvasPattern.setTransform) {
  24714. var matrix = new DOMMatrix();
  24715. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24716. matrix.rotateSelf(0, 0, (pattern.rotation || 0) * RADIAN_TO_DEGREE);
  24717. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24718. canvasPattern.setTransform(matrix);
  24719. }
  24720. return canvasPattern;
  24721. }
  24722. }
  24723. function brushPath(ctx, el, style, inBatch) {
  24724. var _a;
  24725. var hasStroke = styleHasStroke(style);
  24726. var hasFill = styleHasFill(style);
  24727. var strokePercent = style.strokePercent;
  24728. var strokePart = strokePercent < 1;
  24729. var firstDraw = !el.path;
  24730. if ((!el.silent || strokePart) && firstDraw) {
  24731. el.createPathProxy();
  24732. }
  24733. var path = el.path || pathProxyForDraw;
  24734. var dirtyFlag = el.__dirty;
  24735. if (!inBatch) {
  24736. var fill = style.fill;
  24737. var stroke = style.stroke;
  24738. var hasFillGradient = hasFill && !!fill.colorStops;
  24739. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24740. var hasFillPattern = hasFill && !!fill.image;
  24741. var hasStrokePattern = hasStroke && !!stroke.image;
  24742. var fillGradient = void 0;
  24743. var strokeGradient = void 0;
  24744. var fillPattern = void 0;
  24745. var strokePattern = void 0;
  24746. var rect = void 0;
  24747. if (hasFillGradient || hasStrokeGradient) {
  24748. rect = el.getBoundingRect();
  24749. }
  24750. if (hasFillGradient) {
  24751. fillGradient = dirtyFlag
  24752. ? getCanvasGradient(ctx, fill, rect)
  24753. : el.__canvasFillGradient;
  24754. el.__canvasFillGradient = fillGradient;
  24755. }
  24756. if (hasStrokeGradient) {
  24757. strokeGradient = dirtyFlag
  24758. ? getCanvasGradient(ctx, stroke, rect)
  24759. : el.__canvasStrokeGradient;
  24760. el.__canvasStrokeGradient = strokeGradient;
  24761. }
  24762. if (hasFillPattern) {
  24763. fillPattern = (dirtyFlag || !el.__canvasFillPattern)
  24764. ? createCanvasPattern(ctx, fill, el)
  24765. : el.__canvasFillPattern;
  24766. el.__canvasFillPattern = fillPattern;
  24767. }
  24768. if (hasStrokePattern) {
  24769. strokePattern = (dirtyFlag || !el.__canvasStrokePattern)
  24770. ? createCanvasPattern(ctx, stroke, el)
  24771. : el.__canvasStrokePattern;
  24772. el.__canvasStrokePattern = fillPattern;
  24773. }
  24774. if (hasFillGradient) {
  24775. ctx.fillStyle = fillGradient;
  24776. }
  24777. else if (hasFillPattern) {
  24778. if (fillPattern) {
  24779. ctx.fillStyle = fillPattern;
  24780. }
  24781. else {
  24782. hasFill = false;
  24783. }
  24784. }
  24785. if (hasStrokeGradient) {
  24786. ctx.strokeStyle = strokeGradient;
  24787. }
  24788. else if (hasStrokePattern) {
  24789. if (strokePattern) {
  24790. ctx.strokeStyle = strokePattern;
  24791. }
  24792. else {
  24793. hasStroke = false;
  24794. }
  24795. }
  24796. }
  24797. var scale = el.getGlobalScale();
  24798. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24799. var lineDash;
  24800. var lineDashOffset;
  24801. if (ctx.setLineDash && style.lineDash) {
  24802. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24803. }
  24804. var needsRebuild = true;
  24805. if (firstDraw || (dirtyFlag & SHAPE_CHANGED_BIT)) {
  24806. path.setDPR(ctx.dpr);
  24807. if (strokePart) {
  24808. path.setContext(null);
  24809. }
  24810. else {
  24811. path.setContext(ctx);
  24812. needsRebuild = false;
  24813. }
  24814. path.reset();
  24815. el.buildPath(path, el.shape, inBatch);
  24816. path.toStatic();
  24817. el.pathUpdated();
  24818. }
  24819. if (needsRebuild) {
  24820. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24821. }
  24822. if (lineDash) {
  24823. ctx.setLineDash(lineDash);
  24824. ctx.lineDashOffset = lineDashOffset;
  24825. }
  24826. if (!inBatch) {
  24827. if (style.strokeFirst) {
  24828. if (hasStroke) {
  24829. doStrokePath(ctx, style);
  24830. }
  24831. if (hasFill) {
  24832. doFillPath(ctx, style);
  24833. }
  24834. }
  24835. else {
  24836. if (hasFill) {
  24837. doFillPath(ctx, style);
  24838. }
  24839. if (hasStroke) {
  24840. doStrokePath(ctx, style);
  24841. }
  24842. }
  24843. }
  24844. if (lineDash) {
  24845. ctx.setLineDash([]);
  24846. }
  24847. }
  24848. function brushImage(ctx, el, style) {
  24849. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24850. if (!image || !isImageReady(image)) {
  24851. return;
  24852. }
  24853. var x = style.x || 0;
  24854. var y = style.y || 0;
  24855. var width = el.getWidth();
  24856. var height = el.getHeight();
  24857. var aspect = image.width / image.height;
  24858. if (width == null && height != null) {
  24859. width = height * aspect;
  24860. }
  24861. else if (height == null && width != null) {
  24862. height = width / aspect;
  24863. }
  24864. else if (width == null && height == null) {
  24865. width = image.width;
  24866. height = image.height;
  24867. }
  24868. if (style.sWidth && style.sHeight) {
  24869. var sx = style.sx || 0;
  24870. var sy = style.sy || 0;
  24871. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24872. }
  24873. else if (style.sx && style.sy) {
  24874. var sx = style.sx;
  24875. var sy = style.sy;
  24876. var sWidth = width - sx;
  24877. var sHeight = height - sy;
  24878. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24879. }
  24880. else {
  24881. ctx.drawImage(image, x, y, width, height);
  24882. }
  24883. }
  24884. function brushText(ctx, el, style) {
  24885. var _a;
  24886. var text = style.text;
  24887. text != null && (text += '');
  24888. if (text) {
  24889. ctx.font = style.font || DEFAULT_FONT;
  24890. ctx.textAlign = style.textAlign;
  24891. ctx.textBaseline = style.textBaseline;
  24892. var lineDash = void 0;
  24893. var lineDashOffset = void 0;
  24894. if (ctx.setLineDash && style.lineDash) {
  24895. _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  24896. }
  24897. if (lineDash) {
  24898. ctx.setLineDash(lineDash);
  24899. ctx.lineDashOffset = lineDashOffset;
  24900. }
  24901. if (style.strokeFirst) {
  24902. if (styleHasStroke(style)) {
  24903. ctx.strokeText(text, style.x, style.y);
  24904. }
  24905. if (styleHasFill(style)) {
  24906. ctx.fillText(text, style.x, style.y);
  24907. }
  24908. }
  24909. else {
  24910. if (styleHasFill(style)) {
  24911. ctx.fillText(text, style.x, style.y);
  24912. }
  24913. if (styleHasStroke(style)) {
  24914. ctx.strokeText(text, style.x, style.y);
  24915. }
  24916. }
  24917. if (lineDash) {
  24918. ctx.setLineDash([]);
  24919. }
  24920. }
  24921. }
  24922. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24923. var STROKE_PROPS = [
  24924. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24925. ];
  24926. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24927. var styleChanged = false;
  24928. if (!forceSetAll) {
  24929. prevStyle = prevStyle || {};
  24930. if (style === prevStyle) {
  24931. return false;
  24932. }
  24933. }
  24934. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24935. flushPathDrawn(ctx, scope);
  24936. styleChanged = true;
  24937. var opacity = Math.max(Math.min(style.opacity, 1), 0);
  24938. ctx.globalAlpha = isNaN(opacity) ? DEFAULT_COMMON_STYLE.opacity : opacity;
  24939. }
  24940. if (forceSetAll || style.blend !== prevStyle.blend) {
  24941. if (!styleChanged) {
  24942. flushPathDrawn(ctx, scope);
  24943. styleChanged = true;
  24944. }
  24945. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24946. }
  24947. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24948. var propName = SHADOW_NUMBER_PROPS[i];
  24949. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24950. if (!styleChanged) {
  24951. flushPathDrawn(ctx, scope);
  24952. styleChanged = true;
  24953. }
  24954. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24955. }
  24956. }
  24957. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24958. if (!styleChanged) {
  24959. flushPathDrawn(ctx, scope);
  24960. styleChanged = true;
  24961. }
  24962. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24963. }
  24964. return styleChanged;
  24965. }
  24966. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24967. var style = getStyle(el, scope.inHover);
  24968. var prevStyle = forceSetAll
  24969. ? null
  24970. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24971. if (style === prevStyle) {
  24972. return false;
  24973. }
  24974. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24975. if (forceSetAll || style.fill !== prevStyle.fill) {
  24976. if (!styleChanged) {
  24977. flushPathDrawn(ctx, scope);
  24978. styleChanged = true;
  24979. }
  24980. isValidStrokeFillStyle(style.fill) && (ctx.fillStyle = style.fill);
  24981. }
  24982. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24983. if (!styleChanged) {
  24984. flushPathDrawn(ctx, scope);
  24985. styleChanged = true;
  24986. }
  24987. isValidStrokeFillStyle(style.stroke) && (ctx.strokeStyle = style.stroke);
  24988. }
  24989. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24990. if (!styleChanged) {
  24991. flushPathDrawn(ctx, scope);
  24992. styleChanged = true;
  24993. }
  24994. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24995. }
  24996. if (el.hasStroke()) {
  24997. var lineWidth = style.lineWidth;
  24998. var newLineWidth = lineWidth / ((style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1);
  24999. if (ctx.lineWidth !== newLineWidth) {
  25000. if (!styleChanged) {
  25001. flushPathDrawn(ctx, scope);
  25002. styleChanged = true;
  25003. }
  25004. ctx.lineWidth = newLineWidth;
  25005. }
  25006. }
  25007. for (var i = 0; i < STROKE_PROPS.length; i++) {
  25008. var prop = STROKE_PROPS[i];
  25009. var propName = prop[0];
  25010. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  25011. if (!styleChanged) {
  25012. flushPathDrawn(ctx, scope);
  25013. styleChanged = true;
  25014. }
  25015. ctx[propName] = style[propName] || prop[1];
  25016. }
  25017. }
  25018. return styleChanged;
  25019. }
  25020. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  25021. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  25022. }
  25023. function setContextTransform(ctx, el) {
  25024. var m = el.transform;
  25025. var dpr = ctx.dpr || 1;
  25026. if (m) {
  25027. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  25028. }
  25029. else {
  25030. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  25031. }
  25032. }
  25033. function updateClipStatus(clipPaths, ctx, scope) {
  25034. var allClipped = false;
  25035. for (var i = 0; i < clipPaths.length; i++) {
  25036. var clipPath = clipPaths[i];
  25037. allClipped = allClipped || clipPath.isZeroArea();
  25038. setContextTransform(ctx, clipPath);
  25039. ctx.beginPath();
  25040. clipPath.buildPath(ctx, clipPath.shape);
  25041. ctx.clip();
  25042. }
  25043. scope.allClipped = allClipped;
  25044. }
  25045. function isTransformChanged(m0, m1) {
  25046. if (m0 && m1) {
  25047. return m0[0] !== m1[0]
  25048. || m0[1] !== m1[1]
  25049. || m0[2] !== m1[2]
  25050. || m0[3] !== m1[3]
  25051. || m0[4] !== m1[4]
  25052. || m0[5] !== m1[5];
  25053. }
  25054. else if (!m0 && !m1) {
  25055. return false;
  25056. }
  25057. return true;
  25058. }
  25059. var DRAW_TYPE_PATH = 1;
  25060. var DRAW_TYPE_IMAGE = 2;
  25061. var DRAW_TYPE_TEXT = 3;
  25062. var DRAW_TYPE_INCREMENTAL = 4;
  25063. function canPathBatch(style) {
  25064. var hasFill = styleHasFill(style);
  25065. var hasStroke = styleHasStroke(style);
  25066. return !(style.lineDash
  25067. || !(+hasFill ^ +hasStroke)
  25068. || (hasFill && typeof style.fill !== 'string')
  25069. || (hasStroke && typeof style.stroke !== 'string')
  25070. || style.strokePercent < 1
  25071. || style.strokeOpacity < 1
  25072. || style.fillOpacity < 1);
  25073. }
  25074. function flushPathDrawn(ctx, scope) {
  25075. scope.batchFill && ctx.fill();
  25076. scope.batchStroke && ctx.stroke();
  25077. scope.batchFill = '';
  25078. scope.batchStroke = '';
  25079. }
  25080. function getStyle(el, inHover) {
  25081. return inHover ? (el.__hoverStyle || el.style) : el.style;
  25082. }
  25083. function brushSingle(ctx, el) {
  25084. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  25085. }
  25086. function brush(ctx, el, scope, isLast) {
  25087. var m = el.transform;
  25088. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  25089. el.__dirty &= ~REDRAW_BIT;
  25090. el.__isRendered = false;
  25091. return;
  25092. }
  25093. var clipPaths = el.__clipPaths;
  25094. var prevElClipPaths = scope.prevElClipPaths;
  25095. var forceSetTransform = false;
  25096. var forceSetStyle = false;
  25097. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  25098. if (prevElClipPaths && prevElClipPaths.length) {
  25099. flushPathDrawn(ctx, scope);
  25100. ctx.restore();
  25101. forceSetStyle = forceSetTransform = true;
  25102. scope.prevElClipPaths = null;
  25103. scope.allClipped = false;
  25104. scope.prevEl = null;
  25105. }
  25106. if (clipPaths && clipPaths.length) {
  25107. flushPathDrawn(ctx, scope);
  25108. ctx.save();
  25109. updateClipStatus(clipPaths, ctx, scope);
  25110. forceSetTransform = true;
  25111. }
  25112. scope.prevElClipPaths = clipPaths;
  25113. }
  25114. if (scope.allClipped) {
  25115. el.__isRendered = false;
  25116. return;
  25117. }
  25118. el.beforeBrush && el.beforeBrush();
  25119. el.innerBeforeBrush();
  25120. var prevEl = scope.prevEl;
  25121. if (!prevEl) {
  25122. forceSetStyle = forceSetTransform = true;
  25123. }
  25124. var canBatchPath = el instanceof Path
  25125. && el.autoBatch
  25126. && canPathBatch(el.style);
  25127. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  25128. flushPathDrawn(ctx, scope);
  25129. setContextTransform(ctx, el);
  25130. }
  25131. else if (!canBatchPath) {
  25132. flushPathDrawn(ctx, scope);
  25133. }
  25134. var style = getStyle(el, scope.inHover);
  25135. if (el instanceof Path) {
  25136. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  25137. forceSetStyle = true;
  25138. scope.lastDrawType = DRAW_TYPE_PATH;
  25139. }
  25140. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25141. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  25142. ctx.beginPath();
  25143. }
  25144. brushPath(ctx, el, style, canBatchPath);
  25145. if (canBatchPath) {
  25146. scope.batchFill = style.fill || '';
  25147. scope.batchStroke = style.stroke || '';
  25148. }
  25149. }
  25150. else {
  25151. if (el instanceof TSpan) {
  25152. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  25153. forceSetStyle = true;
  25154. scope.lastDrawType = DRAW_TYPE_TEXT;
  25155. }
  25156. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  25157. brushText(ctx, el, style);
  25158. }
  25159. else if (el instanceof ZRImage) {
  25160. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  25161. forceSetStyle = true;
  25162. scope.lastDrawType = DRAW_TYPE_IMAGE;
  25163. }
  25164. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  25165. brushImage(ctx, el, style);
  25166. }
  25167. else if (el.getTemporalDisplayables) {
  25168. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  25169. forceSetStyle = true;
  25170. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  25171. }
  25172. brushIncremental(ctx, el, scope);
  25173. }
  25174. }
  25175. if (canBatchPath && isLast) {
  25176. flushPathDrawn(ctx, scope);
  25177. }
  25178. el.innerAfterBrush();
  25179. el.afterBrush && el.afterBrush();
  25180. scope.prevEl = el;
  25181. el.__dirty = 0;
  25182. el.__isRendered = true;
  25183. }
  25184. function brushIncremental(ctx, el, scope) {
  25185. var displayables = el.getDisplayables();
  25186. var temporalDisplayables = el.getTemporalDisplayables();
  25187. ctx.save();
  25188. var innerScope = {
  25189. prevElClipPaths: null,
  25190. prevEl: null,
  25191. allClipped: false,
  25192. viewWidth: scope.viewWidth,
  25193. viewHeight: scope.viewHeight,
  25194. inHover: scope.inHover
  25195. };
  25196. var i;
  25197. var len;
  25198. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  25199. var displayable = displayables[i];
  25200. displayable.beforeBrush && displayable.beforeBrush();
  25201. displayable.innerBeforeBrush();
  25202. brush(ctx, displayable, innerScope, i === len - 1);
  25203. displayable.innerAfterBrush();
  25204. displayable.afterBrush && displayable.afterBrush();
  25205. innerScope.prevEl = displayable;
  25206. }
  25207. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  25208. var displayable = temporalDisplayables[i_1];
  25209. displayable.beforeBrush && displayable.beforeBrush();
  25210. displayable.innerBeforeBrush();
  25211. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  25212. displayable.innerAfterBrush();
  25213. displayable.afterBrush && displayable.afterBrush();
  25214. innerScope.prevEl = displayable;
  25215. }
  25216. el.clearTemporalDisplayables();
  25217. el.notClear = true;
  25218. ctx.restore();
  25219. }
  25220. var decalMap = new WeakMap();
  25221. var decalCache = new LRU(100);
  25222. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  25223. /**
  25224. * Create or update pattern image from decal options
  25225. *
  25226. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  25227. * @return {Pattern} pattern with generated image, null if no decal
  25228. */
  25229. function createOrUpdatePatternFromDecal(decalObject, api) {
  25230. if (decalObject === 'none') {
  25231. return null;
  25232. }
  25233. var dpr = api.getDevicePixelRatio();
  25234. var zr = api.getZr();
  25235. var isSVG = zr.painter.type === 'svg';
  25236. if (decalObject.dirty) {
  25237. decalMap["delete"](decalObject);
  25238. }
  25239. var oldPattern = decalMap.get(decalObject);
  25240. if (oldPattern) {
  25241. return oldPattern;
  25242. }
  25243. var decalOpt = defaults(decalObject, {
  25244. symbol: 'rect',
  25245. symbolSize: 1,
  25246. symbolKeepAspect: true,
  25247. color: 'rgba(0, 0, 0, 0.2)',
  25248. backgroundColor: null,
  25249. dashArrayX: 5,
  25250. dashArrayY: 5,
  25251. rotation: 0,
  25252. maxTileWidth: 512,
  25253. maxTileHeight: 512
  25254. });
  25255. if (decalOpt.backgroundColor === 'none') {
  25256. decalOpt.backgroundColor = null;
  25257. }
  25258. var pattern = {
  25259. repeat: 'repeat'
  25260. };
  25261. setPatternnSource(pattern);
  25262. pattern.rotation = decalOpt.rotation;
  25263. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  25264. decalMap.set(decalObject, pattern);
  25265. decalObject.dirty = false;
  25266. return pattern;
  25267. function setPatternnSource(pattern) {
  25268. var keys = [dpr];
  25269. var isValidKey = true;
  25270. for (var i = 0; i < decalKeys.length; ++i) {
  25271. var value = decalOpt[decalKeys[i]];
  25272. if (value != null && !isArray(value) && !isString(value) && !isNumber(value) && typeof value !== 'boolean') {
  25273. isValidKey = false;
  25274. break;
  25275. }
  25276. keys.push(value);
  25277. }
  25278. var cacheKey;
  25279. if (isValidKey) {
  25280. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  25281. var cache = decalCache.get(cacheKey);
  25282. if (cache) {
  25283. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  25284. }
  25285. }
  25286. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  25287. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  25288. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  25289. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  25290. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  25291. var canvas = !isSVG && platformApi.createCanvas();
  25292. var svgRoot = isSVG && {
  25293. tag: 'g',
  25294. attrs: {},
  25295. key: 'dcl',
  25296. children: []
  25297. };
  25298. var pSize = getPatternSize();
  25299. var ctx;
  25300. if (canvas) {
  25301. canvas.width = pSize.width * dpr;
  25302. canvas.height = pSize.height * dpr;
  25303. ctx = canvas.getContext('2d');
  25304. }
  25305. brushDecal();
  25306. if (isValidKey) {
  25307. decalCache.put(cacheKey, canvas || svgRoot);
  25308. }
  25309. pattern.image = canvas;
  25310. pattern.svgElement = svgRoot;
  25311. pattern.svgWidth = pSize.width;
  25312. pattern.svgHeight = pSize.height;
  25313. /**
  25314. * Get minimum length that can make a repeatable pattern.
  25315. *
  25316. * @return {Object} pattern width and height
  25317. */
  25318. function getPatternSize() {
  25319. /**
  25320. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  25321. * |--- --- --- --- --- ...
  25322. * |-- -- -- -- -- -- -- -- ...
  25323. * |--- --- --- --- --- ...
  25324. * |-- -- -- -- -- -- -- -- ...
  25325. * So the minimum length of X is 15,
  25326. * which is the least common multiple of `3 + 2` and `2 + 1`
  25327. * |--- --- --- |--- --- ...
  25328. * |-- -- -- -- -- |-- -- -- ...
  25329. */
  25330. var width = 1;
  25331. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  25332. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  25333. }
  25334. var symbolRepeats = 1;
  25335. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  25336. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  25337. }
  25338. width *= symbolRepeats;
  25339. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  25340. if ("development" !== 'production') {
  25341. var warn = function (attrName) {
  25342. /* eslint-disable-next-line */
  25343. 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.");
  25344. };
  25345. if (width > decalOpt.maxTileWidth) {
  25346. warn('maxTileWidth');
  25347. }
  25348. if (height > decalOpt.maxTileHeight) {
  25349. warn('maxTileHeight');
  25350. }
  25351. }
  25352. return {
  25353. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  25354. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  25355. };
  25356. }
  25357. function brushDecal() {
  25358. if (ctx) {
  25359. ctx.clearRect(0, 0, canvas.width, canvas.height);
  25360. if (decalOpt.backgroundColor) {
  25361. ctx.fillStyle = decalOpt.backgroundColor;
  25362. ctx.fillRect(0, 0, canvas.width, canvas.height);
  25363. }
  25364. }
  25365. var ySum = 0;
  25366. for (var i = 0; i < dashArrayY.length; ++i) {
  25367. ySum += dashArrayY[i];
  25368. }
  25369. if (ySum <= 0) {
  25370. // dashArrayY is 0, draw nothing
  25371. return;
  25372. }
  25373. var y = -lineBlockLengthY;
  25374. var yId = 0;
  25375. var yIdTotal = 0;
  25376. var xId0 = 0;
  25377. while (y < pSize.height) {
  25378. if (yId % 2 === 0) {
  25379. var symbolYId = yIdTotal / 2 % symbolArray.length;
  25380. var x = 0;
  25381. var xId1 = 0;
  25382. var xId1Total = 0;
  25383. while (x < pSize.width * 2) {
  25384. var xSum = 0;
  25385. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  25386. xSum += dashArrayX[xId0][i];
  25387. }
  25388. if (xSum <= 0) {
  25389. // Skip empty line
  25390. break;
  25391. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  25392. if (xId1 % 2 === 0) {
  25393. var size = (1 - decalOpt.symbolSize) * 0.5;
  25394. var left = x + dashArrayX[xId0][xId1] * size;
  25395. var top_1 = y + dashArrayY[yId] * size;
  25396. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  25397. var height = dashArrayY[yId] * decalOpt.symbolSize;
  25398. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  25399. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  25400. }
  25401. x += dashArrayX[xId0][xId1];
  25402. ++xId1Total;
  25403. ++xId1;
  25404. if (xId1 === dashArrayX[xId0].length) {
  25405. xId1 = 0;
  25406. }
  25407. }
  25408. ++xId0;
  25409. if (xId0 === dashArrayX.length) {
  25410. xId0 = 0;
  25411. }
  25412. }
  25413. y += dashArrayY[yId];
  25414. ++yIdTotal;
  25415. ++yId;
  25416. if (yId === dashArrayY.length) {
  25417. yId = 0;
  25418. }
  25419. }
  25420. function brushSymbol(x, y, width, height, symbolType) {
  25421. var scale = isSVG ? 1 : dpr;
  25422. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  25423. if (isSVG) {
  25424. var symbolVNode = zr.painter.renderOneToVNode(symbol);
  25425. if (symbolVNode) {
  25426. svgRoot.children.push(symbolVNode);
  25427. }
  25428. } else {
  25429. // Paint to canvas for all other renderers.
  25430. brushSingle(ctx, symbol);
  25431. }
  25432. }
  25433. }
  25434. }
  25435. }
  25436. /**
  25437. * Convert symbol array into normalized array
  25438. *
  25439. * @param {string | (string | string[])[]} symbol symbol input
  25440. * @return {string[][]} normolized symbol array
  25441. */
  25442. function normalizeSymbolArray(symbol) {
  25443. if (!symbol || symbol.length === 0) {
  25444. return [['rect']];
  25445. }
  25446. if (isString(symbol)) {
  25447. return [[symbol]];
  25448. }
  25449. var isAllString = true;
  25450. for (var i = 0; i < symbol.length; ++i) {
  25451. if (!isString(symbol[i])) {
  25452. isAllString = false;
  25453. break;
  25454. }
  25455. }
  25456. if (isAllString) {
  25457. return normalizeSymbolArray([symbol]);
  25458. }
  25459. var result = [];
  25460. for (var i = 0; i < symbol.length; ++i) {
  25461. if (isString(symbol[i])) {
  25462. result.push([symbol[i]]);
  25463. } else {
  25464. result.push(symbol[i]);
  25465. }
  25466. }
  25467. return result;
  25468. }
  25469. /**
  25470. * Convert dash input into dashArray
  25471. *
  25472. * @param {DecalDashArrayX} dash dash input
  25473. * @return {number[][]} normolized dash array
  25474. */
  25475. function normalizeDashArrayX(dash) {
  25476. if (!dash || dash.length === 0) {
  25477. return [[0, 0]];
  25478. }
  25479. if (isNumber(dash)) {
  25480. var dashValue = Math.ceil(dash);
  25481. return [[dashValue, dashValue]];
  25482. }
  25483. /**
  25484. * [20, 5] should be normalized into [[20, 5]],
  25485. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  25486. */
  25487. var isAllNumber = true;
  25488. for (var i = 0; i < dash.length; ++i) {
  25489. if (!isNumber(dash[i])) {
  25490. isAllNumber = false;
  25491. break;
  25492. }
  25493. }
  25494. if (isAllNumber) {
  25495. return normalizeDashArrayX([dash]);
  25496. }
  25497. var result = [];
  25498. for (var i = 0; i < dash.length; ++i) {
  25499. if (isNumber(dash[i])) {
  25500. var dashValue = Math.ceil(dash[i]);
  25501. result.push([dashValue, dashValue]);
  25502. } else {
  25503. var dashValue = map(dash[i], function (n) {
  25504. return Math.ceil(n);
  25505. });
  25506. if (dashValue.length % 2 === 1) {
  25507. // [4, 2, 1] means |---- - -- |---- - -- |
  25508. // so normalize it to be [4, 2, 1, 4, 2, 1]
  25509. result.push(dashValue.concat(dashValue));
  25510. } else {
  25511. result.push(dashValue);
  25512. }
  25513. }
  25514. }
  25515. return result;
  25516. }
  25517. /**
  25518. * Convert dash input into dashArray
  25519. *
  25520. * @param {DecalDashArrayY} dash dash input
  25521. * @return {number[]} normolized dash array
  25522. */
  25523. function normalizeDashArrayY(dash) {
  25524. if (!dash || typeof dash === 'object' && dash.length === 0) {
  25525. return [0, 0];
  25526. }
  25527. if (isNumber(dash)) {
  25528. var dashValue_1 = Math.ceil(dash);
  25529. return [dashValue_1, dashValue_1];
  25530. }
  25531. var dashValue = map(dash, function (n) {
  25532. return Math.ceil(n);
  25533. });
  25534. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  25535. }
  25536. /**
  25537. * Get block length of each line. A block is the length of dash line and space.
  25538. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  25539. * that, so the block length of this line is 5.
  25540. *
  25541. * @param {number[][]} dash dash array of X or Y
  25542. * @return {number[]} block length of each line
  25543. */
  25544. function getLineBlockLengthX(dash) {
  25545. return map(dash, function (line) {
  25546. return getLineBlockLengthY(line);
  25547. });
  25548. }
  25549. function getLineBlockLengthY(dash) {
  25550. var blockLength = 0;
  25551. for (var i = 0; i < dash.length; ++i) {
  25552. blockLength += dash[i];
  25553. }
  25554. if (dash.length % 2 === 1) {
  25555. // [4, 2, 1] means |---- - -- |---- - -- |
  25556. // So total length is (4 + 2 + 1) * 2
  25557. return blockLength * 2;
  25558. }
  25559. return blockLength;
  25560. }
  25561. function decalVisual(ecModel, api) {
  25562. ecModel.eachRawSeries(function (seriesModel) {
  25563. if (ecModel.isSeriesFiltered(seriesModel)) {
  25564. return;
  25565. }
  25566. var data = seriesModel.getData();
  25567. if (data.hasItemVisual()) {
  25568. data.each(function (idx) {
  25569. var decal = data.getItemVisual(idx, 'decal');
  25570. if (decal) {
  25571. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  25572. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  25573. }
  25574. });
  25575. }
  25576. var decal = data.getVisual('decal');
  25577. if (decal) {
  25578. var style = data.getVisual('style');
  25579. style.decal = createOrUpdatePatternFromDecal(decal, api);
  25580. }
  25581. });
  25582. }
  25583. var lifecycle = new Eventful();
  25584. // The implementations will be registered when installing the component.
  25585. // Avoid these code being bundled to the core module.
  25586. var implsStore = {}; // TODO Type
  25587. function registerImpl(name, impl) {
  25588. if ("development" !== 'production') {
  25589. if (implsStore[name]) {
  25590. error("Already has an implementation of " + name + ".");
  25591. }
  25592. }
  25593. implsStore[name] = impl;
  25594. }
  25595. function getImpl(name) {
  25596. if ("development" !== 'production') {
  25597. if (!implsStore[name]) {
  25598. error("Implementation of " + name + " doesn't exists.");
  25599. }
  25600. }
  25601. return implsStore[name];
  25602. }
  25603. var version$1 = '5.4.3';
  25604. var dependencies = {
  25605. zrender: '5.4.4'
  25606. };
  25607. var TEST_FRAME_REMAIN_TIME = 1;
  25608. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  25609. // So data stack stage should be in front of data processing stage.
  25610. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  25611. // put at the beginning of data processing.
  25612. var PRIORITY_PROCESSOR_FILTER = 1000;
  25613. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  25614. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  25615. var PRIORITY_VISUAL_LAYOUT = 1000;
  25616. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  25617. var PRIORITY_VISUAL_GLOBAL = 2000;
  25618. var PRIORITY_VISUAL_CHART = 3000;
  25619. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  25620. // overwrite the viusal result of component (like `visualMap`)
  25621. // using data item specific setting (like itemStyle.xxx on data item)
  25622. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  25623. // visual result like `symbolSize`.
  25624. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  25625. var PRIORITY_VISUAL_BRUSH = 5000;
  25626. var PRIORITY_VISUAL_ARIA = 6000;
  25627. var PRIORITY_VISUAL_DECAL = 7000;
  25628. var PRIORITY = {
  25629. PROCESSOR: {
  25630. FILTER: PRIORITY_PROCESSOR_FILTER,
  25631. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25632. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25633. },
  25634. VISUAL: {
  25635. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25636. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25637. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25638. CHART: PRIORITY_VISUAL_CHART,
  25639. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25640. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25641. BRUSH: PRIORITY_VISUAL_BRUSH,
  25642. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25643. ARIA: PRIORITY_VISUAL_ARIA,
  25644. DECAL: PRIORITY_VISUAL_DECAL
  25645. }
  25646. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25647. // where they must not be invoked nestedly, except the only case: invoke
  25648. // dispatchAction with updateMethod "none" in main process.
  25649. // This flag is used to carry out this rule.
  25650. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25651. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25652. var PENDING_UPDATE = '__pendingUpdate';
  25653. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25654. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25655. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25656. var CONNECT_STATUS_PENDING = 0;
  25657. var CONNECT_STATUS_UPDATING = 1;
  25658. var CONNECT_STATUS_UPDATED = 2;
  25659. function createRegisterEventWithLowercaseECharts(method) {
  25660. return function () {
  25661. var args = [];
  25662. for (var _i = 0; _i < arguments.length; _i++) {
  25663. args[_i] = arguments[_i];
  25664. }
  25665. if (this.isDisposed()) {
  25666. disposedWarning(this.id);
  25667. return;
  25668. }
  25669. return toLowercaseNameAndCallEventful(this, method, args);
  25670. };
  25671. }
  25672. function createRegisterEventWithLowercaseMessageCenter(method) {
  25673. return function () {
  25674. var args = [];
  25675. for (var _i = 0; _i < arguments.length; _i++) {
  25676. args[_i] = arguments[_i];
  25677. }
  25678. return toLowercaseNameAndCallEventful(this, method, args);
  25679. };
  25680. }
  25681. function toLowercaseNameAndCallEventful(host, method, args) {
  25682. // `args[0]` is event name. Event name is all lowercase.
  25683. args[0] = args[0] && args[0].toLowerCase();
  25684. return Eventful.prototype[method].apply(host, args);
  25685. }
  25686. var MessageCenter =
  25687. /** @class */
  25688. function (_super) {
  25689. __extends(MessageCenter, _super);
  25690. function MessageCenter() {
  25691. return _super !== null && _super.apply(this, arguments) || this;
  25692. }
  25693. return MessageCenter;
  25694. }(Eventful);
  25695. var messageCenterProto = MessageCenter.prototype;
  25696. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25697. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25698. // Internal method names for class ECharts
  25699. // ---------------------------------------
  25700. var prepare;
  25701. var prepareView;
  25702. var updateDirectly;
  25703. var updateMethods;
  25704. var doConvertPixel;
  25705. var updateStreamModes;
  25706. var doDispatchAction;
  25707. var flushPendingActions;
  25708. var triggerUpdatedEvent;
  25709. var bindRenderedEvent;
  25710. var bindMouseEvent;
  25711. var render;
  25712. var renderComponents;
  25713. var renderSeries;
  25714. var createExtensionAPI;
  25715. var enableConnect;
  25716. var markStatusToUpdate;
  25717. var applyChangedStates;
  25718. var ECharts =
  25719. /** @class */
  25720. function (_super) {
  25721. __extends(ECharts, _super);
  25722. function ECharts(dom, // Theme name or themeOption.
  25723. theme, opts) {
  25724. var _this = _super.call(this, new ECEventProcessor()) || this;
  25725. _this._chartsViews = [];
  25726. _this._chartsMap = {};
  25727. _this._componentsViews = [];
  25728. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25729. _this._pendingActions = [];
  25730. opts = opts || {}; // Get theme by name
  25731. if (isString(theme)) {
  25732. theme = themeStorage[theme];
  25733. }
  25734. _this._dom = dom;
  25735. var defaultRenderer = 'canvas';
  25736. var defaultCoarsePointer = 'auto';
  25737. var defaultUseDirtyRect = false;
  25738. if ("development" !== 'production') {
  25739. var root =
  25740. /* eslint-disable-next-line */
  25741. env.hasGlobalWindow ? window : global;
  25742. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25743. defaultCoarsePointer = retrieve2(root.__ECHARTS__DEFAULT__COARSE_POINTER, defaultCoarsePointer);
  25744. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25745. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25746. }
  25747. var zr = _this._zr = init(dom, {
  25748. renderer: opts.renderer || defaultRenderer,
  25749. devicePixelRatio: opts.devicePixelRatio,
  25750. width: opts.width,
  25751. height: opts.height,
  25752. ssr: opts.ssr,
  25753. useDirtyRect: retrieve2(opts.useDirtyRect, defaultUseDirtyRect),
  25754. useCoarsePointer: retrieve2(opts.useCoarsePointer, defaultCoarsePointer),
  25755. pointerSize: opts.pointerSize
  25756. });
  25757. _this._ssr = opts.ssr; // Expect 60 fps.
  25758. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25759. theme = clone(theme);
  25760. theme && globalBackwardCompat(theme, true);
  25761. _this._theme = theme;
  25762. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25763. _this._coordSysMgr = new CoordinateSystemManager();
  25764. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25765. function prioritySortFunc(a, b) {
  25766. return a.__prio - b.__prio;
  25767. }
  25768. sort(visualFuncs, prioritySortFunc);
  25769. sort(dataProcessorFuncs, prioritySortFunc);
  25770. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25771. _this._messageCenter = new MessageCenter(); // Init mouse events
  25772. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25773. _this.resize = bind(_this.resize, _this);
  25774. zr.animation.on('frame', _this._onframe, _this);
  25775. bindRenderedEvent(zr, _this);
  25776. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25777. setAsPrimitive(_this);
  25778. return _this;
  25779. }
  25780. ECharts.prototype._onframe = function () {
  25781. if (this._disposed) {
  25782. return;
  25783. }
  25784. applyChangedStates(this);
  25785. var scheduler = this._scheduler; // Lazy update
  25786. if (this[PENDING_UPDATE]) {
  25787. var silent = this[PENDING_UPDATE].silent;
  25788. this[IN_MAIN_PROCESS_KEY] = true;
  25789. try {
  25790. prepare(this);
  25791. updateMethods.update.call(this, null, this[PENDING_UPDATE].updateParams);
  25792. } catch (e) {
  25793. this[IN_MAIN_PROCESS_KEY] = false;
  25794. this[PENDING_UPDATE] = null;
  25795. throw e;
  25796. } // At present, in each frame, zrender performs:
  25797. // (1) animation step forward.
  25798. // (2) trigger('frame') (where this `_onframe` is called)
  25799. // (3) zrender flush (render).
  25800. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25801. // will render the final state of the elements before the real animation started.
  25802. this._zr.flush();
  25803. this[IN_MAIN_PROCESS_KEY] = false;
  25804. this[PENDING_UPDATE] = null;
  25805. flushPendingActions.call(this, silent);
  25806. triggerUpdatedEvent.call(this, silent);
  25807. } // Avoid do both lazy update and progress in one frame.
  25808. else if (scheduler.unfinished) {
  25809. // Stream progress.
  25810. var remainTime = TEST_FRAME_REMAIN_TIME;
  25811. var ecModel = this._model;
  25812. var api = this._api;
  25813. scheduler.unfinished = false;
  25814. do {
  25815. var startTime = +new Date();
  25816. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25817. scheduler.performDataProcessorTasks(ecModel);
  25818. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25819. // each frame is not a good user experience. So we follow the rule that
  25820. // the extent of the coordinate system is determined in the first frame (the
  25821. // frame is executed immediately after task reset.
  25822. // this._coordSysMgr.update(ecModel, api);
  25823. // console.log('--- ec frame visual ---', remainTime);
  25824. scheduler.performVisualTasks(ecModel);
  25825. renderSeries(this, this._model, api, 'remain', {});
  25826. remainTime -= +new Date() - startTime;
  25827. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25828. if (!scheduler.unfinished) {
  25829. this._zr.flush();
  25830. } // Else, zr flushing be ensue within the same frame,
  25831. // because zr flushing is after onframe event.
  25832. }
  25833. };
  25834. ECharts.prototype.getDom = function () {
  25835. return this._dom;
  25836. };
  25837. ECharts.prototype.getId = function () {
  25838. return this.id;
  25839. };
  25840. ECharts.prototype.getZr = function () {
  25841. return this._zr;
  25842. };
  25843. ECharts.prototype.isSSR = function () {
  25844. return this._ssr;
  25845. };
  25846. /* eslint-disable-next-line */
  25847. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25848. if (this[IN_MAIN_PROCESS_KEY]) {
  25849. if ("development" !== 'production') {
  25850. error('`setOption` should not be called during main process.');
  25851. }
  25852. return;
  25853. }
  25854. if (this._disposed) {
  25855. disposedWarning(this.id);
  25856. return;
  25857. }
  25858. var silent;
  25859. var replaceMerge;
  25860. var transitionOpt;
  25861. if (isObject(notMerge)) {
  25862. lazyUpdate = notMerge.lazyUpdate;
  25863. silent = notMerge.silent;
  25864. replaceMerge = notMerge.replaceMerge;
  25865. transitionOpt = notMerge.transition;
  25866. notMerge = notMerge.notMerge;
  25867. }
  25868. this[IN_MAIN_PROCESS_KEY] = true;
  25869. if (!this._model || notMerge) {
  25870. var optionManager = new OptionManager(this._api);
  25871. var theme = this._theme;
  25872. var ecModel = this._model = new GlobalModel();
  25873. ecModel.scheduler = this._scheduler;
  25874. ecModel.ssr = this._ssr;
  25875. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25876. }
  25877. this._model.setOption(option, {
  25878. replaceMerge: replaceMerge
  25879. }, optionPreprocessorFuncs);
  25880. var updateParams = {
  25881. seriesTransition: transitionOpt,
  25882. optionChanged: true
  25883. };
  25884. if (lazyUpdate) {
  25885. this[PENDING_UPDATE] = {
  25886. silent: silent,
  25887. updateParams: updateParams
  25888. };
  25889. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25890. // It should wake it up to make sure zrender start to render at the next frame.
  25891. this.getZr().wakeUp();
  25892. } else {
  25893. try {
  25894. prepare(this);
  25895. updateMethods.update.call(this, null, updateParams);
  25896. } catch (e) {
  25897. this[PENDING_UPDATE] = null;
  25898. this[IN_MAIN_PROCESS_KEY] = false;
  25899. throw e;
  25900. } // Ensure zr refresh sychronously, and then pixel in canvas can be
  25901. // fetched after `setOption`.
  25902. if (!this._ssr) {
  25903. // not use flush when using ssr mode.
  25904. this._zr.flush();
  25905. }
  25906. this[PENDING_UPDATE] = null;
  25907. this[IN_MAIN_PROCESS_KEY] = false;
  25908. flushPendingActions.call(this, silent);
  25909. triggerUpdatedEvent.call(this, silent);
  25910. }
  25911. };
  25912. /**
  25913. * @deprecated
  25914. */
  25915. ECharts.prototype.setTheme = function () {
  25916. deprecateLog('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25917. }; // We don't want developers to use getModel directly.
  25918. ECharts.prototype.getModel = function () {
  25919. return this._model;
  25920. };
  25921. ECharts.prototype.getOption = function () {
  25922. return this._model && this._model.getOption();
  25923. };
  25924. ECharts.prototype.getWidth = function () {
  25925. return this._zr.getWidth();
  25926. };
  25927. ECharts.prototype.getHeight = function () {
  25928. return this._zr.getHeight();
  25929. };
  25930. ECharts.prototype.getDevicePixelRatio = function () {
  25931. return this._zr.painter.dpr
  25932. /* eslint-disable-next-line */
  25933. || env.hasGlobalWindow && window.devicePixelRatio || 1;
  25934. };
  25935. /**
  25936. * Get canvas which has all thing rendered
  25937. * @deprecated Use renderToCanvas instead.
  25938. */
  25939. ECharts.prototype.getRenderedCanvas = function (opts) {
  25940. if ("development" !== 'production') {
  25941. deprecateReplaceLog('getRenderedCanvas', 'renderToCanvas');
  25942. }
  25943. return this.renderToCanvas(opts);
  25944. };
  25945. ECharts.prototype.renderToCanvas = function (opts) {
  25946. opts = opts || {};
  25947. var painter = this._zr.painter;
  25948. if ("development" !== 'production') {
  25949. if (painter.type !== 'canvas') {
  25950. throw new Error('renderToCanvas can only be used in the canvas renderer.');
  25951. }
  25952. }
  25953. return painter.getRenderedCanvas({
  25954. backgroundColor: opts.backgroundColor || this._model.get('backgroundColor'),
  25955. pixelRatio: opts.pixelRatio || this.getDevicePixelRatio()
  25956. });
  25957. };
  25958. ECharts.prototype.renderToSVGString = function (opts) {
  25959. opts = opts || {};
  25960. var painter = this._zr.painter;
  25961. if ("development" !== 'production') {
  25962. if (painter.type !== 'svg') {
  25963. throw new Error('renderToSVGString can only be used in the svg renderer.');
  25964. }
  25965. }
  25966. return painter.renderToString({
  25967. useViewBox: opts.useViewBox
  25968. });
  25969. };
  25970. /**
  25971. * Get svg data url
  25972. */
  25973. ECharts.prototype.getSvgDataURL = function () {
  25974. if (!env.svgSupported) {
  25975. return;
  25976. }
  25977. var zr = this._zr;
  25978. var list = zr.storage.getDisplayList(); // Stop animations
  25979. each(list, function (el) {
  25980. el.stopAnimation(null, true);
  25981. });
  25982. return zr.painter.toDataURL();
  25983. };
  25984. ECharts.prototype.getDataURL = function (opts) {
  25985. if (this._disposed) {
  25986. disposedWarning(this.id);
  25987. return;
  25988. }
  25989. opts = opts || {};
  25990. var excludeComponents = opts.excludeComponents;
  25991. var ecModel = this._model;
  25992. var excludesComponentViews = [];
  25993. var self = this;
  25994. each(excludeComponents, function (componentType) {
  25995. ecModel.eachComponent({
  25996. mainType: componentType
  25997. }, function (component) {
  25998. var view = self._componentsMap[component.__viewId];
  25999. if (!view.group.ignore) {
  26000. excludesComponentViews.push(view);
  26001. view.group.ignore = true;
  26002. }
  26003. });
  26004. });
  26005. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.renderToCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  26006. each(excludesComponentViews, function (view) {
  26007. view.group.ignore = false;
  26008. });
  26009. return url;
  26010. };
  26011. ECharts.prototype.getConnectedDataURL = function (opts) {
  26012. if (this._disposed) {
  26013. disposedWarning(this.id);
  26014. return;
  26015. }
  26016. var isSvg = opts.type === 'svg';
  26017. var groupId = this.group;
  26018. var mathMin = Math.min;
  26019. var mathMax = Math.max;
  26020. var MAX_NUMBER = Infinity;
  26021. if (connectedGroups[groupId]) {
  26022. var left_1 = MAX_NUMBER;
  26023. var top_1 = MAX_NUMBER;
  26024. var right_1 = -MAX_NUMBER;
  26025. var bottom_1 = -MAX_NUMBER;
  26026. var canvasList_1 = [];
  26027. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  26028. each(instances$1, function (chart, id) {
  26029. if (chart.group === groupId) {
  26030. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.renderToCanvas(clone(opts));
  26031. var boundingRect = chart.getDom().getBoundingClientRect();
  26032. left_1 = mathMin(boundingRect.left, left_1);
  26033. top_1 = mathMin(boundingRect.top, top_1);
  26034. right_1 = mathMax(boundingRect.right, right_1);
  26035. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  26036. canvasList_1.push({
  26037. dom: canvas,
  26038. left: boundingRect.left,
  26039. top: boundingRect.top
  26040. });
  26041. }
  26042. });
  26043. left_1 *= dpr_1;
  26044. top_1 *= dpr_1;
  26045. right_1 *= dpr_1;
  26046. bottom_1 *= dpr_1;
  26047. var width = right_1 - left_1;
  26048. var height = bottom_1 - top_1;
  26049. var targetCanvas = platformApi.createCanvas();
  26050. var zr_1 = init(targetCanvas, {
  26051. renderer: isSvg ? 'svg' : 'canvas'
  26052. });
  26053. zr_1.resize({
  26054. width: width,
  26055. height: height
  26056. });
  26057. if (isSvg) {
  26058. var content_1 = '';
  26059. each(canvasList_1, function (item) {
  26060. var x = item.left - left_1;
  26061. var y = item.top - top_1;
  26062. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  26063. });
  26064. zr_1.painter.getSvgRoot().innerHTML = content_1;
  26065. if (opts.connectedBackgroundColor) {
  26066. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  26067. }
  26068. zr_1.refreshImmediately();
  26069. return zr_1.painter.toDataURL();
  26070. } else {
  26071. // Background between the charts
  26072. if (opts.connectedBackgroundColor) {
  26073. zr_1.add(new Rect({
  26074. shape: {
  26075. x: 0,
  26076. y: 0,
  26077. width: width,
  26078. height: height
  26079. },
  26080. style: {
  26081. fill: opts.connectedBackgroundColor
  26082. }
  26083. }));
  26084. }
  26085. each(canvasList_1, function (item) {
  26086. var img = new ZRImage({
  26087. style: {
  26088. x: item.left * dpr_1 - left_1,
  26089. y: item.top * dpr_1 - top_1,
  26090. image: item.dom
  26091. }
  26092. });
  26093. zr_1.add(img);
  26094. });
  26095. zr_1.refreshImmediately();
  26096. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  26097. }
  26098. } else {
  26099. return this.getDataURL(opts);
  26100. }
  26101. };
  26102. ECharts.prototype.convertToPixel = function (finder, value) {
  26103. return doConvertPixel(this, 'convertToPixel', finder, value);
  26104. };
  26105. ECharts.prototype.convertFromPixel = function (finder, value) {
  26106. return doConvertPixel(this, 'convertFromPixel', finder, value);
  26107. };
  26108. /**
  26109. * Is the specified coordinate systems or components contain the given pixel point.
  26110. * @param {Array|number} value
  26111. * @return {boolean} result
  26112. */
  26113. ECharts.prototype.containPixel = function (finder, value) {
  26114. if (this._disposed) {
  26115. disposedWarning(this.id);
  26116. return;
  26117. }
  26118. var ecModel = this._model;
  26119. var result;
  26120. var findResult = parseFinder(ecModel, finder);
  26121. each(findResult, function (models, key) {
  26122. key.indexOf('Models') >= 0 && each(models, function (model) {
  26123. var coordSys = model.coordinateSystem;
  26124. if (coordSys && coordSys.containPoint) {
  26125. result = result || !!coordSys.containPoint(value);
  26126. } else if (key === 'seriesModels') {
  26127. var view = this._chartsMap[model.__viewId];
  26128. if (view && view.containPoint) {
  26129. result = result || view.containPoint(value, model);
  26130. } else {
  26131. if ("development" !== 'production') {
  26132. warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  26133. }
  26134. }
  26135. } else {
  26136. if ("development" !== 'production') {
  26137. warn(key + ': containPoint is not supported');
  26138. }
  26139. }
  26140. }, this);
  26141. }, this);
  26142. return !!result;
  26143. };
  26144. /**
  26145. * Get visual from series or data.
  26146. * @param finder
  26147. * If string, e.g., 'series', means {seriesIndex: 0}.
  26148. * If Object, could contain some of these properties below:
  26149. * {
  26150. * seriesIndex / seriesId / seriesName,
  26151. * dataIndex / dataIndexInside
  26152. * }
  26153. * If dataIndex is not specified, series visual will be fetched,
  26154. * but not data item visual.
  26155. * If all of seriesIndex, seriesId, seriesName are not specified,
  26156. * visual will be fetched from first series.
  26157. * @param visualType 'color', 'symbol', 'symbolSize'
  26158. */
  26159. ECharts.prototype.getVisual = function (finder, visualType) {
  26160. var ecModel = this._model;
  26161. var parsedFinder = parseFinder(ecModel, finder, {
  26162. defaultMainType: 'series'
  26163. });
  26164. var seriesModel = parsedFinder.seriesModel;
  26165. if ("development" !== 'production') {
  26166. if (!seriesModel) {
  26167. warn('There is no specified series model');
  26168. }
  26169. }
  26170. var data = seriesModel.getData();
  26171. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  26172. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  26173. };
  26174. /**
  26175. * Get view of corresponding component model
  26176. */
  26177. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  26178. return this._componentsMap[componentModel.__viewId];
  26179. };
  26180. /**
  26181. * Get view of corresponding series model
  26182. */
  26183. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  26184. return this._chartsMap[seriesModel.__viewId];
  26185. };
  26186. ECharts.prototype._initEvents = function () {
  26187. var _this = this;
  26188. each(MOUSE_EVENT_NAMES, function (eveName) {
  26189. var handler = function (e) {
  26190. var ecModel = _this.getModel();
  26191. var el = e.target;
  26192. var params;
  26193. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  26194. if (isGlobalOut) {
  26195. params = {};
  26196. } else {
  26197. el && findEventDispatcher(el, function (parent) {
  26198. var ecData = getECData(parent);
  26199. if (ecData && ecData.dataIndex != null) {
  26200. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  26201. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType, el) || {};
  26202. return true;
  26203. } // If element has custom eventData of components
  26204. else if (ecData.eventData) {
  26205. params = extend({}, ecData.eventData);
  26206. return true;
  26207. }
  26208. }, true);
  26209. } // Contract: if params prepared in mouse event,
  26210. // these properties must be specified:
  26211. // {
  26212. // componentType: string (component main type)
  26213. // componentIndex: number
  26214. // }
  26215. // Otherwise event query can not work.
  26216. if (params) {
  26217. var componentType = params.componentType;
  26218. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  26219. // markLine/markPoint/markArea, the componentType is
  26220. // 'markLine'/'markPoint'/'markArea', but we should better
  26221. // enable them to be queried by seriesIndex, since their
  26222. // option is set in each series.
  26223. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  26224. componentType = 'series';
  26225. componentIndex = params.seriesIndex;
  26226. }
  26227. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  26228. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  26229. if ("development" !== 'production') {
  26230. // `event.componentType` and `event[componentTpype + 'Index']` must not
  26231. // be missed, otherwise there is no way to distinguish source component.
  26232. // See `dataFormat.getDataParams`.
  26233. if (!isGlobalOut && !(model && view)) {
  26234. warn('model or view can not be found by params');
  26235. }
  26236. }
  26237. params.event = e;
  26238. params.type = eveName;
  26239. _this._$eventProcessor.eventInfo = {
  26240. targetEl: el,
  26241. packedEvent: params,
  26242. model: model,
  26243. view: view
  26244. };
  26245. _this.trigger(eveName, params);
  26246. }
  26247. }; // Consider that some component (like tooltip, brush, ...)
  26248. // register zr event handler, but user event handler might
  26249. // do anything, such as call `setOption` or `dispatchAction`,
  26250. // which probably update any of the content and probably
  26251. // cause problem if it is called previous other inner handlers.
  26252. handler.zrEventfulCallAtLast = true;
  26253. _this._zr.on(eveName, handler, _this);
  26254. });
  26255. each(eventActionMap, function (actionType, eventType) {
  26256. _this._messageCenter.on(eventType, function (event) {
  26257. this.trigger(eventType, event);
  26258. }, _this);
  26259. }); // Extra events
  26260. // TODO register?
  26261. each(['selectchanged'], function (eventType) {
  26262. _this._messageCenter.on(eventType, function (event) {
  26263. this.trigger(eventType, event);
  26264. }, _this);
  26265. });
  26266. handleLegacySelectEvents(this._messageCenter, this, this._api);
  26267. };
  26268. ECharts.prototype.isDisposed = function () {
  26269. return this._disposed;
  26270. };
  26271. ECharts.prototype.clear = function () {
  26272. if (this._disposed) {
  26273. disposedWarning(this.id);
  26274. return;
  26275. }
  26276. this.setOption({
  26277. series: []
  26278. }, true);
  26279. };
  26280. ECharts.prototype.dispose = function () {
  26281. if (this._disposed) {
  26282. disposedWarning(this.id);
  26283. return;
  26284. }
  26285. this._disposed = true;
  26286. var dom = this.getDom();
  26287. if (dom) {
  26288. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  26289. }
  26290. var chart = this;
  26291. var api = chart._api;
  26292. var ecModel = chart._model;
  26293. each(chart._componentsViews, function (component) {
  26294. component.dispose(ecModel, api);
  26295. });
  26296. each(chart._chartsViews, function (chart) {
  26297. chart.dispose(ecModel, api);
  26298. }); // Dispose after all views disposed
  26299. chart._zr.dispose(); // Set properties to null.
  26300. // To reduce the memory cost in case the top code still holds this instance unexpectedly.
  26301. 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;
  26302. delete instances$1[chart.id];
  26303. };
  26304. /**
  26305. * Resize the chart
  26306. */
  26307. ECharts.prototype.resize = function (opts) {
  26308. if (this[IN_MAIN_PROCESS_KEY]) {
  26309. if ("development" !== 'production') {
  26310. error('`resize` should not be called during main process.');
  26311. }
  26312. return;
  26313. }
  26314. if (this._disposed) {
  26315. disposedWarning(this.id);
  26316. return;
  26317. }
  26318. this._zr.resize(opts);
  26319. var ecModel = this._model; // Resize loading effect
  26320. this._loadingFX && this._loadingFX.resize();
  26321. if (!ecModel) {
  26322. return;
  26323. }
  26324. var needPrepare = ecModel.resetOption('media');
  26325. var silent = opts && opts.silent; // There is some real cases that:
  26326. // chart.setOption(option, { lazyUpdate: true });
  26327. // chart.resize();
  26328. if (this[PENDING_UPDATE]) {
  26329. if (silent == null) {
  26330. silent = this[PENDING_UPDATE].silent;
  26331. }
  26332. needPrepare = true;
  26333. this[PENDING_UPDATE] = null;
  26334. }
  26335. this[IN_MAIN_PROCESS_KEY] = true;
  26336. try {
  26337. needPrepare && prepare(this);
  26338. updateMethods.update.call(this, {
  26339. type: 'resize',
  26340. animation: extend({
  26341. // Disable animation
  26342. duration: 0
  26343. }, opts && opts.animation)
  26344. });
  26345. } catch (e) {
  26346. this[IN_MAIN_PROCESS_KEY] = false;
  26347. throw e;
  26348. }
  26349. this[IN_MAIN_PROCESS_KEY] = false;
  26350. flushPendingActions.call(this, silent);
  26351. triggerUpdatedEvent.call(this, silent);
  26352. };
  26353. ECharts.prototype.showLoading = function (name, cfg) {
  26354. if (this._disposed) {
  26355. disposedWarning(this.id);
  26356. return;
  26357. }
  26358. if (isObject(name)) {
  26359. cfg = name;
  26360. name = '';
  26361. }
  26362. name = name || 'default';
  26363. this.hideLoading();
  26364. if (!loadingEffects[name]) {
  26365. if ("development" !== 'production') {
  26366. warn('Loading effects ' + name + ' not exists.');
  26367. }
  26368. return;
  26369. }
  26370. var el = loadingEffects[name](this._api, cfg);
  26371. var zr = this._zr;
  26372. this._loadingFX = el;
  26373. zr.add(el);
  26374. };
  26375. /**
  26376. * Hide loading effect
  26377. */
  26378. ECharts.prototype.hideLoading = function () {
  26379. if (this._disposed) {
  26380. disposedWarning(this.id);
  26381. return;
  26382. }
  26383. this._loadingFX && this._zr.remove(this._loadingFX);
  26384. this._loadingFX = null;
  26385. };
  26386. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  26387. var payload = extend({}, eventObj);
  26388. payload.type = eventActionMap[eventObj.type];
  26389. return payload;
  26390. };
  26391. /**
  26392. * @param opt If pass boolean, means opt.silent
  26393. * @param opt.silent Default `false`. Whether trigger events.
  26394. * @param opt.flush Default `undefined`.
  26395. * true: Flush immediately, and then pixel in canvas can be fetched
  26396. * immediately. Caution: it might affect performance.
  26397. * false: Not flush.
  26398. * undefined: Auto decide whether perform flush.
  26399. */
  26400. ECharts.prototype.dispatchAction = function (payload, opt) {
  26401. if (this._disposed) {
  26402. disposedWarning(this.id);
  26403. return;
  26404. }
  26405. if (!isObject(opt)) {
  26406. opt = {
  26407. silent: !!opt
  26408. };
  26409. }
  26410. if (!actions[payload.type]) {
  26411. return;
  26412. } // Avoid dispatch action before setOption. Especially in `connect`.
  26413. if (!this._model) {
  26414. return;
  26415. } // May dispatchAction in rendering procedure
  26416. if (this[IN_MAIN_PROCESS_KEY]) {
  26417. this._pendingActions.push(payload);
  26418. return;
  26419. }
  26420. var silent = opt.silent;
  26421. doDispatchAction.call(this, payload, silent);
  26422. var flush = opt.flush;
  26423. if (flush) {
  26424. this._zr.flush();
  26425. } else if (flush !== false && env.browser.weChat) {
  26426. // In WeChat embedded browser, `requestAnimationFrame` and `setInterval`
  26427. // hang when sliding page (on touch event), which cause that zr does not
  26428. // refresh until user interaction finished, which is not expected.
  26429. // But `dispatchAction` may be called too frequently when pan on touch
  26430. // screen, which impacts performance if do not throttle them.
  26431. this._throttledZrFlush();
  26432. }
  26433. flushPendingActions.call(this, silent);
  26434. triggerUpdatedEvent.call(this, silent);
  26435. };
  26436. ECharts.prototype.updateLabelLayout = function () {
  26437. lifecycle.trigger('series:layoutlabels', this._model, this._api, {
  26438. // Not adding series labels.
  26439. // TODO
  26440. updatedSeries: []
  26441. });
  26442. };
  26443. ECharts.prototype.appendData = function (params) {
  26444. if (this._disposed) {
  26445. disposedWarning(this.id);
  26446. return;
  26447. }
  26448. var seriesIndex = params.seriesIndex;
  26449. var ecModel = this.getModel();
  26450. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  26451. if ("development" !== 'production') {
  26452. assert(params.data && seriesModel);
  26453. }
  26454. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  26455. // system, util some scenario require that. In the expected usage of
  26456. // `appendData`, the initial extent of coordinate system should better
  26457. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  26458. // the extent changed while `appendData`, the location of the painted
  26459. // graphic elements have to be changed, which make the usage of
  26460. // `appendData` meaningless.
  26461. this._scheduler.unfinished = true;
  26462. this.getZr().wakeUp();
  26463. }; // A work around for no `internal` modifier in ts yet but
  26464. // need to strictly hide private methods to JS users.
  26465. ECharts.internalField = function () {
  26466. prepare = function (ecIns) {
  26467. var scheduler = ecIns._scheduler;
  26468. scheduler.restorePipelines(ecIns._model);
  26469. scheduler.prepareStageTasks();
  26470. prepareView(ecIns, true);
  26471. prepareView(ecIns, false);
  26472. scheduler.plan();
  26473. };
  26474. /**
  26475. * Prepare view instances of charts and components
  26476. */
  26477. prepareView = function (ecIns, isComponent) {
  26478. var ecModel = ecIns._model;
  26479. var scheduler = ecIns._scheduler;
  26480. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  26481. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  26482. var zr = ecIns._zr;
  26483. var api = ecIns._api;
  26484. for (var i = 0; i < viewList.length; i++) {
  26485. viewList[i].__alive = false;
  26486. }
  26487. isComponent ? ecModel.eachComponent(function (componentType, model) {
  26488. componentType !== 'series' && doPrepare(model);
  26489. }) : ecModel.eachSeries(doPrepare);
  26490. function doPrepare(model) {
  26491. // By default view will be reused if possible for the case that `setOption` with "notMerge"
  26492. // mode and need to enable transition animation. (Usually, when they have the same id, or
  26493. // especially no id but have the same type & name & index. See the `model.id` generation
  26494. // rule in `makeIdAndName` and `viewId` generation rule here).
  26495. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  26496. // the new model has nothing to do with the old model.
  26497. var requireNewView = model.__requireNewView; // This command should not work twice.
  26498. model.__requireNewView = false; // Consider: id same and type changed.
  26499. var viewId = '_ec_' + model.id + '_' + model.type;
  26500. var view = !requireNewView && viewMap[viewId];
  26501. if (!view) {
  26502. var classType = parseClassType(model.type);
  26503. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  26504. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  26505. // For backward compat, still support a chart type declared as only subType
  26506. // like "liquidfill", but recommend "series.liquidfill"
  26507. // But need a base class to make a type series.
  26508. ChartView.getClass(classType.sub);
  26509. if ("development" !== 'production') {
  26510. assert(Clazz, classType.sub + ' does not exist.');
  26511. }
  26512. view = new Clazz();
  26513. view.init(ecModel, api);
  26514. viewMap[viewId] = view;
  26515. viewList.push(view);
  26516. zr.add(view.group);
  26517. }
  26518. model.__viewId = view.__id = viewId;
  26519. view.__alive = true;
  26520. view.__model = model;
  26521. view.group.__ecComponentInfo = {
  26522. mainType: model.mainType,
  26523. index: model.componentIndex
  26524. };
  26525. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  26526. }
  26527. for (var i = 0; i < viewList.length;) {
  26528. var view = viewList[i];
  26529. if (!view.__alive) {
  26530. !isComponent && view.renderTask.dispose();
  26531. zr.remove(view.group);
  26532. view.dispose(ecModel, api);
  26533. viewList.splice(i, 1);
  26534. if (viewMap[view.__id] === view) {
  26535. delete viewMap[view.__id];
  26536. }
  26537. view.__id = view.group.__ecComponentInfo = null;
  26538. } else {
  26539. i++;
  26540. }
  26541. }
  26542. };
  26543. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  26544. var ecModel = ecIns._model;
  26545. ecModel.setUpdatePayload(payload); // broadcast
  26546. if (!mainType) {
  26547. // FIXME
  26548. // Chart will not be update directly here, except set dirty.
  26549. // But there is no such scenario now.
  26550. each([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  26551. return;
  26552. }
  26553. var query = {};
  26554. query[mainType + 'Id'] = payload[mainType + 'Id'];
  26555. query[mainType + 'Index'] = payload[mainType + 'Index'];
  26556. query[mainType + 'Name'] = payload[mainType + 'Name'];
  26557. var condition = {
  26558. mainType: mainType,
  26559. query: query
  26560. };
  26561. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  26562. var excludeSeriesId = payload.excludeSeriesId;
  26563. var excludeSeriesIdMap;
  26564. if (excludeSeriesId != null) {
  26565. excludeSeriesIdMap = createHashMap();
  26566. each(normalizeToArray(excludeSeriesId), function (id) {
  26567. var modelId = convertOptionIdName(id, null);
  26568. if (modelId != null) {
  26569. excludeSeriesIdMap.set(modelId, true);
  26570. }
  26571. });
  26572. } // If dispatchAction before setOption, do nothing.
  26573. ecModel && ecModel.eachComponent(condition, function (model) {
  26574. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26575. if (isExcluded) {
  26576. return;
  26577. }
  26578. if (isHighDownPayload(payload)) {
  26579. if (model instanceof SeriesModel) {
  26580. if (payload.type === HIGHLIGHT_ACTION_TYPE && !payload.notBlur && !model.get(['emphasis', 'disabled'])) {
  26581. blurSeriesFromHighlightPayload(model, payload, ecIns._api);
  26582. }
  26583. } else {
  26584. var _a = findComponentHighDownDispatchers(model.mainType, model.componentIndex, payload.name, ecIns._api),
  26585. focusSelf = _a.focusSelf,
  26586. dispatchers = _a.dispatchers;
  26587. if (payload.type === HIGHLIGHT_ACTION_TYPE && focusSelf && !payload.notBlur) {
  26588. blurComponent(model.mainType, model.componentIndex, ecIns._api);
  26589. } // PENDING:
  26590. // Whether to put this "enter emphasis" code in `ComponentView`,
  26591. // which will be the same as `ChartView` but might be not necessary
  26592. // and will be far from this logic.
  26593. if (dispatchers) {
  26594. each(dispatchers, function (dispatcher) {
  26595. payload.type === HIGHLIGHT_ACTION_TYPE ? enterEmphasis(dispatcher) : leaveEmphasis(dispatcher);
  26596. });
  26597. }
  26598. }
  26599. } else if (isSelectChangePayload(payload)) {
  26600. // TODO geo
  26601. if (model instanceof SeriesModel) {
  26602. toggleSelectionFromPayload(model, payload, ecIns._api);
  26603. updateSeriesElementSelection(model);
  26604. markStatusToUpdate(ecIns);
  26605. }
  26606. }
  26607. }, ecIns);
  26608. ecModel && ecModel.eachComponent(condition, function (model) {
  26609. var isExcluded = excludeSeriesIdMap && excludeSeriesIdMap.get(model.id) != null;
  26610. if (isExcluded) {
  26611. return;
  26612. }
  26613. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  26614. }, ecIns);
  26615. function callView(view) {
  26616. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  26617. }
  26618. };
  26619. updateMethods = {
  26620. prepareAndUpdate: function (payload) {
  26621. prepare(this);
  26622. updateMethods.update.call(this, payload, {
  26623. // Needs to mark option changed if newOption is given.
  26624. // It's from MagicType.
  26625. // TODO If use a separate flag optionChanged in payload?
  26626. optionChanged: payload.newOption != null
  26627. });
  26628. },
  26629. update: function (payload, updateParams) {
  26630. var ecModel = this._model;
  26631. var api = this._api;
  26632. var zr = this._zr;
  26633. var coordSysMgr = this._coordSysMgr;
  26634. var scheduler = this._scheduler; // update before setOption
  26635. if (!ecModel) {
  26636. return;
  26637. }
  26638. ecModel.setUpdatePayload(payload);
  26639. scheduler.restoreData(ecModel, payload);
  26640. scheduler.performSeriesTasks(ecModel); // TODO
  26641. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  26642. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  26643. // Create new coordinate system each update
  26644. // In LineView may save the old coordinate system and use it to get the original point.
  26645. coordSysMgr.create(ecModel, api);
  26646. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  26647. // stream modes after data processing, where the filtered data is used to
  26648. // determine whether to use progressive rendering.
  26649. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  26650. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  26651. // the drawback is the full coord info can not be fetched. Fortunately this full
  26652. // coord is not required in stream mode updater currently.
  26653. coordSysMgr.update(ecModel, api);
  26654. clearColorPalette(ecModel);
  26655. scheduler.performVisualTasks(ecModel, payload);
  26656. render(this, ecModel, api, payload, updateParams); // Set background
  26657. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  26658. var darkMode = ecModel.get('darkMode');
  26659. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  26660. if (darkMode != null && darkMode !== 'auto') {
  26661. zr.setDarkMode(darkMode);
  26662. }
  26663. lifecycle.trigger('afterupdate', ecModel, api);
  26664. },
  26665. updateTransform: function (payload) {
  26666. var _this = this;
  26667. var ecModel = this._model;
  26668. var api = this._api; // update before setOption
  26669. if (!ecModel) {
  26670. return;
  26671. }
  26672. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  26673. var componentDirtyList = [];
  26674. ecModel.eachComponent(function (componentType, componentModel) {
  26675. if (componentType === 'series') {
  26676. return;
  26677. }
  26678. var componentView = _this.getViewOfComponentModel(componentModel);
  26679. if (componentView && componentView.__alive) {
  26680. if (componentView.updateTransform) {
  26681. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  26682. result && result.update && componentDirtyList.push(componentView);
  26683. } else {
  26684. componentDirtyList.push(componentView);
  26685. }
  26686. }
  26687. });
  26688. var seriesDirtyMap = createHashMap();
  26689. ecModel.eachSeries(function (seriesModel) {
  26690. var chartView = _this._chartsMap[seriesModel.__viewId];
  26691. if (chartView.updateTransform) {
  26692. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  26693. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  26694. } else {
  26695. seriesDirtyMap.set(seriesModel.uid, 1);
  26696. }
  26697. });
  26698. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26699. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  26700. this._scheduler.performVisualTasks(ecModel, payload, {
  26701. setDirty: true,
  26702. dirtyMap: seriesDirtyMap
  26703. }); // Currently, not call render of components. Geo render cost a lot.
  26704. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  26705. renderSeries(this, ecModel, api, payload, {}, seriesDirtyMap);
  26706. lifecycle.trigger('afterupdate', ecModel, api);
  26707. },
  26708. updateView: function (payload) {
  26709. var ecModel = this._model; // update before setOption
  26710. if (!ecModel) {
  26711. return;
  26712. }
  26713. ecModel.setUpdatePayload(payload);
  26714. ChartView.markUpdateMethod(payload, 'updateView');
  26715. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26716. this._scheduler.performVisualTasks(ecModel, payload, {
  26717. setDirty: true
  26718. });
  26719. render(this, ecModel, this._api, payload, {});
  26720. lifecycle.trigger('afterupdate', ecModel, this._api);
  26721. },
  26722. updateVisual: function (payload) {
  26723. // updateMethods.update.call(this, payload);
  26724. var _this = this;
  26725. var ecModel = this._model; // update before setOption
  26726. if (!ecModel) {
  26727. return;
  26728. }
  26729. ecModel.setUpdatePayload(payload); // clear all visual
  26730. ecModel.eachSeries(function (seriesModel) {
  26731. seriesModel.getData().clearAllVisual();
  26732. }); // Perform visual
  26733. ChartView.markUpdateMethod(payload, 'updateVisual');
  26734. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26735. this._scheduler.performVisualTasks(ecModel, payload, {
  26736. visualType: 'visual',
  26737. setDirty: true
  26738. });
  26739. ecModel.eachComponent(function (componentType, componentModel) {
  26740. if (componentType !== 'series') {
  26741. var componentView = _this.getViewOfComponentModel(componentModel);
  26742. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26743. }
  26744. });
  26745. ecModel.eachSeries(function (seriesModel) {
  26746. var chartView = _this._chartsMap[seriesModel.__viewId];
  26747. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26748. });
  26749. lifecycle.trigger('afterupdate', ecModel, this._api);
  26750. },
  26751. updateLayout: function (payload) {
  26752. updateMethods.update.call(this, payload);
  26753. }
  26754. };
  26755. doConvertPixel = function (ecIns, methodName, finder, value) {
  26756. if (ecIns._disposed) {
  26757. disposedWarning(ecIns.id);
  26758. return;
  26759. }
  26760. var ecModel = ecIns._model;
  26761. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26762. var result;
  26763. var parsedFinder = parseFinder(ecModel, finder);
  26764. for (var i = 0; i < coordSysList.length; i++) {
  26765. var coordSys = coordSysList[i];
  26766. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26767. return result;
  26768. }
  26769. }
  26770. if ("development" !== 'production') {
  26771. warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26772. }
  26773. };
  26774. updateStreamModes = function (ecIns, ecModel) {
  26775. var chartsMap = ecIns._chartsMap;
  26776. var scheduler = ecIns._scheduler;
  26777. ecModel.eachSeries(function (seriesModel) {
  26778. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26779. });
  26780. };
  26781. doDispatchAction = function (payload, silent) {
  26782. var _this = this;
  26783. var ecModel = this.getModel();
  26784. var payloadType = payload.type;
  26785. var escapeConnect = payload.escapeConnect;
  26786. var actionWrap = actions[payloadType];
  26787. var actionInfo = actionWrap.actionInfo;
  26788. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26789. var updateMethod = cptTypeTmp.pop();
  26790. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26791. this[IN_MAIN_PROCESS_KEY] = true;
  26792. var payloads = [payload];
  26793. var batched = false; // Batch action
  26794. if (payload.batch) {
  26795. batched = true;
  26796. payloads = map(payload.batch, function (item) {
  26797. item = defaults(extend({}, item), payload);
  26798. item.batch = null;
  26799. return item;
  26800. });
  26801. }
  26802. var eventObjBatch = [];
  26803. var eventObj;
  26804. var isSelectChange = isSelectChangePayload(payload);
  26805. var isHighDown = isHighDownPayload(payload); // Only leave blur once if there are multiple batches.
  26806. if (isHighDown) {
  26807. allLeaveBlur(this._api);
  26808. }
  26809. each(payloads, function (batchItem) {
  26810. // Action can specify the event by return it.
  26811. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26812. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26813. eventObj.type = actionInfo.event || eventObj.type;
  26814. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26815. if (isHighDown) {
  26816. var _a = preParseFinder(payload),
  26817. queryOptionMap = _a.queryOptionMap,
  26818. mainTypeSpecified = _a.mainTypeSpecified;
  26819. var componentMainType = mainTypeSpecified ? queryOptionMap.keys()[0] : 'series';
  26820. updateDirectly(_this, updateMethod, batchItem, componentMainType);
  26821. markStatusToUpdate(_this);
  26822. } else if (isSelectChange) {
  26823. // At present `dispatchAction({ type: 'select', ... })` is not supported on components.
  26824. // geo still use 'geoselect'.
  26825. updateDirectly(_this, updateMethod, batchItem, 'series');
  26826. markStatusToUpdate(_this);
  26827. } else if (cptType) {
  26828. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26829. }
  26830. });
  26831. if (updateMethod !== 'none' && !isHighDown && !isSelectChange && !cptType) {
  26832. try {
  26833. // Still dirty
  26834. if (this[PENDING_UPDATE]) {
  26835. prepare(this);
  26836. updateMethods.update.call(this, payload);
  26837. this[PENDING_UPDATE] = null;
  26838. } else {
  26839. updateMethods[updateMethod].call(this, payload);
  26840. }
  26841. } catch (e) {
  26842. this[IN_MAIN_PROCESS_KEY] = false;
  26843. throw e;
  26844. }
  26845. } // Follow the rule of action batch
  26846. if (batched) {
  26847. eventObj = {
  26848. type: actionInfo.event || payloadType,
  26849. escapeConnect: escapeConnect,
  26850. batch: eventObjBatch
  26851. };
  26852. } else {
  26853. eventObj = eventObjBatch[0];
  26854. }
  26855. this[IN_MAIN_PROCESS_KEY] = false;
  26856. if (!silent) {
  26857. var messageCenter = this._messageCenter;
  26858. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26859. if (isSelectChange) {
  26860. var newObj = {
  26861. type: 'selectchanged',
  26862. escapeConnect: escapeConnect,
  26863. selected: getAllSelectedIndices(ecModel),
  26864. isFromClick: payload.isFromClick || false,
  26865. fromAction: payload.type,
  26866. fromActionPayload: payload
  26867. };
  26868. messageCenter.trigger(newObj.type, newObj);
  26869. }
  26870. }
  26871. };
  26872. flushPendingActions = function (silent) {
  26873. var pendingActions = this._pendingActions;
  26874. while (pendingActions.length) {
  26875. var payload = pendingActions.shift();
  26876. doDispatchAction.call(this, payload, silent);
  26877. }
  26878. };
  26879. triggerUpdatedEvent = function (silent) {
  26880. !silent && this.trigger('updated');
  26881. };
  26882. /**
  26883. * Event `rendered` is triggered when zr
  26884. * rendered. It is useful for realtime
  26885. * snapshot (reflect animation).
  26886. *
  26887. * Event `finished` is triggered when:
  26888. * (1) zrender rendering finished.
  26889. * (2) initial animation finished.
  26890. * (3) progressive rendering finished.
  26891. * (4) no pending action.
  26892. * (5) no delayed setOption needs to be processed.
  26893. */
  26894. bindRenderedEvent = function (zr, ecIns) {
  26895. zr.on('rendered', function (params) {
  26896. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatedly,
  26897. // so it should only be triggered when rendering indeed happens
  26898. // in zrender. (Consider the case that dipatchAction is keep
  26899. // triggering when mouse move).
  26900. if ( // Although zr is dirty if initial animation is not finished
  26901. // and this checking is called on frame, we also check
  26902. // animation finished for robustness.
  26903. zr.animation.isFinished() && !ecIns[PENDING_UPDATE] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26904. ecIns.trigger('finished');
  26905. }
  26906. });
  26907. };
  26908. bindMouseEvent = function (zr, ecIns) {
  26909. zr.on('mouseover', function (e) {
  26910. var el = e.target;
  26911. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26912. if (dispatcher) {
  26913. handleGlobalMouseOverForHighDown(dispatcher, e, ecIns._api);
  26914. markStatusToUpdate(ecIns);
  26915. }
  26916. }).on('mouseout', function (e) {
  26917. var el = e.target;
  26918. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26919. if (dispatcher) {
  26920. handleGlobalMouseOutForHighDown(dispatcher, e, ecIns._api);
  26921. markStatusToUpdate(ecIns);
  26922. }
  26923. }).on('click', function (e) {
  26924. var el = e.target;
  26925. var dispatcher = findEventDispatcher(el, function (target) {
  26926. return getECData(target).dataIndex != null;
  26927. }, true);
  26928. if (dispatcher) {
  26929. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26930. var ecData = getECData(dispatcher);
  26931. ecIns._api.dispatchAction({
  26932. type: actionType,
  26933. dataType: ecData.dataType,
  26934. dataIndexInside: ecData.dataIndex,
  26935. seriesIndex: ecData.seriesIndex,
  26936. isFromClick: true
  26937. });
  26938. }
  26939. });
  26940. };
  26941. function clearColorPalette(ecModel) {
  26942. ecModel.clearColorPalette();
  26943. ecModel.eachSeries(function (seriesModel) {
  26944. seriesModel.clearColorPalette();
  26945. });
  26946. }
  26947. function allocateZlevels(ecModel) {
  26948. var componentZLevels = [];
  26949. var seriesZLevels = [];
  26950. var hasSeperateZLevel = false;
  26951. ecModel.eachComponent(function (componentType, componentModel) {
  26952. var zlevel = componentModel.get('zlevel') || 0;
  26953. var z = componentModel.get('z') || 0;
  26954. var zlevelKey = componentModel.getZLevelKey();
  26955. hasSeperateZLevel = hasSeperateZLevel || !!zlevelKey;
  26956. (componentType === 'series' ? seriesZLevels : componentZLevels).push({
  26957. zlevel: zlevel,
  26958. z: z,
  26959. idx: componentModel.componentIndex,
  26960. type: componentType,
  26961. key: zlevelKey
  26962. });
  26963. });
  26964. if (hasSeperateZLevel) {
  26965. // Series after component
  26966. var zLevels = componentZLevels.concat(seriesZLevels);
  26967. var lastSeriesZLevel_1;
  26968. var lastSeriesKey_1;
  26969. sort(zLevels, function (a, b) {
  26970. if (a.zlevel === b.zlevel) {
  26971. return a.z - b.z;
  26972. }
  26973. return a.zlevel - b.zlevel;
  26974. });
  26975. each(zLevels, function (item) {
  26976. var componentModel = ecModel.getComponent(item.type, item.idx);
  26977. var zlevel = item.zlevel;
  26978. var key = item.key;
  26979. if (lastSeriesZLevel_1 != null) {
  26980. zlevel = Math.max(lastSeriesZLevel_1, zlevel);
  26981. }
  26982. if (key) {
  26983. if (zlevel === lastSeriesZLevel_1 && key !== lastSeriesKey_1) {
  26984. zlevel++;
  26985. }
  26986. lastSeriesKey_1 = key;
  26987. } else if (lastSeriesKey_1) {
  26988. if (zlevel === lastSeriesZLevel_1) {
  26989. zlevel++;
  26990. }
  26991. lastSeriesKey_1 = '';
  26992. }
  26993. lastSeriesZLevel_1 = zlevel;
  26994. componentModel.setZLevel(zlevel);
  26995. });
  26996. }
  26997. }
  26998. render = function (ecIns, ecModel, api, payload, updateParams) {
  26999. allocateZlevels(ecModel);
  27000. renderComponents(ecIns, ecModel, api, payload, updateParams);
  27001. each(ecIns._chartsViews, function (chart) {
  27002. chart.__alive = false;
  27003. });
  27004. renderSeries(ecIns, ecModel, api, payload, updateParams); // Remove groups of unrendered charts
  27005. each(ecIns._chartsViews, function (chart) {
  27006. if (!chart.__alive) {
  27007. chart.remove(ecModel, api);
  27008. }
  27009. });
  27010. };
  27011. renderComponents = function (ecIns, ecModel, api, payload, updateParams, dirtyList) {
  27012. each(dirtyList || ecIns._componentsViews, function (componentView) {
  27013. var componentModel = componentView.__model;
  27014. clearStates(componentModel, componentView);
  27015. componentView.render(componentModel, ecModel, api, payload);
  27016. updateZ(componentModel, componentView);
  27017. updateStates(componentModel, componentView);
  27018. });
  27019. };
  27020. /**
  27021. * Render each chart and component
  27022. */
  27023. renderSeries = function (ecIns, ecModel, api, payload, updateParams, dirtyMap) {
  27024. // Render all charts
  27025. var scheduler = ecIns._scheduler;
  27026. updateParams = extend(updateParams || {}, {
  27027. updatedSeries: ecModel.getSeries()
  27028. }); // TODO progressive?
  27029. lifecycle.trigger('series:beforeupdate', ecModel, api, updateParams);
  27030. var unfinished = false;
  27031. ecModel.eachSeries(function (seriesModel) {
  27032. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27033. chartView.__alive = true;
  27034. var renderTask = chartView.renderTask;
  27035. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  27036. clearStates(seriesModel, chartView);
  27037. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  27038. renderTask.dirty();
  27039. }
  27040. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  27041. unfinished = true;
  27042. }
  27043. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  27044. // incremental render (always render from the __startIndex each frame)
  27045. // chartView.group.markRedraw();
  27046. updateBlend(seriesModel, chartView);
  27047. updateSeriesElementSelection(seriesModel);
  27048. });
  27049. scheduler.unfinished = unfinished || scheduler.unfinished;
  27050. lifecycle.trigger('series:layoutlabels', ecModel, api, updateParams); // transition after label is layouted.
  27051. lifecycle.trigger('series:transition', ecModel, api, updateParams);
  27052. ecModel.eachSeries(function (seriesModel) {
  27053. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  27054. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  27055. // label should be in normal status when layouting.
  27056. updateStates(seriesModel, chartView);
  27057. }); // If use hover layer
  27058. updateHoverLayerStatus(ecIns, ecModel);
  27059. lifecycle.trigger('series:afterupdate', ecModel, api, updateParams);
  27060. };
  27061. markStatusToUpdate = function (ecIns) {
  27062. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  27063. ecIns.getZr().wakeUp();
  27064. };
  27065. applyChangedStates = function (ecIns) {
  27066. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  27067. return;
  27068. }
  27069. ecIns.getZr().storage.traverse(function (el) {
  27070. // Not applied on removed elements, it may still in fading.
  27071. if (isElementRemoved(el)) {
  27072. return;
  27073. }
  27074. applyElementStates(el);
  27075. });
  27076. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  27077. };
  27078. function applyElementStates(el) {
  27079. var newStates = [];
  27080. var oldStates = el.currentStates; // Keep other states.
  27081. for (var i = 0; i < oldStates.length; i++) {
  27082. var stateName = oldStates[i];
  27083. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  27084. newStates.push(stateName);
  27085. }
  27086. } // Only use states when it's exists.
  27087. if (el.selected && el.states.select) {
  27088. newStates.push('select');
  27089. }
  27090. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  27091. newStates.push('emphasis');
  27092. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  27093. newStates.push('blur');
  27094. }
  27095. el.useStates(newStates);
  27096. }
  27097. function updateHoverLayerStatus(ecIns, ecModel) {
  27098. var zr = ecIns._zr;
  27099. var storage = zr.storage;
  27100. var elCount = 0;
  27101. storage.traverse(function (el) {
  27102. if (!el.isGroup) {
  27103. elCount++;
  27104. }
  27105. });
  27106. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  27107. ecModel.eachSeries(function (seriesModel) {
  27108. if (seriesModel.preventUsingHoverLayer) {
  27109. return;
  27110. }
  27111. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  27112. if (chartView.__alive) {
  27113. chartView.eachRendered(function (el) {
  27114. if (el.states.emphasis) {
  27115. el.states.emphasis.hoverLayer = true;
  27116. }
  27117. });
  27118. }
  27119. });
  27120. }
  27121. }
  27122. /**
  27123. * Update chart and blend.
  27124. */
  27125. function updateBlend(seriesModel, chartView) {
  27126. var blendMode = seriesModel.get('blendMode') || null;
  27127. chartView.eachRendered(function (el) {
  27128. // FIXME marker and other components
  27129. if (!el.isGroup) {
  27130. // DON'T mark the element dirty. In case element is incremental and don't want to rerender.
  27131. el.style.blend = blendMode;
  27132. }
  27133. });
  27134. }
  27135. function updateZ(model, view) {
  27136. if (model.preventAutoZ) {
  27137. return;
  27138. }
  27139. var z = model.get('z') || 0;
  27140. var zlevel = model.get('zlevel') || 0; // Set z and zlevel
  27141. view.eachRendered(function (el) {
  27142. doUpdateZ(el, z, zlevel, -Infinity); // Don't traverse the children because it has been traversed in _updateZ.
  27143. return true;
  27144. });
  27145. }
  27146. function doUpdateZ(el, z, zlevel, maxZ2) {
  27147. // Group may also have textContent
  27148. var label = el.getTextContent();
  27149. var labelLine = el.getTextGuideLine();
  27150. var isGroup = el.isGroup;
  27151. if (isGroup) {
  27152. // set z & zlevel of children elements of Group
  27153. var children = el.childrenRef();
  27154. for (var i = 0; i < children.length; i++) {
  27155. maxZ2 = Math.max(doUpdateZ(children[i], z, zlevel, maxZ2), maxZ2);
  27156. }
  27157. } else {
  27158. // not Group
  27159. el.z = z;
  27160. el.zlevel = zlevel;
  27161. maxZ2 = Math.max(el.z2, maxZ2);
  27162. } // always set z and zlevel if label/labelLine exists
  27163. if (label) {
  27164. label.z = z;
  27165. label.zlevel = zlevel; // lift z2 of text content
  27166. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  27167. isFinite(maxZ2) && (label.z2 = maxZ2 + 2);
  27168. }
  27169. if (labelLine) {
  27170. var textGuideLineConfig = el.textGuideLineConfig;
  27171. labelLine.z = z;
  27172. labelLine.zlevel = zlevel;
  27173. isFinite(maxZ2) && (labelLine.z2 = maxZ2 + (textGuideLineConfig && textGuideLineConfig.showAbove ? 1 : -1));
  27174. }
  27175. return maxZ2;
  27176. } // Clear states without animation.
  27177. // TODO States on component.
  27178. function clearStates(model, view) {
  27179. view.eachRendered(function (el) {
  27180. // Not applied on removed elements, it may still in fading.
  27181. if (isElementRemoved(el)) {
  27182. return;
  27183. }
  27184. var textContent = el.getTextContent();
  27185. var textGuide = el.getTextGuideLine();
  27186. if (el.stateTransition) {
  27187. el.stateTransition = null;
  27188. }
  27189. if (textContent && textContent.stateTransition) {
  27190. textContent.stateTransition = null;
  27191. }
  27192. if (textGuide && textGuide.stateTransition) {
  27193. textGuide.stateTransition = null;
  27194. } // TODO If el is incremental.
  27195. if (el.hasState()) {
  27196. el.prevStates = el.currentStates;
  27197. el.clearStates();
  27198. } else if (el.prevStates) {
  27199. el.prevStates = null;
  27200. }
  27201. });
  27202. }
  27203. function updateStates(model, view) {
  27204. var stateAnimationModel = model.getModel('stateAnimation');
  27205. var enableAnimation = model.isAnimationEnabled();
  27206. var duration = stateAnimationModel.get('duration');
  27207. var stateTransition = duration > 0 ? {
  27208. duration: duration,
  27209. delay: stateAnimationModel.get('delay'),
  27210. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  27211. } : null;
  27212. view.eachRendered(function (el) {
  27213. if (el.states && el.states.emphasis) {
  27214. // Not applied on removed elements, it may still in fading.
  27215. if (isElementRemoved(el)) {
  27216. return;
  27217. }
  27218. if (el instanceof Path) {
  27219. savePathStates(el);
  27220. } // Only updated on changed element. In case element is incremental and don't want to rerender.
  27221. // TODO, a more proper way?
  27222. if (el.__dirty) {
  27223. var prevStates = el.prevStates; // Restore states without animation
  27224. if (prevStates) {
  27225. el.useStates(prevStates);
  27226. }
  27227. } // Update state transition and enable animation again.
  27228. if (enableAnimation) {
  27229. el.stateTransition = stateTransition;
  27230. var textContent = el.getTextContent();
  27231. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  27232. if (textContent) {
  27233. textContent.stateTransition = stateTransition;
  27234. }
  27235. if (textGuide) {
  27236. textGuide.stateTransition = stateTransition;
  27237. }
  27238. } // Use highlighted and selected flag to toggle states.
  27239. if (el.__dirty) {
  27240. applyElementStates(el);
  27241. }
  27242. }
  27243. });
  27244. }
  27245. createExtensionAPI = function (ecIns) {
  27246. return new (
  27247. /** @class */
  27248. function (_super) {
  27249. __extends(class_1, _super);
  27250. function class_1() {
  27251. return _super !== null && _super.apply(this, arguments) || this;
  27252. }
  27253. class_1.prototype.getCoordinateSystems = function () {
  27254. return ecIns._coordSysMgr.getCoordinateSystems();
  27255. };
  27256. class_1.prototype.getComponentByElement = function (el) {
  27257. while (el) {
  27258. var modelInfo = el.__ecComponentInfo;
  27259. if (modelInfo != null) {
  27260. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  27261. }
  27262. el = el.parent;
  27263. }
  27264. };
  27265. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  27266. enterEmphasis(el, highlightDigit);
  27267. markStatusToUpdate(ecIns);
  27268. };
  27269. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  27270. leaveEmphasis(el, highlightDigit);
  27271. markStatusToUpdate(ecIns);
  27272. };
  27273. class_1.prototype.enterBlur = function (el) {
  27274. enterBlur(el);
  27275. markStatusToUpdate(ecIns);
  27276. };
  27277. class_1.prototype.leaveBlur = function (el) {
  27278. leaveBlur(el);
  27279. markStatusToUpdate(ecIns);
  27280. };
  27281. class_1.prototype.enterSelect = function (el) {
  27282. enterSelect(el);
  27283. markStatusToUpdate(ecIns);
  27284. };
  27285. class_1.prototype.leaveSelect = function (el) {
  27286. leaveSelect(el);
  27287. markStatusToUpdate(ecIns);
  27288. };
  27289. class_1.prototype.getModel = function () {
  27290. return ecIns.getModel();
  27291. };
  27292. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  27293. return ecIns.getViewOfComponentModel(componentModel);
  27294. };
  27295. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  27296. return ecIns.getViewOfSeriesModel(seriesModel);
  27297. };
  27298. return class_1;
  27299. }(ExtensionAPI))(ecIns);
  27300. };
  27301. enableConnect = function (chart) {
  27302. function updateConnectedChartsStatus(charts, status) {
  27303. for (var i = 0; i < charts.length; i++) {
  27304. var otherChart = charts[i];
  27305. otherChart[CONNECT_STATUS_KEY] = status;
  27306. }
  27307. }
  27308. each(eventActionMap, function (actionType, eventType) {
  27309. chart._messageCenter.on(eventType, function (event) {
  27310. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  27311. if (event && event.escapeConnect) {
  27312. return;
  27313. }
  27314. var action_1 = chart.makeActionFromEvent(event);
  27315. var otherCharts_1 = [];
  27316. each(instances$1, function (otherChart) {
  27317. if (otherChart !== chart && otherChart.group === chart.group) {
  27318. otherCharts_1.push(otherChart);
  27319. }
  27320. });
  27321. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  27322. each(otherCharts_1, function (otherChart) {
  27323. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  27324. otherChart.dispatchAction(action_1);
  27325. }
  27326. });
  27327. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  27328. }
  27329. });
  27330. });
  27331. };
  27332. }();
  27333. return ECharts;
  27334. }(Eventful);
  27335. var echartsProto = ECharts.prototype;
  27336. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  27337. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  27338. /**
  27339. * @deprecated
  27340. */
  27341. // @ts-ignore
  27342. echartsProto.one = function (eventName, cb, ctx) {
  27343. var self = this;
  27344. deprecateLog('ECharts#one is deprecated.');
  27345. function wrapped() {
  27346. var args2 = [];
  27347. for (var _i = 0; _i < arguments.length; _i++) {
  27348. args2[_i] = arguments[_i];
  27349. }
  27350. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  27351. self.off(eventName, wrapped);
  27352. }
  27353. this.on.call(this, eventName, wrapped, ctx);
  27354. };
  27355. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  27356. function disposedWarning(id) {
  27357. if ("development" !== 'production') {
  27358. warn('Instance ' + id + ' has been disposed');
  27359. }
  27360. }
  27361. var actions = {};
  27362. /**
  27363. * Map eventType to actionType
  27364. */
  27365. var eventActionMap = {};
  27366. var dataProcessorFuncs = [];
  27367. var optionPreprocessorFuncs = [];
  27368. var visualFuncs = [];
  27369. var themeStorage = {};
  27370. var loadingEffects = {};
  27371. var instances$1 = {};
  27372. var connectedGroups = {};
  27373. var idBase = +new Date() - 0;
  27374. var groupIdBase = +new Date() - 0;
  27375. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  27376. /**
  27377. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  27378. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  27379. * @param opts.width Use clientWidth of the input `dom` by default.
  27380. * Can be 'auto' (the same as null/undefined)
  27381. * @param opts.height Use clientHeight of the input `dom` by default.
  27382. * Can be 'auto' (the same as null/undefined)
  27383. * @param opts.locale Specify the locale.
  27384. * @param opts.useDirtyRect Enable dirty rectangle rendering or not.
  27385. */
  27386. function init$1(dom, theme, opts) {
  27387. var isClient = !(opts && opts.ssr);
  27388. if (isClient) {
  27389. if ("development" !== 'production') {
  27390. if (!dom) {
  27391. throw new Error('Initialize failed: invalid dom.');
  27392. }
  27393. }
  27394. var existInstance = getInstanceByDom(dom);
  27395. if (existInstance) {
  27396. if ("development" !== 'production') {
  27397. warn('There is a chart instance already initialized on the dom.');
  27398. }
  27399. return existInstance;
  27400. }
  27401. if ("development" !== 'production') {
  27402. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  27403. 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.');
  27404. }
  27405. }
  27406. }
  27407. var chart = new ECharts(dom, theme, opts);
  27408. chart.id = 'ec_' + idBase++;
  27409. instances$1[chart.id] = chart;
  27410. isClient && setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  27411. enableConnect(chart);
  27412. lifecycle.trigger('afterinit', chart);
  27413. return chart;
  27414. }
  27415. /**
  27416. * @usage
  27417. * (A)
  27418. * ```js
  27419. * let chart1 = echarts.init(dom1);
  27420. * let chart2 = echarts.init(dom2);
  27421. * chart1.group = 'xxx';
  27422. * chart2.group = 'xxx';
  27423. * echarts.connect('xxx');
  27424. * ```
  27425. * (B)
  27426. * ```js
  27427. * let chart1 = echarts.init(dom1);
  27428. * let chart2 = echarts.init(dom2);
  27429. * echarts.connect('xxx', [chart1, chart2]);
  27430. * ```
  27431. */
  27432. function connect(groupId) {
  27433. // Is array of charts
  27434. if (isArray(groupId)) {
  27435. var charts = groupId;
  27436. groupId = null; // If any chart has group
  27437. each(charts, function (chart) {
  27438. if (chart.group != null) {
  27439. groupId = chart.group;
  27440. }
  27441. });
  27442. groupId = groupId || 'g_' + groupIdBase++;
  27443. each(charts, function (chart) {
  27444. chart.group = groupId;
  27445. });
  27446. }
  27447. connectedGroups[groupId] = true;
  27448. return groupId;
  27449. }
  27450. function disconnect(groupId) {
  27451. connectedGroups[groupId] = false;
  27452. }
  27453. /**
  27454. * Alias and backward compatibility
  27455. * @deprecated
  27456. */
  27457. var disConnect = disconnect;
  27458. /**
  27459. * Dispose a chart instance
  27460. */
  27461. function dispose$1(chart) {
  27462. if (isString(chart)) {
  27463. chart = instances$1[chart];
  27464. } else if (!(chart instanceof ECharts)) {
  27465. // Try to treat as dom
  27466. chart = getInstanceByDom(chart);
  27467. }
  27468. if (chart instanceof ECharts && !chart.isDisposed()) {
  27469. chart.dispose();
  27470. }
  27471. }
  27472. function getInstanceByDom(dom) {
  27473. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  27474. }
  27475. function getInstanceById(key) {
  27476. return instances$1[key];
  27477. }
  27478. /**
  27479. * Register theme
  27480. */
  27481. function registerTheme(name, theme) {
  27482. themeStorage[name] = theme;
  27483. }
  27484. /**
  27485. * Register option preprocessor
  27486. */
  27487. function registerPreprocessor(preprocessorFunc) {
  27488. if (indexOf(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  27489. optionPreprocessorFuncs.push(preprocessorFunc);
  27490. }
  27491. }
  27492. function registerProcessor(priority, processor) {
  27493. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  27494. }
  27495. /**
  27496. * Register postIniter
  27497. * @param {Function} postInitFunc
  27498. */
  27499. function registerPostInit(postInitFunc) {
  27500. registerUpdateLifecycle('afterinit', postInitFunc);
  27501. }
  27502. /**
  27503. * Register postUpdater
  27504. * @param {Function} postUpdateFunc
  27505. */
  27506. function registerPostUpdate(postUpdateFunc) {
  27507. registerUpdateLifecycle('afterupdate', postUpdateFunc);
  27508. }
  27509. function registerUpdateLifecycle(name, cb) {
  27510. lifecycle.on(name, cb);
  27511. }
  27512. function registerAction(actionInfo, eventName, action) {
  27513. if (isFunction(eventName)) {
  27514. action = eventName;
  27515. eventName = '';
  27516. }
  27517. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  27518. event: eventName
  27519. }][0]; // Event name is all lowercase
  27520. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  27521. eventName = actionInfo.event;
  27522. if (eventActionMap[eventName]) {
  27523. // Already registered.
  27524. return;
  27525. } // Validate action type and event name.
  27526. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  27527. if (!actions[actionType]) {
  27528. actions[actionType] = {
  27529. action: action,
  27530. actionInfo: actionInfo
  27531. };
  27532. }
  27533. eventActionMap[eventName] = actionType;
  27534. }
  27535. function registerCoordinateSystem(type, coordSysCreator) {
  27536. CoordinateSystemManager.register(type, coordSysCreator);
  27537. }
  27538. /**
  27539. * Get dimensions of specified coordinate system.
  27540. * @param {string} type
  27541. * @return {Array.<string|Object>}
  27542. */
  27543. function getCoordinateSystemDimensions(type) {
  27544. var coordSysCreator = CoordinateSystemManager.get(type);
  27545. if (coordSysCreator) {
  27546. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  27547. }
  27548. }
  27549. function registerLayout(priority, layoutTask) {
  27550. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  27551. }
  27552. function registerVisual(priority, visualTask) {
  27553. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  27554. }
  27555. var registeredTasks = [];
  27556. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  27557. if (isFunction(priority) || isObject(priority)) {
  27558. fn = priority;
  27559. priority = defaultPriority;
  27560. }
  27561. if ("development" !== 'production') {
  27562. if (isNaN(priority) || priority == null) {
  27563. throw new Error('Illegal priority');
  27564. } // Check duplicate
  27565. each(targetList, function (wrap) {
  27566. assert(wrap.__raw !== fn);
  27567. });
  27568. } // Already registered
  27569. if (indexOf(registeredTasks, fn) >= 0) {
  27570. return;
  27571. }
  27572. registeredTasks.push(fn);
  27573. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  27574. stageHandler.__prio = priority;
  27575. stageHandler.__raw = fn;
  27576. targetList.push(stageHandler);
  27577. }
  27578. function registerLoading(name, loadingFx) {
  27579. loadingEffects[name] = loadingFx;
  27580. }
  27581. /**
  27582. * ZRender need a canvas context to do measureText.
  27583. * But in node environment canvas may be created by node-canvas.
  27584. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  27585. *
  27586. *
  27587. * @deprecated use setPlatformAPI({ createCanvas }) instead.
  27588. *
  27589. * @example
  27590. * let Canvas = require('canvas');
  27591. * let echarts = require('echarts');
  27592. * echarts.setCanvasCreator(function () {
  27593. * // Small size is enough.
  27594. * return new Canvas(32, 32);
  27595. * });
  27596. */
  27597. function setCanvasCreator(creator) {
  27598. if ("development" !== 'production') {
  27599. deprecateLog('setCanvasCreator is deprecated. Use setPlatformAPI({ createCanvas }) instead.');
  27600. }
  27601. setPlatformAPI({
  27602. createCanvas: creator
  27603. });
  27604. }
  27605. /**
  27606. * The parameters and usage: see `geoSourceManager.registerMap`.
  27607. * Compatible with previous `echarts.registerMap`.
  27608. */
  27609. function registerMap(mapName, geoJson, specialAreas) {
  27610. var registerMap = getImpl('registerMap');
  27611. registerMap && registerMap(mapName, geoJson, specialAreas);
  27612. }
  27613. function getMap(mapName) {
  27614. var getMap = getImpl('getMap');
  27615. return getMap && getMap(mapName);
  27616. }
  27617. var registerTransform = registerExternalTransform;
  27618. /**
  27619. * Globa dispatchAction to a specified chart instance.
  27620. */
  27621. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  27622. // if (!payload || !payload.chartId) {
  27623. // // Must have chartId to find chart
  27624. // return;
  27625. // }
  27626. // const chart = instances[payload.chartId];
  27627. // if (chart) {
  27628. // chart.dispatchAction(payload, opt);
  27629. // }
  27630. // }
  27631. // Builtin global visual
  27632. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  27633. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  27634. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  27635. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  27636. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  27637. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  27638. registerPreprocessor(globalBackwardCompat);
  27639. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  27640. registerLoading('default', defaultLoading); // Default actions
  27641. registerAction({
  27642. type: HIGHLIGHT_ACTION_TYPE,
  27643. event: HIGHLIGHT_ACTION_TYPE,
  27644. update: HIGHLIGHT_ACTION_TYPE
  27645. }, noop);
  27646. registerAction({
  27647. type: DOWNPLAY_ACTION_TYPE,
  27648. event: DOWNPLAY_ACTION_TYPE,
  27649. update: DOWNPLAY_ACTION_TYPE
  27650. }, noop);
  27651. registerAction({
  27652. type: SELECT_ACTION_TYPE,
  27653. event: SELECT_ACTION_TYPE,
  27654. update: SELECT_ACTION_TYPE
  27655. }, noop);
  27656. registerAction({
  27657. type: UNSELECT_ACTION_TYPE,
  27658. event: UNSELECT_ACTION_TYPE,
  27659. update: UNSELECT_ACTION_TYPE
  27660. }, noop);
  27661. registerAction({
  27662. type: TOGGLE_SELECT_ACTION_TYPE,
  27663. event: TOGGLE_SELECT_ACTION_TYPE,
  27664. update: TOGGLE_SELECT_ACTION_TYPE
  27665. }, noop); // Default theme
  27666. registerTheme('light', lightTheme);
  27667. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  27668. // be mounted on `echarts` is the extension `dataTool` is imported.
  27669. var dataTool = {};
  27670. var extensions = [];
  27671. var extensionRegisters = {
  27672. registerPreprocessor: registerPreprocessor,
  27673. registerProcessor: registerProcessor,
  27674. registerPostInit: registerPostInit,
  27675. registerPostUpdate: registerPostUpdate,
  27676. registerUpdateLifecycle: registerUpdateLifecycle,
  27677. registerAction: registerAction,
  27678. registerCoordinateSystem: registerCoordinateSystem,
  27679. registerLayout: registerLayout,
  27680. registerVisual: registerVisual,
  27681. registerTransform: registerTransform,
  27682. registerLoading: registerLoading,
  27683. registerMap: registerMap,
  27684. registerImpl: registerImpl,
  27685. PRIORITY: PRIORITY,
  27686. ComponentModel: ComponentModel,
  27687. ComponentView: ComponentView,
  27688. SeriesModel: SeriesModel,
  27689. ChartView: ChartView,
  27690. // TODO Use ComponentModel and SeriesModel instead of Constructor
  27691. registerComponentModel: function (ComponentModelClass) {
  27692. ComponentModel.registerClass(ComponentModelClass);
  27693. },
  27694. registerComponentView: function (ComponentViewClass) {
  27695. ComponentView.registerClass(ComponentViewClass);
  27696. },
  27697. registerSeriesModel: function (SeriesModelClass) {
  27698. SeriesModel.registerClass(SeriesModelClass);
  27699. },
  27700. registerChartView: function (ChartViewClass) {
  27701. ChartView.registerClass(ChartViewClass);
  27702. },
  27703. registerSubTypeDefaulter: function (componentType, defaulter) {
  27704. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  27705. },
  27706. registerPainter: function (painterType, PainterCtor) {
  27707. registerPainter(painterType, PainterCtor);
  27708. }
  27709. };
  27710. function use(ext) {
  27711. if (isArray(ext)) {
  27712. // use([ChartLine, ChartBar]);
  27713. each(ext, function (singleExt) {
  27714. use(singleExt);
  27715. });
  27716. return;
  27717. }
  27718. if (indexOf(extensions, ext) >= 0) {
  27719. return;
  27720. }
  27721. extensions.push(ext);
  27722. if (isFunction(ext)) {
  27723. ext = {
  27724. install: ext
  27725. };
  27726. }
  27727. ext.install(extensionRegisters);
  27728. }
  27729. /*
  27730. * Licensed to the Apache Software Foundation (ASF) under one
  27731. * or more contributor license agreements. See the NOTICE file
  27732. * distributed with this work for additional information
  27733. * regarding copyright ownership. The ASF licenses this file
  27734. * to you under the Apache License, Version 2.0 (the
  27735. * "License"); you may not use this file except in compliance
  27736. * with the License. You may obtain a copy of the License at
  27737. *
  27738. * http://www.apache.org/licenses/LICENSE-2.0
  27739. *
  27740. * Unless required by applicable law or agreed to in writing,
  27741. * software distributed under the License is distributed on an
  27742. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27743. * KIND, either express or implied. See the License for the
  27744. * specific language governing permissions and limitations
  27745. * under the License.
  27746. */
  27747. /**
  27748. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27749. */
  27750. /*
  27751. * Licensed to the Apache Software Foundation (ASF) under one
  27752. * or more contributor license agreements. See the NOTICE file
  27753. * distributed with this work for additional information
  27754. * regarding copyright ownership. The ASF licenses this file
  27755. * to you under the Apache License, Version 2.0 (the
  27756. * "License"); you may not use this file except in compliance
  27757. * with the License. You may obtain a copy of the License at
  27758. *
  27759. * http://www.apache.org/licenses/LICENSE-2.0
  27760. *
  27761. * Unless required by applicable law or agreed to in writing,
  27762. * software distributed under the License is distributed on an
  27763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27764. * KIND, either express or implied. See the License for the
  27765. * specific language governing permissions and limitations
  27766. * under the License.
  27767. */
  27768. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27769. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27770. }
  27771. function defaultKeyGetter(item) {
  27772. return item;
  27773. }
  27774. var DataDiffer =
  27775. /** @class */
  27776. function () {
  27777. /**
  27778. * @param context Can be visited by this.context in callback.
  27779. */
  27780. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27781. diffMode) {
  27782. this._old = oldArr;
  27783. this._new = newArr;
  27784. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27785. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27786. this.context = context;
  27787. this._diffModeMultiple = diffMode === 'multiple';
  27788. }
  27789. /**
  27790. * Callback function when add a data
  27791. */
  27792. DataDiffer.prototype.add = function (func) {
  27793. this._add = func;
  27794. return this;
  27795. };
  27796. /**
  27797. * Callback function when update a data
  27798. */
  27799. DataDiffer.prototype.update = function (func) {
  27800. this._update = func;
  27801. return this;
  27802. };
  27803. /**
  27804. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27805. */
  27806. DataDiffer.prototype.updateManyToOne = function (func) {
  27807. this._updateManyToOne = func;
  27808. return this;
  27809. };
  27810. /**
  27811. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27812. */
  27813. DataDiffer.prototype.updateOneToMany = function (func) {
  27814. this._updateOneToMany = func;
  27815. return this;
  27816. };
  27817. /**
  27818. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27819. */
  27820. DataDiffer.prototype.updateManyToMany = function (func) {
  27821. this._updateManyToMany = func;
  27822. return this;
  27823. };
  27824. /**
  27825. * Callback function when remove a data
  27826. */
  27827. DataDiffer.prototype.remove = function (func) {
  27828. this._remove = func;
  27829. return this;
  27830. };
  27831. DataDiffer.prototype.execute = function () {
  27832. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27833. };
  27834. DataDiffer.prototype._executeOneToOne = function () {
  27835. var oldArr = this._old;
  27836. var newArr = this._new;
  27837. var newDataIndexMap = {};
  27838. var oldDataKeyArr = new Array(oldArr.length);
  27839. var newDataKeyArr = new Array(newArr.length);
  27840. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27841. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27842. for (var i = 0; i < oldArr.length; i++) {
  27843. var oldKey = oldDataKeyArr[i];
  27844. var newIdxMapVal = newDataIndexMap[oldKey];
  27845. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27846. if (newIdxMapValLen > 1) {
  27847. // Consider there is duplicate key (for example, use dataItem.name as key).
  27848. // We should make sure every item in newArr and oldArr can be visited.
  27849. var newIdx = newIdxMapVal.shift();
  27850. if (newIdxMapVal.length === 1) {
  27851. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27852. }
  27853. this._update && this._update(newIdx, i);
  27854. } else if (newIdxMapValLen === 1) {
  27855. newDataIndexMap[oldKey] = null;
  27856. this._update && this._update(newIdxMapVal, i);
  27857. } else {
  27858. this._remove && this._remove(i);
  27859. }
  27860. }
  27861. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27862. };
  27863. /**
  27864. * For example, consider the case:
  27865. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27866. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27867. * Where:
  27868. * o0, o1, n0 has key 'a' (many to one)
  27869. * o5, n4, n5, n6 has key 'b' (one to many)
  27870. * o2, n1 has key 'c' (one to one)
  27871. * n2, n3 has key 'd' (add)
  27872. * o3, o4 has key 'e' (remove)
  27873. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27874. * Then:
  27875. * (The order of the following directives are not ensured.)
  27876. * this._updateManyToOne(n0, [o0, o1]);
  27877. * this._updateOneToMany([n4, n5, n6], o5);
  27878. * this._update(n1, o2);
  27879. * this._remove(o3);
  27880. * this._remove(o4);
  27881. * this._remove(o6);
  27882. * this._remove(o7);
  27883. * this._add(n2);
  27884. * this._add(n3);
  27885. * this._add(n7);
  27886. * this._add(n8);
  27887. */
  27888. DataDiffer.prototype._executeMultiple = function () {
  27889. var oldArr = this._old;
  27890. var newArr = this._new;
  27891. var oldDataIndexMap = {};
  27892. var newDataIndexMap = {};
  27893. var oldDataKeyArr = [];
  27894. var newDataKeyArr = [];
  27895. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27896. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27897. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27898. var oldKey = oldDataKeyArr[i];
  27899. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27900. var newIdxMapVal = newDataIndexMap[oldKey];
  27901. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27902. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27903. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27904. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27905. newDataIndexMap[oldKey] = null;
  27906. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27907. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27908. newDataIndexMap[oldKey] = null;
  27909. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27910. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27911. newDataIndexMap[oldKey] = null;
  27912. } else if (oldIdxMapValLen > 1 && newIdxMapValLen > 1) {
  27913. this._updateManyToMany && this._updateManyToMany(newIdxMapVal, oldIdxMapVal);
  27914. newDataIndexMap[oldKey] = null;
  27915. } else if (oldIdxMapValLen > 1) {
  27916. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27917. this._remove && this._remove(oldIdxMapVal[i_1]);
  27918. }
  27919. } else {
  27920. this._remove && this._remove(oldIdxMapVal);
  27921. }
  27922. }
  27923. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27924. };
  27925. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27926. for (var i = 0; i < newDataKeyArr.length; i++) {
  27927. var newKey = newDataKeyArr[i];
  27928. var newIdxMapVal = newDataIndexMap[newKey];
  27929. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27930. if (idxMapValLen > 1) {
  27931. for (var j = 0; j < idxMapValLen; j++) {
  27932. this._add && this._add(newIdxMapVal[j]);
  27933. }
  27934. } else if (idxMapValLen === 1) {
  27935. this._add && this._add(newIdxMapVal);
  27936. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27937. newDataIndexMap[newKey] = null;
  27938. }
  27939. };
  27940. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27941. map, // In 'byKey', the output `keyArr` is duplication removed.
  27942. // In 'byIndex', the output `keyArr` is not duplication removed and
  27943. // its indices are accurately corresponding to `arr`.
  27944. keyArr, keyGetterName) {
  27945. var cbModeMultiple = this._diffModeMultiple;
  27946. for (var i = 0; i < arr.length; i++) {
  27947. // Add prefix to avoid conflict with Object.prototype.
  27948. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27949. if (!cbModeMultiple) {
  27950. keyArr[i] = key;
  27951. }
  27952. if (!map) {
  27953. continue;
  27954. }
  27955. var idxMapVal = map[key];
  27956. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27957. if (idxMapValLen === 0) {
  27958. // Simple optimize: in most cases, one index has one key,
  27959. // do not need array.
  27960. map[key] = i;
  27961. if (cbModeMultiple) {
  27962. keyArr.push(key);
  27963. }
  27964. } else if (idxMapValLen === 1) {
  27965. map[key] = [idxMapVal, i];
  27966. } else {
  27967. idxMapVal.push(i);
  27968. }
  27969. }
  27970. };
  27971. return DataDiffer;
  27972. }();
  27973. var DimensionUserOuput =
  27974. /** @class */
  27975. function () {
  27976. function DimensionUserOuput(encode, dimRequest) {
  27977. this._encode = encode;
  27978. this._schema = dimRequest;
  27979. }
  27980. DimensionUserOuput.prototype.get = function () {
  27981. return {
  27982. // Do not generate full dimension name until fist used.
  27983. fullDimensions: this._getFullDimensionNames(),
  27984. encode: this._encode
  27985. };
  27986. };
  27987. /**
  27988. * Get all data store dimension names.
  27989. * Theoretically a series data store is defined both by series and used dataset (if any).
  27990. * If some dimensions are omitted for performance reason in `this.dimensions`,
  27991. * the dimension name may not be auto-generated if user does not specify a dimension name.
  27992. * In this case, the dimension name is `null`/`undefined`.
  27993. */
  27994. DimensionUserOuput.prototype._getFullDimensionNames = function () {
  27995. if (!this._cachedDimNames) {
  27996. this._cachedDimNames = this._schema ? this._schema.makeOutputDimensionNames() : [];
  27997. }
  27998. return this._cachedDimNames;
  27999. };
  28000. return DimensionUserOuput;
  28001. }();
  28002. function summarizeDimensions(data, schema) {
  28003. var summary = {};
  28004. var encode = summary.encode = {};
  28005. var notExtraCoordDimMap = createHashMap();
  28006. var defaultedLabel = [];
  28007. var defaultedTooltip = [];
  28008. var userOutputEncode = {};
  28009. each(data.dimensions, function (dimName) {
  28010. var dimItem = data.getDimensionInfo(dimName);
  28011. var coordDim = dimItem.coordDim;
  28012. if (coordDim) {
  28013. if ("development" !== 'production') {
  28014. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  28015. }
  28016. var coordDimIndex = dimItem.coordDimIndex;
  28017. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  28018. if (!dimItem.isExtraCoord) {
  28019. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  28020. // because when dataset is used, it is hard to guess which dimension
  28021. // can be value dimension. If both show x, y on label is not look good,
  28022. // and conventionally y axis is focused more.
  28023. if (mayLabelDimType(dimItem.type)) {
  28024. defaultedLabel[0] = dimName;
  28025. } // User output encode do not contain generated coords.
  28026. // And it only has index. User can use index to retrieve value from the raw item array.
  28027. getOrCreateEncodeArr(userOutputEncode, coordDim)[coordDimIndex] = data.getDimensionIndex(dimItem.name);
  28028. }
  28029. if (dimItem.defaultTooltip) {
  28030. defaultedTooltip.push(dimName);
  28031. }
  28032. }
  28033. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  28034. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  28035. var dimIndex = dimItem.otherDims[otherDim];
  28036. if (dimIndex != null && dimIndex !== false) {
  28037. encodeArr[dimIndex] = dimItem.name;
  28038. }
  28039. });
  28040. });
  28041. var dataDimsOnCoord = [];
  28042. var encodeFirstDimNotExtra = {};
  28043. notExtraCoordDimMap.each(function (v, coordDim) {
  28044. var dimArr = encode[coordDim];
  28045. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  28046. // dim canot on more than one coordDim.
  28047. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  28048. });
  28049. summary.dataDimsOnCoord = dataDimsOnCoord;
  28050. summary.dataDimIndicesOnCoord = map(dataDimsOnCoord, function (dimName) {
  28051. return data.getDimensionInfo(dimName).storeDimIndex;
  28052. });
  28053. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  28054. var encodeLabel = encode.label; // FIXME `encode.label` is not recommended, because formatter cannot be set
  28055. // in this way. Use label.formatter instead. Maybe remove this approach someday.
  28056. if (encodeLabel && encodeLabel.length) {
  28057. defaultedLabel = encodeLabel.slice();
  28058. }
  28059. var encodeTooltip = encode.tooltip;
  28060. if (encodeTooltip && encodeTooltip.length) {
  28061. defaultedTooltip = encodeTooltip.slice();
  28062. } else if (!defaultedTooltip.length) {
  28063. defaultedTooltip = defaultedLabel.slice();
  28064. }
  28065. encode.defaultedLabel = defaultedLabel;
  28066. encode.defaultedTooltip = defaultedTooltip;
  28067. summary.userOutput = new DimensionUserOuput(userOutputEncode, schema);
  28068. return summary;
  28069. }
  28070. function getOrCreateEncodeArr(encode, dim) {
  28071. if (!encode.hasOwnProperty(dim)) {
  28072. encode[dim] = [];
  28073. }
  28074. return encode[dim];
  28075. } // FIXME:TS should be type `AxisType`
  28076. function getDimensionTypeByAxis(axisType) {
  28077. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  28078. }
  28079. function mayLabelDimType(dimType) {
  28080. // In most cases, ordinal and time do not suitable for label.
  28081. // Ordinal info can be displayed on axis. Time is too long.
  28082. return !(dimType === 'ordinal' || dimType === 'time');
  28083. } // function findTheLastDimMayLabel(data) {
  28084. // // Get last value dim
  28085. // let dimensions = data.dimensions.slice();
  28086. // let valueType;
  28087. // let valueDim;
  28088. // while (dimensions.length && (
  28089. // valueDim = dimensions.pop(),
  28090. // valueType = data.getDimensionInfo(valueDim).type,
  28091. // valueType === 'ordinal' || valueType === 'time'
  28092. // )) {} // jshint ignore:line
  28093. // return valueDim;
  28094. // }
  28095. var SeriesDimensionDefine =
  28096. /** @class */
  28097. function () {
  28098. /**
  28099. * @param opt All of the fields will be shallow copied.
  28100. */
  28101. function SeriesDimensionDefine(opt) {
  28102. /**
  28103. * The format of `otherDims` is:
  28104. * ```js
  28105. * {
  28106. * tooltip?: number
  28107. * label?: number
  28108. * itemName?: number
  28109. * seriesName?: number
  28110. * }
  28111. * ```
  28112. *
  28113. * A `series.encode` can specified these fields:
  28114. * ```js
  28115. * encode: {
  28116. * // "3, 1, 5" is the index of data dimension.
  28117. * tooltip: [3, 1, 5],
  28118. * label: [0, 3],
  28119. * ...
  28120. * }
  28121. * ```
  28122. * `otherDims` is the parse result of the `series.encode` above, like:
  28123. * ```js
  28124. * // Suppose the index of this data dimension is `3`.
  28125. * this.otherDims = {
  28126. * // `3` is at the index `0` of the `encode.tooltip`
  28127. * tooltip: 0,
  28128. * // `3` is at the index `1` of the `encode.label`
  28129. * label: 1
  28130. * };
  28131. * ```
  28132. *
  28133. * This prop should never be `null`/`undefined` after initialized.
  28134. */
  28135. this.otherDims = {};
  28136. if (opt != null) {
  28137. extend(this, opt);
  28138. }
  28139. }
  28140. return SeriesDimensionDefine;
  28141. }();
  28142. var inner$4 = makeInner();
  28143. var dimTypeShort = {
  28144. float: 'f',
  28145. int: 'i',
  28146. ordinal: 'o',
  28147. number: 'n',
  28148. time: 't'
  28149. };
  28150. /**
  28151. * Represents the dimension requirement of a series.
  28152. *
  28153. * NOTICE:
  28154. * When there are too many dimensions in dataset and many series, only the used dimensions
  28155. * (i.e., used by coord sys and declared in `series.encode`) are add to `dimensionDefineList`.
  28156. * But users may query data by other unused dimension names.
  28157. * In this case, users can only query data if and only if they have defined dimension names
  28158. * via ec option, so we provide `getDimensionIndexFromSource`, which only query them from
  28159. * `source` dimensions.
  28160. */
  28161. var SeriesDataSchema =
  28162. /** @class */
  28163. function () {
  28164. function SeriesDataSchema(opt) {
  28165. this.dimensions = opt.dimensions;
  28166. this._dimOmitted = opt.dimensionOmitted;
  28167. this.source = opt.source;
  28168. this._fullDimCount = opt.fullDimensionCount;
  28169. this._updateDimOmitted(opt.dimensionOmitted);
  28170. }
  28171. SeriesDataSchema.prototype.isDimensionOmitted = function () {
  28172. return this._dimOmitted;
  28173. };
  28174. SeriesDataSchema.prototype._updateDimOmitted = function (dimensionOmitted) {
  28175. this._dimOmitted = dimensionOmitted;
  28176. if (!dimensionOmitted) {
  28177. return;
  28178. }
  28179. if (!this._dimNameMap) {
  28180. this._dimNameMap = ensureSourceDimNameMap(this.source);
  28181. }
  28182. };
  28183. /**
  28184. * @caution Can only be used when `dimensionOmitted: true`.
  28185. *
  28186. * Get index by user defined dimension name (i.e., not internal generate name).
  28187. * That is, get index from `dimensionsDefine`.
  28188. * If no `dimensionsDefine`, or no name get, return -1.
  28189. */
  28190. SeriesDataSchema.prototype.getSourceDimensionIndex = function (dimName) {
  28191. return retrieve2(this._dimNameMap.get(dimName), -1);
  28192. };
  28193. /**
  28194. * @caution Can only be used when `dimensionOmitted: true`.
  28195. *
  28196. * Notice: may return `null`/`undefined` if user not specify dimension names.
  28197. */
  28198. SeriesDataSchema.prototype.getSourceDimension = function (dimIndex) {
  28199. var dimensionsDefine = this.source.dimensionsDefine;
  28200. if (dimensionsDefine) {
  28201. return dimensionsDefine[dimIndex];
  28202. }
  28203. };
  28204. SeriesDataSchema.prototype.makeStoreSchema = function () {
  28205. var dimCount = this._fullDimCount;
  28206. var willRetrieveDataByName = shouldRetrieveDataByName(this.source);
  28207. var makeHashStrict = !shouldOmitUnusedDimensions(dimCount); // If source don't have dimensions or series don't omit unsed dimensions.
  28208. // Generate from seriesDimList directly
  28209. var dimHash = '';
  28210. var dims = [];
  28211. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < dimCount; fullDimIdx++) {
  28212. var property = void 0;
  28213. var type = void 0;
  28214. var ordinalMeta = void 0;
  28215. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28216. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28217. property = willRetrieveDataByName ? seriesDimDef.name : null;
  28218. type = seriesDimDef.type;
  28219. ordinalMeta = seriesDimDef.ordinalMeta;
  28220. seriesDimIdx++;
  28221. } else {
  28222. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28223. if (sourceDimDef) {
  28224. property = willRetrieveDataByName ? sourceDimDef.name : null;
  28225. type = sourceDimDef.type;
  28226. }
  28227. }
  28228. dims.push({
  28229. property: property,
  28230. type: type,
  28231. ordinalMeta: ordinalMeta
  28232. }); // If retrieving data by index,
  28233. // use <index, type, ordinalMeta> to determine whether data can be shared.
  28234. // (Because in this case there might be no dimension name defined in dataset, but indices always exists).
  28235. // (Indices are always 0, 1, 2, ..., so we can ignore them to shorten the hash).
  28236. // Otherwise if retrieving data by property name (like `data: [{aa: 123, bb: 765}, ...]`),
  28237. // use <property, type, ordinalMeta> in hash.
  28238. if (willRetrieveDataByName && property != null // For data stack, we have make sure each series has its own dim on this store.
  28239. // So we do not add property to hash to make sure they can share this store.
  28240. && (!seriesDimDef || !seriesDimDef.isCalculationCoord)) {
  28241. dimHash += makeHashStrict // Use escape character '`' in case that property name contains '$'.
  28242. ? property.replace(/\`/g, '`1').replace(/\$/g, '`2') // For better performance, when there are large dimensions, tolerant this defects that hardly meet.
  28243. : property;
  28244. }
  28245. dimHash += '$';
  28246. dimHash += dimTypeShort[type] || 'f';
  28247. if (ordinalMeta) {
  28248. dimHash += ordinalMeta.uid;
  28249. }
  28250. dimHash += '$';
  28251. } // Source from endpoint(usually series) will be read differently
  28252. // when seriesLayoutBy or startIndex(which is affected by sourceHeader) are different.
  28253. // So we use this three props as key.
  28254. var source = this.source;
  28255. var hash = [source.seriesLayoutBy, source.startIndex, dimHash].join('$$');
  28256. return {
  28257. dimensions: dims,
  28258. hash: hash
  28259. };
  28260. };
  28261. SeriesDataSchema.prototype.makeOutputDimensionNames = function () {
  28262. var result = [];
  28263. for (var fullDimIdx = 0, seriesDimIdx = 0; fullDimIdx < this._fullDimCount; fullDimIdx++) {
  28264. var name_1 = void 0;
  28265. var seriesDimDef = this.dimensions[seriesDimIdx]; // The list has been sorted by `storeDimIndex` asc.
  28266. if (seriesDimDef && seriesDimDef.storeDimIndex === fullDimIdx) {
  28267. if (!seriesDimDef.isCalculationCoord) {
  28268. name_1 = seriesDimDef.name;
  28269. }
  28270. seriesDimIdx++;
  28271. } else {
  28272. var sourceDimDef = this.getSourceDimension(fullDimIdx);
  28273. if (sourceDimDef) {
  28274. name_1 = sourceDimDef.name;
  28275. }
  28276. }
  28277. result.push(name_1);
  28278. }
  28279. return result;
  28280. };
  28281. SeriesDataSchema.prototype.appendCalculationDimension = function (dimDef) {
  28282. this.dimensions.push(dimDef);
  28283. dimDef.isCalculationCoord = true;
  28284. this._fullDimCount++; // If append dimension on a data store, consider the store
  28285. // might be shared by different series, series dimensions not
  28286. // really map to store dimensions.
  28287. this._updateDimOmitted(true);
  28288. };
  28289. return SeriesDataSchema;
  28290. }();
  28291. function isSeriesDataSchema(schema) {
  28292. return schema instanceof SeriesDataSchema;
  28293. }
  28294. function createDimNameMap(dimsDef) {
  28295. var dataDimNameMap = createHashMap();
  28296. for (var i = 0; i < (dimsDef || []).length; i++) {
  28297. var dimDefItemRaw = dimsDef[i];
  28298. var userDimName = isObject(dimDefItemRaw) ? dimDefItemRaw.name : dimDefItemRaw;
  28299. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28300. dataDimNameMap.set(userDimName, i);
  28301. }
  28302. }
  28303. return dataDimNameMap;
  28304. }
  28305. function ensureSourceDimNameMap(source) {
  28306. var innerSource = inner$4(source);
  28307. return innerSource.dimNameMap || (innerSource.dimNameMap = createDimNameMap(source.dimensionsDefine));
  28308. }
  28309. function shouldOmitUnusedDimensions(dimCount) {
  28310. return dimCount > 30;
  28311. }
  28312. var isObject$2 = isObject;
  28313. var map$1 = map;
  28314. var CtorInt32Array$1 = typeof Int32Array === 'undefined' ? Array : Int32Array; // Use prefix to avoid index to be the same as otherIdList[idx],
  28315. // which will cause weird update animation.
  28316. var ID_PREFIX = 'e\0\0';
  28317. var INDEX_NOT_FOUND = -1; // type SeriesDimensionIndex = DimensionIndex;
  28318. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_dimSummary', 'userOutput', '_rawData', '_dimValueGetter', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  28319. var CLONE_PROPERTIES = ['_approximateExtent']; // -----------------------------
  28320. // Internal method declarations:
  28321. // -----------------------------
  28322. var prepareInvertedIndex;
  28323. var getId;
  28324. var getIdNameFromStore;
  28325. var normalizeDimensions;
  28326. var transferProperties;
  28327. var cloneListForMapAndSample;
  28328. var makeIdFromName;
  28329. var SeriesData =
  28330. /** @class */
  28331. function () {
  28332. /**
  28333. * @param dimensionsInput.dimensions
  28334. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  28335. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  28336. */
  28337. function SeriesData(dimensionsInput, hostModel) {
  28338. this.type = 'list';
  28339. this._dimOmitted = false;
  28340. this._nameList = [];
  28341. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  28342. // Never used yet (not used yet).
  28343. // private _optionModels: Model[] = [];
  28344. // Global visual properties after visual coding
  28345. this._visual = {}; // Global layout properties.
  28346. this._layout = {}; // Item visual properties after visual coding
  28347. this._itemVisuals = []; // Item layout properties after layout
  28348. this._itemLayouts = []; // Graphic elements
  28349. this._graphicEls = []; // key: dim, value: extent
  28350. this._approximateExtent = {};
  28351. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  28352. // (in type `OptionDataItemObject`).
  28353. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  28354. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  28355. this.hasItemOption = false; // Methods that create a new list based on this list should be listed here.
  28356. // Notice that those method should `RETURN` the new list.
  28357. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  28358. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  28359. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  28360. var dimensions;
  28361. var assignStoreDimIdx = false;
  28362. if (isSeriesDataSchema(dimensionsInput)) {
  28363. dimensions = dimensionsInput.dimensions;
  28364. this._dimOmitted = dimensionsInput.isDimensionOmitted();
  28365. this._schema = dimensionsInput;
  28366. } else {
  28367. assignStoreDimIdx = true;
  28368. dimensions = dimensionsInput;
  28369. }
  28370. dimensions = dimensions || ['x', 'y'];
  28371. var dimensionInfos = {};
  28372. var dimensionNames = [];
  28373. var invertedIndicesMap = {};
  28374. var needsHasOwn = false;
  28375. var emptyObj = {};
  28376. for (var i = 0; i < dimensions.length; i++) {
  28377. // Use the original dimensions[i], where other flag props may exists.
  28378. var dimInfoInput = dimensions[i];
  28379. var dimensionInfo = isString(dimInfoInput) ? new SeriesDimensionDefine({
  28380. name: dimInfoInput
  28381. }) : !(dimInfoInput instanceof SeriesDimensionDefine) ? new SeriesDimensionDefine(dimInfoInput) : dimInfoInput;
  28382. var dimensionName = dimensionInfo.name;
  28383. dimensionInfo.type = dimensionInfo.type || 'float';
  28384. if (!dimensionInfo.coordDim) {
  28385. dimensionInfo.coordDim = dimensionName;
  28386. dimensionInfo.coordDimIndex = 0;
  28387. }
  28388. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  28389. dimensionNames.push(dimensionName);
  28390. dimensionInfos[dimensionName] = dimensionInfo;
  28391. if (emptyObj[dimensionName] != null) {
  28392. needsHasOwn = true;
  28393. }
  28394. if (dimensionInfo.createInvertedIndices) {
  28395. invertedIndicesMap[dimensionName] = [];
  28396. }
  28397. if (otherDims.itemName === 0) {
  28398. this._nameDimIdx = i;
  28399. }
  28400. if (otherDims.itemId === 0) {
  28401. this._idDimIdx = i;
  28402. }
  28403. if ("development" !== 'production') {
  28404. assert(assignStoreDimIdx || dimensionInfo.storeDimIndex >= 0);
  28405. }
  28406. if (assignStoreDimIdx) {
  28407. dimensionInfo.storeDimIndex = i;
  28408. }
  28409. }
  28410. this.dimensions = dimensionNames;
  28411. this._dimInfos = dimensionInfos;
  28412. this._initGetDimensionInfo(needsHasOwn);
  28413. this.hostModel = hostModel;
  28414. this._invertedIndicesMap = invertedIndicesMap;
  28415. if (this._dimOmitted) {
  28416. var dimIdxToName_1 = this._dimIdxToName = createHashMap();
  28417. each(dimensionNames, function (dimName) {
  28418. dimIdxToName_1.set(dimensionInfos[dimName].storeDimIndex, dimName);
  28419. });
  28420. }
  28421. }
  28422. /**
  28423. *
  28424. * Get concrete dimension name by dimension name or dimension index.
  28425. * If input a dimension name, do not validate whether the dimension name exits.
  28426. *
  28427. * @caution
  28428. * @param dim Must make sure the dimension is `SeriesDimensionLoose`.
  28429. * Because only those dimensions will have auto-generated dimension names if not
  28430. * have a user-specified name, and other dimensions will get a return of null/undefined.
  28431. *
  28432. * @notice Because of this reason, should better use `getDimensionIndex` instead, for examples:
  28433. * ```js
  28434. * const val = data.getStore().get(data.getDimensionIndex(dim), dataIdx);
  28435. * ```
  28436. *
  28437. * @return Concrete dim name.
  28438. */
  28439. SeriesData.prototype.getDimension = function (dim) {
  28440. var dimIdx = this._recognizeDimIndex(dim);
  28441. if (dimIdx == null) {
  28442. return dim;
  28443. }
  28444. dimIdx = dim;
  28445. if (!this._dimOmitted) {
  28446. return this.dimensions[dimIdx];
  28447. } // Retrieve from series dimension definition because it probably contains
  28448. // generated dimension name (like 'x', 'y').
  28449. var dimName = this._dimIdxToName.get(dimIdx);
  28450. if (dimName != null) {
  28451. return dimName;
  28452. }
  28453. var sourceDimDef = this._schema.getSourceDimension(dimIdx);
  28454. if (sourceDimDef) {
  28455. return sourceDimDef.name;
  28456. }
  28457. };
  28458. /**
  28459. * Get dimension index in data store. Return -1 if not found.
  28460. * Can be used to index value from getRawValue.
  28461. */
  28462. SeriesData.prototype.getDimensionIndex = function (dim) {
  28463. var dimIdx = this._recognizeDimIndex(dim);
  28464. if (dimIdx != null) {
  28465. return dimIdx;
  28466. }
  28467. if (dim == null) {
  28468. return -1;
  28469. }
  28470. var dimInfo = this._getDimInfo(dim);
  28471. return dimInfo ? dimInfo.storeDimIndex : this._dimOmitted ? this._schema.getSourceDimensionIndex(dim) : -1;
  28472. };
  28473. /**
  28474. * The meanings of the input parameter `dim`:
  28475. *
  28476. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  28477. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  28478. * + If dim is a number-like string (e.g., `"1"`):
  28479. * + If there is the same concrete dim name defined in `series.dimensions` or `dataset.dimensions`,
  28480. * it means that concrete name.
  28481. * + If not, it will be converted to a number, which means the index of the dimension.
  28482. * (why? because of the backward compatibility. We have been tolerating number-like string in
  28483. * dimension setting, although now it seems that it is not a good idea.)
  28484. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  28485. * if no dimension name is defined as `"1"`.
  28486. * + If dim is a not-number-like string, it means the concrete dim name.
  28487. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  28488. * or customized in `dimensions` property of option like `"age"`.
  28489. *
  28490. * @return recognized `DimensionIndex`. Otherwise return null/undefined (means that dim is `DimensionName`).
  28491. */
  28492. SeriesData.prototype._recognizeDimIndex = function (dim) {
  28493. if (isNumber(dim) // If being a number-like string but not being defined as a dimension name.
  28494. || dim != null && !isNaN(dim) && !this._getDimInfo(dim) && (!this._dimOmitted || this._schema.getSourceDimensionIndex(dim) < 0)) {
  28495. return +dim;
  28496. }
  28497. };
  28498. SeriesData.prototype._getStoreDimIndex = function (dim) {
  28499. var dimIdx = this.getDimensionIndex(dim);
  28500. if ("development" !== 'production') {
  28501. if (dimIdx == null) {
  28502. throw new Error('Unknown dimension ' + dim);
  28503. }
  28504. }
  28505. return dimIdx;
  28506. };
  28507. /**
  28508. * Get type and calculation info of particular dimension
  28509. * @param dim
  28510. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  28511. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  28512. */
  28513. SeriesData.prototype.getDimensionInfo = function (dim) {
  28514. // Do not clone, because there may be categories in dimInfo.
  28515. return this._getDimInfo(this.getDimension(dim));
  28516. };
  28517. SeriesData.prototype._initGetDimensionInfo = function (needsHasOwn) {
  28518. var dimensionInfos = this._dimInfos;
  28519. this._getDimInfo = needsHasOwn ? function (dimName) {
  28520. return dimensionInfos.hasOwnProperty(dimName) ? dimensionInfos[dimName] : undefined;
  28521. } : function (dimName) {
  28522. return dimensionInfos[dimName];
  28523. };
  28524. };
  28525. /**
  28526. * concrete dimension name list on coord.
  28527. */
  28528. SeriesData.prototype.getDimensionsOnCoord = function () {
  28529. return this._dimSummary.dataDimsOnCoord.slice();
  28530. };
  28531. SeriesData.prototype.mapDimension = function (coordDim, idx) {
  28532. var dimensionsSummary = this._dimSummary;
  28533. if (idx == null) {
  28534. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  28535. }
  28536. var dims = dimensionsSummary.encode[coordDim];
  28537. return dims ? dims[idx] : null;
  28538. };
  28539. SeriesData.prototype.mapDimensionsAll = function (coordDim) {
  28540. var dimensionsSummary = this._dimSummary;
  28541. var dims = dimensionsSummary.encode[coordDim];
  28542. return (dims || []).slice();
  28543. };
  28544. SeriesData.prototype.getStore = function () {
  28545. return this._store;
  28546. };
  28547. /**
  28548. * Initialize from data
  28549. * @param data source or data or data store.
  28550. * @param nameList The name of a datum is used on data diff and
  28551. * default label/tooltip.
  28552. * A name can be specified in encode.itemName,
  28553. * or dataItem.name (only for series option data),
  28554. * or provided in nameList from outside.
  28555. */
  28556. SeriesData.prototype.initData = function (data, nameList, dimValueGetter) {
  28557. var _this = this;
  28558. var store;
  28559. if (data instanceof DataStore) {
  28560. store = data;
  28561. }
  28562. if (!store) {
  28563. var dimensions = this.dimensions;
  28564. var provider = isSourceInstance(data) || isArrayLike(data) ? new DefaultDataProvider(data, dimensions.length) : data;
  28565. store = new DataStore();
  28566. var dimensionInfos = map$1(dimensions, function (dimName) {
  28567. return {
  28568. type: _this._dimInfos[dimName].type,
  28569. property: dimName
  28570. };
  28571. });
  28572. store.initData(provider, dimensionInfos, dimValueGetter);
  28573. }
  28574. this._store = store; // Reset
  28575. this._nameList = (nameList || []).slice();
  28576. this._idList = [];
  28577. this._nameRepeatCount = {};
  28578. this._doInit(0, store.count()); // Cache summary info for fast visit. See "dimensionHelper".
  28579. // Needs to be initialized after store is prepared.
  28580. this._dimSummary = summarizeDimensions(this, this._schema);
  28581. this.userOutput = this._dimSummary.userOutput;
  28582. };
  28583. /**
  28584. * Caution: Can be only called on raw data (before `this._indices` created).
  28585. */
  28586. SeriesData.prototype.appendData = function (data) {
  28587. var range = this._store.appendData(data);
  28588. this._doInit(range[0], range[1]);
  28589. };
  28590. /**
  28591. * Caution: Can be only called on raw data (before `this._indices` created).
  28592. * This method does not modify `rawData` (`dataProvider`), but only
  28593. * add values to store.
  28594. *
  28595. * The final count will be increased by `Math.max(values.length, names.length)`.
  28596. *
  28597. * @param values That is the SourceType: 'arrayRows', like
  28598. * [
  28599. * [12, 33, 44],
  28600. * [NaN, 43, 1],
  28601. * ['-', 'asdf', 0]
  28602. * ]
  28603. * Each item is exactly corresponding to a dimension.
  28604. */
  28605. SeriesData.prototype.appendValues = function (values, names) {
  28606. var _a = this._store.appendValues(values, names.length),
  28607. start = _a.start,
  28608. end = _a.end;
  28609. var shouldMakeIdFromName = this._shouldMakeIdFromName();
  28610. this._updateOrdinalMeta();
  28611. if (names) {
  28612. for (var idx = start; idx < end; idx++) {
  28613. var sourceIdx = idx - start;
  28614. this._nameList[idx] = names[sourceIdx];
  28615. if (shouldMakeIdFromName) {
  28616. makeIdFromName(this, idx);
  28617. }
  28618. }
  28619. }
  28620. };
  28621. SeriesData.prototype._updateOrdinalMeta = function () {
  28622. var store = this._store;
  28623. var dimensions = this.dimensions;
  28624. for (var i = 0; i < dimensions.length; i++) {
  28625. var dimInfo = this._dimInfos[dimensions[i]];
  28626. if (dimInfo.ordinalMeta) {
  28627. store.collectOrdinalMeta(dimInfo.storeDimIndex, dimInfo.ordinalMeta);
  28628. }
  28629. }
  28630. };
  28631. SeriesData.prototype._shouldMakeIdFromName = function () {
  28632. var provider = this._store.getProvider();
  28633. return this._idDimIdx == null && provider.getSource().sourceFormat !== SOURCE_FORMAT_TYPED_ARRAY && !provider.fillStorage;
  28634. };
  28635. SeriesData.prototype._doInit = function (start, end) {
  28636. if (start >= end) {
  28637. return;
  28638. }
  28639. var store = this._store;
  28640. var provider = store.getProvider();
  28641. this._updateOrdinalMeta();
  28642. var nameList = this._nameList;
  28643. var idList = this._idList;
  28644. var sourceFormat = provider.getSource().sourceFormat;
  28645. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL; // Each data item is value
  28646. // [1, 2]
  28647. // 2
  28648. // Bar chart, line chart which uses category axis
  28649. // only gives the 'y' value. 'x' value is the indices of category
  28650. // Use a tempValue to normalize the value to be a (x, y) value
  28651. // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  28652. // This kind of ids and names are always stored `_nameList` and `_idList`.
  28653. if (isFormatOriginal && !provider.pure) {
  28654. var sharedDataItem = [];
  28655. for (var idx = start; idx < end; idx++) {
  28656. // NOTICE: Try not to write things into dataItem
  28657. var dataItem = provider.getItem(idx, sharedDataItem);
  28658. if (!this.hasItemOption && isDataItemOption(dataItem)) {
  28659. this.hasItemOption = true;
  28660. }
  28661. if (dataItem) {
  28662. var itemName = dataItem.name;
  28663. if (nameList[idx] == null && itemName != null) {
  28664. nameList[idx] = convertOptionIdName(itemName, null);
  28665. }
  28666. var itemId = dataItem.id;
  28667. if (idList[idx] == null && itemId != null) {
  28668. idList[idx] = convertOptionIdName(itemId, null);
  28669. }
  28670. }
  28671. }
  28672. }
  28673. if (this._shouldMakeIdFromName()) {
  28674. for (var idx = start; idx < end; idx++) {
  28675. makeIdFromName(this, idx);
  28676. }
  28677. }
  28678. prepareInvertedIndex(this);
  28679. };
  28680. /**
  28681. * PENDING: In fact currently this function is only used to short-circuit
  28682. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  28683. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  28684. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  28685. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  28686. * But if we add "custom data filter" in future, which is not "axis related", this method may
  28687. * be still needed.
  28688. *
  28689. * Optimize for the scenario that data is filtered by a given extent.
  28690. * Consider that if data amount is more than hundreds of thousand,
  28691. * extent calculation will cost more than 10ms and the cache will
  28692. * be erased because of the filtering.
  28693. */
  28694. SeriesData.prototype.getApproximateExtent = function (dim) {
  28695. return this._approximateExtent[dim] || this._store.getDataExtent(this._getStoreDimIndex(dim));
  28696. };
  28697. /**
  28698. * Calculate extent on a filtered data might be time consuming.
  28699. * Approximate extent is only used for: calculate extent of filtered data outside.
  28700. */
  28701. SeriesData.prototype.setApproximateExtent = function (extent, dim) {
  28702. dim = this.getDimension(dim);
  28703. this._approximateExtent[dim] = extent.slice();
  28704. };
  28705. SeriesData.prototype.getCalculationInfo = function (key) {
  28706. return this._calculationInfo[key];
  28707. };
  28708. SeriesData.prototype.setCalculationInfo = function (key, value) {
  28709. isObject$2(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  28710. };
  28711. /**
  28712. * @return Never be null/undefined. `number` will be converted to string. Because:
  28713. * In most cases, name is used in display, where returning a string is more convenient.
  28714. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28715. * rule that name `2` equals to name `'2'`.
  28716. */
  28717. SeriesData.prototype.getName = function (idx) {
  28718. var rawIndex = this.getRawIndex(idx);
  28719. var name = this._nameList[rawIndex];
  28720. if (name == null && this._nameDimIdx != null) {
  28721. name = getIdNameFromStore(this, this._nameDimIdx, rawIndex);
  28722. }
  28723. if (name == null) {
  28724. name = '';
  28725. }
  28726. return name;
  28727. };
  28728. SeriesData.prototype._getCategory = function (dimIdx, idx) {
  28729. var ordinal = this._store.get(dimIdx, idx);
  28730. var ordinalMeta = this._store.getOrdinalMeta(dimIdx);
  28731. if (ordinalMeta) {
  28732. return ordinalMeta.categories[ordinal];
  28733. }
  28734. return ordinal;
  28735. };
  28736. /**
  28737. * @return Never null/undefined. `number` will be converted to string. Because:
  28738. * In all cases having encountered at present, id is used in making diff comparison, which
  28739. * are usually based on hash map. We can keep the rule that the internal id are always string
  28740. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28741. */
  28742. SeriesData.prototype.getId = function (idx) {
  28743. return getId(this, this.getRawIndex(idx));
  28744. };
  28745. SeriesData.prototype.count = function () {
  28746. return this._store.count();
  28747. };
  28748. /**
  28749. * Get value. Return NaN if idx is out of range.
  28750. *
  28751. * @notice Should better to use `data.getStore().get(dimIndex, dataIdx)` instead.
  28752. */
  28753. SeriesData.prototype.get = function (dim, idx) {
  28754. var store = this._store;
  28755. var dimInfo = this._dimInfos[dim];
  28756. if (dimInfo) {
  28757. return store.get(dimInfo.storeDimIndex, idx);
  28758. }
  28759. };
  28760. /**
  28761. * @notice Should better to use `data.getStore().getByRawIndex(dimIndex, dataIdx)` instead.
  28762. */
  28763. SeriesData.prototype.getByRawIndex = function (dim, rawIdx) {
  28764. var store = this._store;
  28765. var dimInfo = this._dimInfos[dim];
  28766. if (dimInfo) {
  28767. return store.getByRawIndex(dimInfo.storeDimIndex, rawIdx);
  28768. }
  28769. };
  28770. SeriesData.prototype.getIndices = function () {
  28771. return this._store.getIndices();
  28772. };
  28773. SeriesData.prototype.getDataExtent = function (dim) {
  28774. return this._store.getDataExtent(this._getStoreDimIndex(dim));
  28775. };
  28776. SeriesData.prototype.getSum = function (dim) {
  28777. return this._store.getSum(this._getStoreDimIndex(dim));
  28778. };
  28779. SeriesData.prototype.getMedian = function (dim) {
  28780. return this._store.getMedian(this._getStoreDimIndex(dim));
  28781. };
  28782. SeriesData.prototype.getValues = function (dimensions, idx) {
  28783. var _this = this;
  28784. var store = this._store;
  28785. return isArray(dimensions) ? store.getValues(map$1(dimensions, function (dim) {
  28786. return _this._getStoreDimIndex(dim);
  28787. }), idx) : store.getValues(dimensions);
  28788. };
  28789. /**
  28790. * If value is NaN. Including '-'
  28791. * Only check the coord dimensions.
  28792. */
  28793. SeriesData.prototype.hasValue = function (idx) {
  28794. var dataDimIndicesOnCoord = this._dimSummary.dataDimIndicesOnCoord;
  28795. for (var i = 0, len = dataDimIndicesOnCoord.length; i < len; i++) {
  28796. // Ordinal type originally can be string or number.
  28797. // But when an ordinal type is used on coord, it can
  28798. // not be string but only number. So we can also use isNaN.
  28799. if (isNaN(this._store.get(dataDimIndicesOnCoord[i], idx))) {
  28800. return false;
  28801. }
  28802. }
  28803. return true;
  28804. };
  28805. /**
  28806. * Retrieve the index with given name
  28807. */
  28808. SeriesData.prototype.indexOfName = function (name) {
  28809. for (var i = 0, len = this._store.count(); i < len; i++) {
  28810. if (this.getName(i) === name) {
  28811. return i;
  28812. }
  28813. }
  28814. return -1;
  28815. };
  28816. SeriesData.prototype.getRawIndex = function (idx) {
  28817. return this._store.getRawIndex(idx);
  28818. };
  28819. SeriesData.prototype.indexOfRawIndex = function (rawIndex) {
  28820. return this._store.indexOfRawIndex(rawIndex);
  28821. };
  28822. /**
  28823. * Only support the dimension which inverted index created.
  28824. * Do not support other cases until required.
  28825. * @param dim concrete dim
  28826. * @param value ordinal index
  28827. * @return rawIndex
  28828. */
  28829. SeriesData.prototype.rawIndexOf = function (dim, value) {
  28830. var invertedIndices = dim && this._invertedIndicesMap[dim];
  28831. if ("development" !== 'production') {
  28832. if (!invertedIndices) {
  28833. throw new Error('Do not supported yet');
  28834. }
  28835. }
  28836. var rawIndex = invertedIndices[value];
  28837. if (rawIndex == null || isNaN(rawIndex)) {
  28838. return INDEX_NOT_FOUND;
  28839. }
  28840. return rawIndex;
  28841. };
  28842. /**
  28843. * Retrieve the index of nearest value
  28844. * @param dim
  28845. * @param value
  28846. * @param [maxDistance=Infinity]
  28847. * @return If and only if multiple indices has
  28848. * the same value, they are put to the result.
  28849. */
  28850. SeriesData.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28851. return this._store.indicesOfNearest(this._getStoreDimIndex(dim), value, maxDistance);
  28852. };
  28853. SeriesData.prototype.each = function (dims, cb, ctx) {
  28854. if (isFunction(dims)) {
  28855. ctx = cb;
  28856. cb = dims;
  28857. dims = [];
  28858. } // ctxCompat just for compat echarts3
  28859. var fCtx = ctx || this;
  28860. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28861. this._store.each(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28862. };
  28863. SeriesData.prototype.filterSelf = function (dims, cb, ctx) {
  28864. if (isFunction(dims)) {
  28865. ctx = cb;
  28866. cb = dims;
  28867. dims = [];
  28868. } // ctxCompat just for compat echarts3
  28869. var fCtx = ctx || this;
  28870. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28871. this._store = this._store.filter(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28872. return this;
  28873. };
  28874. /**
  28875. * Select data in range. (For optimization of filter)
  28876. * (Manually inline code, support 5 million data filtering in data zoom.)
  28877. */
  28878. SeriesData.prototype.selectRange = function (range) {
  28879. var _this = this;
  28880. var innerRange = {};
  28881. var dims = keys(range);
  28882. each(dims, function (dim) {
  28883. var dimIdx = _this._getStoreDimIndex(dim);
  28884. innerRange[dimIdx] = range[dim];
  28885. });
  28886. this._store = this._store.selectRange(innerRange);
  28887. return this;
  28888. };
  28889. /* eslint-enable max-len */
  28890. SeriesData.prototype.mapArray = function (dims, cb, ctx) {
  28891. if (isFunction(dims)) {
  28892. ctx = cb;
  28893. cb = dims;
  28894. dims = [];
  28895. } // ctxCompat just for compat echarts3
  28896. ctx = ctx || this;
  28897. var result = [];
  28898. this.each(dims, function () {
  28899. result.push(cb && cb.apply(this, arguments));
  28900. }, ctx);
  28901. return result;
  28902. };
  28903. SeriesData.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28904. var fCtx = ctx || ctxCompat || this;
  28905. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this);
  28906. var list = cloneListForMapAndSample(this);
  28907. list._store = this._store.map(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28908. return list;
  28909. };
  28910. SeriesData.prototype.modify = function (dims, cb, ctx, ctxCompat) {
  28911. var _this = this; // ctxCompat just for compat echarts3
  28912. var fCtx = ctx || ctxCompat || this;
  28913. if ("development" !== 'production') {
  28914. each(normalizeDimensions(dims), function (dim) {
  28915. var dimInfo = _this.getDimensionInfo(dim);
  28916. if (!dimInfo.isCalculationCoord) {
  28917. console.error('Danger: only stack dimension can be modified');
  28918. }
  28919. });
  28920. }
  28921. var dimIndices = map$1(normalizeDimensions(dims), this._getStoreDimIndex, this); // If do shallow clone here, if there are too many stacked series,
  28922. // it still cost lots of memory, because `_store.dimensions` are not shared.
  28923. // We should consider there probably be shallow clone happen in each series
  28924. // in consequent filter/map.
  28925. this._store.modify(dimIndices, fCtx ? bind(cb, fCtx) : cb);
  28926. };
  28927. /**
  28928. * Large data down sampling on given dimension
  28929. * @param sampleIndex Sample index for name and id
  28930. */
  28931. SeriesData.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28932. var list = cloneListForMapAndSample(this);
  28933. list._store = this._store.downSample(this._getStoreDimIndex(dimension), rate, sampleValue, sampleIndex);
  28934. return list;
  28935. };
  28936. /**
  28937. * Large data down sampling using largest-triangle-three-buckets
  28938. * @param {string} valueDimension
  28939. * @param {number} targetCount
  28940. */
  28941. SeriesData.prototype.lttbDownSample = function (valueDimension, rate) {
  28942. var list = cloneListForMapAndSample(this);
  28943. list._store = this._store.lttbDownSample(this._getStoreDimIndex(valueDimension), rate);
  28944. return list;
  28945. };
  28946. SeriesData.prototype.getRawDataItem = function (idx) {
  28947. return this._store.getRawDataItem(idx);
  28948. };
  28949. /**
  28950. * Get model of one data item.
  28951. */
  28952. // TODO: Type of data item
  28953. SeriesData.prototype.getItemModel = function (idx) {
  28954. var hostModel = this.hostModel;
  28955. var dataItem = this.getRawDataItem(idx);
  28956. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28957. };
  28958. /**
  28959. * Create a data differ
  28960. */
  28961. SeriesData.prototype.diff = function (otherList) {
  28962. var thisList = this;
  28963. return new DataDiffer(otherList ? otherList.getStore().getIndices() : [], this.getStore().getIndices(), function (idx) {
  28964. return getId(otherList, idx);
  28965. }, function (idx) {
  28966. return getId(thisList, idx);
  28967. });
  28968. };
  28969. /**
  28970. * Get visual property.
  28971. */
  28972. SeriesData.prototype.getVisual = function (key) {
  28973. var visual = this._visual;
  28974. return visual && visual[key];
  28975. };
  28976. SeriesData.prototype.setVisual = function (kvObj, val) {
  28977. this._visual = this._visual || {};
  28978. if (isObject$2(kvObj)) {
  28979. extend(this._visual, kvObj);
  28980. } else {
  28981. this._visual[kvObj] = val;
  28982. }
  28983. };
  28984. /**
  28985. * Get visual property of single data item
  28986. */
  28987. // eslint-disable-next-line
  28988. SeriesData.prototype.getItemVisual = function (idx, key) {
  28989. var itemVisual = this._itemVisuals[idx];
  28990. var val = itemVisual && itemVisual[key];
  28991. if (val == null) {
  28992. // Use global visual property
  28993. return this.getVisual(key);
  28994. }
  28995. return val;
  28996. };
  28997. /**
  28998. * If exists visual property of single data item
  28999. */
  29000. SeriesData.prototype.hasItemVisual = function () {
  29001. return this._itemVisuals.length > 0;
  29002. };
  29003. /**
  29004. * Make sure itemVisual property is unique
  29005. */
  29006. // TODO: use key to save visual to reduce memory.
  29007. SeriesData.prototype.ensureUniqueItemVisual = function (idx, key) {
  29008. var itemVisuals = this._itemVisuals;
  29009. var itemVisual = itemVisuals[idx];
  29010. if (!itemVisual) {
  29011. itemVisual = itemVisuals[idx] = {};
  29012. }
  29013. var val = itemVisual[key];
  29014. if (val == null) {
  29015. val = this.getVisual(key); // TODO Performance?
  29016. if (isArray(val)) {
  29017. val = val.slice();
  29018. } else if (isObject$2(val)) {
  29019. val = extend({}, val);
  29020. }
  29021. itemVisual[key] = val;
  29022. }
  29023. return val;
  29024. }; // eslint-disable-next-line
  29025. SeriesData.prototype.setItemVisual = function (idx, key, value) {
  29026. var itemVisual = this._itemVisuals[idx] || {};
  29027. this._itemVisuals[idx] = itemVisual;
  29028. if (isObject$2(key)) {
  29029. extend(itemVisual, key);
  29030. } else {
  29031. itemVisual[key] = value;
  29032. }
  29033. };
  29034. /**
  29035. * Clear itemVisuals and list visual.
  29036. */
  29037. SeriesData.prototype.clearAllVisual = function () {
  29038. this._visual = {};
  29039. this._itemVisuals = [];
  29040. };
  29041. SeriesData.prototype.setLayout = function (key, val) {
  29042. isObject$2(key) ? extend(this._layout, key) : this._layout[key] = val;
  29043. };
  29044. /**
  29045. * Get layout property.
  29046. */
  29047. SeriesData.prototype.getLayout = function (key) {
  29048. return this._layout[key];
  29049. };
  29050. /**
  29051. * Get layout of single data item
  29052. */
  29053. SeriesData.prototype.getItemLayout = function (idx) {
  29054. return this._itemLayouts[idx];
  29055. };
  29056. /**
  29057. * Set layout of single data item
  29058. */
  29059. SeriesData.prototype.setItemLayout = function (idx, layout, merge) {
  29060. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  29061. };
  29062. /**
  29063. * Clear all layout of single data item
  29064. */
  29065. SeriesData.prototype.clearItemLayouts = function () {
  29066. this._itemLayouts.length = 0;
  29067. };
  29068. /**
  29069. * Set graphic element relative to data. It can be set as null
  29070. */
  29071. SeriesData.prototype.setItemGraphicEl = function (idx, el) {
  29072. var seriesIndex = this.hostModel && this.hostModel.seriesIndex;
  29073. setCommonECData(seriesIndex, this.dataType, idx, el);
  29074. this._graphicEls[idx] = el;
  29075. };
  29076. SeriesData.prototype.getItemGraphicEl = function (idx) {
  29077. return this._graphicEls[idx];
  29078. };
  29079. SeriesData.prototype.eachItemGraphicEl = function (cb, context) {
  29080. each(this._graphicEls, function (el, idx) {
  29081. if (el) {
  29082. cb && cb.call(context, el, idx);
  29083. }
  29084. });
  29085. };
  29086. /**
  29087. * Shallow clone a new list except visual and layout properties, and graph elements.
  29088. * New list only change the indices.
  29089. */
  29090. SeriesData.prototype.cloneShallow = function (list) {
  29091. if (!list) {
  29092. list = new SeriesData(this._schema ? this._schema : map$1(this.dimensions, this._getDimInfo, this), this.hostModel);
  29093. }
  29094. transferProperties(list, this);
  29095. list._store = this._store;
  29096. return list;
  29097. };
  29098. /**
  29099. * Wrap some method to add more feature
  29100. */
  29101. SeriesData.prototype.wrapMethod = function (methodName, injectFunction) {
  29102. var originalMethod = this[methodName];
  29103. if (!isFunction(originalMethod)) {
  29104. return;
  29105. }
  29106. this.__wrappedMethods = this.__wrappedMethods || [];
  29107. this.__wrappedMethods.push(methodName);
  29108. this[methodName] = function () {
  29109. var res = originalMethod.apply(this, arguments);
  29110. return injectFunction.apply(this, [res].concat(slice(arguments)));
  29111. };
  29112. }; // ----------------------------------------------------------
  29113. // A work around for internal method visiting private member.
  29114. // ----------------------------------------------------------
  29115. SeriesData.internalField = function () {
  29116. prepareInvertedIndex = function (data) {
  29117. var invertedIndicesMap = data._invertedIndicesMap;
  29118. each(invertedIndicesMap, function (invertedIndices, dim) {
  29119. var dimInfo = data._dimInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  29120. var ordinalMeta = dimInfo.ordinalMeta;
  29121. var store = data._store;
  29122. if (ordinalMeta) {
  29123. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array$1(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  29124. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  29125. for (var i = 0; i < invertedIndices.length; i++) {
  29126. invertedIndices[i] = INDEX_NOT_FOUND;
  29127. }
  29128. for (var i = 0; i < store.count(); i++) {
  29129. // Only support the case that all values are distinct.
  29130. invertedIndices[store.get(dimInfo.storeDimIndex, i)] = i;
  29131. }
  29132. }
  29133. });
  29134. };
  29135. getIdNameFromStore = function (data, dimIdx, idx) {
  29136. return convertOptionIdName(data._getCategory(dimIdx, idx), null);
  29137. };
  29138. /**
  29139. * @see the comment of `List['getId']`.
  29140. */
  29141. getId = function (data, rawIndex) {
  29142. var id = data._idList[rawIndex];
  29143. if (id == null && data._idDimIdx != null) {
  29144. id = getIdNameFromStore(data, data._idDimIdx, rawIndex);
  29145. }
  29146. if (id == null) {
  29147. id = ID_PREFIX + rawIndex;
  29148. }
  29149. return id;
  29150. };
  29151. normalizeDimensions = function (dimensions) {
  29152. if (!isArray(dimensions)) {
  29153. dimensions = dimensions != null ? [dimensions] : [];
  29154. }
  29155. return dimensions;
  29156. };
  29157. /**
  29158. * Data in excludeDimensions is copied, otherwise transferred.
  29159. */
  29160. cloneListForMapAndSample = function (original) {
  29161. 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
  29162. transferProperties(list, original);
  29163. return list;
  29164. };
  29165. transferProperties = function (target, source) {
  29166. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  29167. if (source.hasOwnProperty(propName)) {
  29168. target[propName] = source[propName];
  29169. }
  29170. });
  29171. target.__wrappedMethods = source.__wrappedMethods;
  29172. each(CLONE_PROPERTIES, function (propName) {
  29173. target[propName] = clone(source[propName]);
  29174. });
  29175. target._calculationInfo = extend({}, source._calculationInfo);
  29176. };
  29177. makeIdFromName = function (data, idx) {
  29178. var nameList = data._nameList;
  29179. var idList = data._idList;
  29180. var nameDimIdx = data._nameDimIdx;
  29181. var idDimIdx = data._idDimIdx;
  29182. var name = nameList[idx];
  29183. var id = idList[idx];
  29184. if (name == null && nameDimIdx != null) {
  29185. nameList[idx] = name = getIdNameFromStore(data, nameDimIdx, idx);
  29186. }
  29187. if (id == null && idDimIdx != null) {
  29188. idList[idx] = id = getIdNameFromStore(data, idDimIdx, idx);
  29189. }
  29190. if (id == null && name != null) {
  29191. var nameRepeatCount = data._nameRepeatCount;
  29192. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  29193. id = name;
  29194. if (nmCnt > 1) {
  29195. id += '__ec__' + nmCnt;
  29196. }
  29197. idList[idx] = id;
  29198. }
  29199. };
  29200. }();
  29201. return SeriesData;
  29202. }();
  29203. /**
  29204. * For outside usage compat (like echarts-gl are using it).
  29205. */
  29206. function createDimensions(source, opt) {
  29207. return prepareSeriesDataSchema(source, opt).dimensions;
  29208. }
  29209. /**
  29210. * This method builds the relationship between:
  29211. * + "what the coord sys or series requires (see `coordDimensions`)",
  29212. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimensionsDefine` and `opt.encodeDefine`)"
  29213. * + "what the data source provids (see `source`)".
  29214. *
  29215. * Some guess strategy will be adapted if user does not define something.
  29216. * If no 'value' dimension specified, the first no-named dimension will be
  29217. * named as 'value'.
  29218. *
  29219. * @return The results are always sorted by `storeDimIndex` asc.
  29220. */
  29221. function prepareSeriesDataSchema( // TODO: TYPE completeDimensions type
  29222. source, opt) {
  29223. if (!isSourceInstance(source)) {
  29224. source = createSourceFromSeriesDataOption(source);
  29225. }
  29226. opt = opt || {};
  29227. var sysDims = opt.coordDimensions || [];
  29228. var dimsDef = opt.dimensionsDefine || source.dimensionsDefine || [];
  29229. var coordDimNameMap = createHashMap();
  29230. var resultList = [];
  29231. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimensionsCount); // Try to ignore unused dimensions if sharing a high dimension datastore
  29232. // 30 is an experience value.
  29233. var omitUnusedDimensions = opt.canOmitUnusedDimensions && shouldOmitUnusedDimensions(dimCount);
  29234. var isUsingSourceDimensionsDef = dimsDef === source.dimensionsDefine;
  29235. var dataDimNameMap = isUsingSourceDimensionsDef ? ensureSourceDimNameMap(source) : createDimNameMap(dimsDef);
  29236. var encodeDef = opt.encodeDefine;
  29237. if (!encodeDef && opt.encodeDefaulter) {
  29238. encodeDef = opt.encodeDefaulter(source, dimCount);
  29239. }
  29240. var encodeDefMap = createHashMap(encodeDef);
  29241. var indicesMap = new CtorInt32Array(dimCount);
  29242. for (var i = 0; i < indicesMap.length; i++) {
  29243. indicesMap[i] = -1;
  29244. }
  29245. function getResultItem(dimIdx) {
  29246. var idx = indicesMap[dimIdx];
  29247. if (idx < 0) {
  29248. var dimDefItemRaw = dimsDef[dimIdx];
  29249. var dimDefItem = isObject(dimDefItemRaw) ? dimDefItemRaw : {
  29250. name: dimDefItemRaw
  29251. };
  29252. var resultItem = new SeriesDimensionDefine();
  29253. var userDimName = dimDefItem.name;
  29254. if (userDimName != null && dataDimNameMap.get(userDimName) != null) {
  29255. // Only if `series.dimensions` is defined in option
  29256. // displayName, will be set, and dimension will be displayed vertically in
  29257. // tooltip by default.
  29258. resultItem.name = resultItem.displayName = userDimName;
  29259. }
  29260. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  29261. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  29262. var newIdx = resultList.length;
  29263. indicesMap[dimIdx] = newIdx;
  29264. resultItem.storeDimIndex = dimIdx;
  29265. resultList.push(resultItem);
  29266. return resultItem;
  29267. }
  29268. return resultList[idx];
  29269. }
  29270. if (!omitUnusedDimensions) {
  29271. for (var i = 0; i < dimCount; i++) {
  29272. getResultItem(i);
  29273. }
  29274. } // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  29275. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  29276. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  29277. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  29278. // this case.
  29279. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  29280. encodeDefMap.set(coordDim, false);
  29281. return;
  29282. }
  29283. var validDataDims = encodeDefMap.set(coordDim, []);
  29284. each(dataDims, function (resultDimIdxOrName, idx) {
  29285. // The input resultDimIdx can be dim name or index.
  29286. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  29287. if (resultDimIdx != null && resultDimIdx < dimCount) {
  29288. validDataDims[idx] = resultDimIdx;
  29289. applyDim(getResultItem(resultDimIdx), coordDim, idx);
  29290. }
  29291. });
  29292. }); // Apply templates and default order from `sysDims`.
  29293. var availDimIdx = 0;
  29294. each(sysDims, function (sysDimItemRaw) {
  29295. var coordDim;
  29296. var sysDimItemDimsDef;
  29297. var sysDimItemOtherDims;
  29298. var sysDimItem;
  29299. if (isString(sysDimItemRaw)) {
  29300. coordDim = sysDimItemRaw;
  29301. sysDimItem = {};
  29302. } else {
  29303. sysDimItem = sysDimItemRaw;
  29304. coordDim = sysDimItem.name;
  29305. var ordinalMeta = sysDimItem.ordinalMeta;
  29306. sysDimItem.ordinalMeta = null;
  29307. sysDimItem = extend({}, sysDimItem);
  29308. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  29309. sysDimItemDimsDef = sysDimItem.dimsDef;
  29310. sysDimItemOtherDims = sysDimItem.otherDims;
  29311. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  29312. }
  29313. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  29314. if (dataDims === false) {
  29315. return;
  29316. }
  29317. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  29318. if (!dataDims.length) {
  29319. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  29320. while (availDimIdx < dimCount && getResultItem(availDimIdx).coordDim != null) {
  29321. availDimIdx++;
  29322. }
  29323. availDimIdx < dimCount && dataDims.push(availDimIdx++);
  29324. }
  29325. } // Apply templates.
  29326. each(dataDims, function (resultDimIdx, coordDimIndex) {
  29327. var resultItem = getResultItem(resultDimIdx); // Coordinate system has a higher priority on dim type than source.
  29328. if (isUsingSourceDimensionsDef && sysDimItem.type != null) {
  29329. resultItem.type = sysDimItem.type;
  29330. }
  29331. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  29332. if (resultItem.name == null && sysDimItemDimsDef) {
  29333. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  29334. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  29335. name: sysDimItemDimsDefItem
  29336. });
  29337. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  29338. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  29339. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  29340. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  29341. });
  29342. });
  29343. function applyDim(resultItem, coordDim, coordDimIndex) {
  29344. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  29345. resultItem.otherDims[coordDim] = coordDimIndex;
  29346. } else {
  29347. resultItem.coordDim = coordDim;
  29348. resultItem.coordDimIndex = coordDimIndex;
  29349. coordDimNameMap.set(coordDim, true);
  29350. }
  29351. } // Make sure the first extra dim is 'value'.
  29352. var generateCoord = opt.generateCoord;
  29353. var generateCoordCount = opt.generateCoordCount;
  29354. var fromZero = generateCoordCount != null;
  29355. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29356. var extra = generateCoord || 'value';
  29357. function ifNoNameFillWithCoordName(resultItem) {
  29358. if (resultItem.name == null) {
  29359. // Duplication will be removed in the next step.
  29360. resultItem.name = resultItem.coordDim;
  29361. }
  29362. } // Set dim `name` and other `coordDim` and other props.
  29363. if (!omitUnusedDimensions) {
  29364. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29365. var resultItem = getResultItem(resultDimIdx);
  29366. var coordDim = resultItem.coordDim;
  29367. if (coordDim == null) {
  29368. // TODO no need to generate coordDim for isExtraCoord?
  29369. resultItem.coordDim = genCoordDimName(extra, coordDimNameMap, fromZero);
  29370. resultItem.coordDimIndex = 0; // Series specified generateCoord is using out.
  29371. if (!generateCoord || generateCoordCount <= 0) {
  29372. resultItem.isExtraCoord = true;
  29373. }
  29374. generateCoordCount--;
  29375. }
  29376. ifNoNameFillWithCoordName(resultItem);
  29377. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  29378. // {
  29379. // dataset: {source: [
  29380. // ['2001', 123],
  29381. // ['2002', 456],
  29382. // ...
  29383. // ['The others', 987],
  29384. // ]},
  29385. // series: {type: 'pie'}
  29386. // }
  29387. // The first column should better be treated as a "ordinal" although it
  29388. // might not be detected as an "ordinal" by `guessOrdinal`.
  29389. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29390. resultItem.type = 'ordinal';
  29391. }
  29392. }
  29393. } else {
  29394. each(resultList, function (resultItem) {
  29395. // PENDING: guessOrdinal or let user specify type: 'ordinal' manually?
  29396. ifNoNameFillWithCoordName(resultItem);
  29397. }); // Sort dimensions: there are some rule that use the last dim as label,
  29398. // and for some latter travel process easier.
  29399. resultList.sort(function (item0, item1) {
  29400. return item0.storeDimIndex - item1.storeDimIndex;
  29401. });
  29402. }
  29403. removeDuplication(resultList);
  29404. return new SeriesDataSchema({
  29405. source: source,
  29406. dimensions: resultList,
  29407. fullDimensionCount: dimCount,
  29408. dimensionOmitted: omitUnusedDimensions
  29409. });
  29410. }
  29411. function removeDuplication(result) {
  29412. var duplicationMap = createHashMap();
  29413. for (var i = 0; i < result.length; i++) {
  29414. var dim = result[i];
  29415. var dimOriginalName = dim.name;
  29416. var count = duplicationMap.get(dimOriginalName) || 0;
  29417. if (count > 0) {
  29418. // Starts from 0.
  29419. dim.name = dimOriginalName + (count - 1);
  29420. }
  29421. count++;
  29422. duplicationMap.set(dimOriginalName, count);
  29423. }
  29424. } // ??? TODO
  29425. // Originally detect dimCount by data[0]. Should we
  29426. // optimize it to only by sysDims and dimensions and encode.
  29427. // So only necessary dims will be initialized.
  29428. // But
  29429. // (1) custom series should be considered. where other dims
  29430. // may be visited.
  29431. // (2) sometimes user need to calculate bubble size or use visualMap
  29432. // on other dimensions besides coordSys needed.
  29433. // So, dims that is not used by system, should be shared in data store?
  29434. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29435. // Note that the result dimCount should not small than columns count
  29436. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29437. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29438. each(sysDims, function (sysDimItem) {
  29439. var sysDimItemDimsDef;
  29440. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29441. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29442. }
  29443. });
  29444. return dimCount;
  29445. }
  29446. function genCoordDimName(name, map, fromZero) {
  29447. if (fromZero || map.hasKey(name)) {
  29448. var i = 0;
  29449. while (map.hasKey(name + i)) {
  29450. i++;
  29451. }
  29452. name += i;
  29453. }
  29454. map.set(name, true);
  29455. return name;
  29456. }
  29457. /**
  29458. * @class
  29459. * For example:
  29460. * {
  29461. * coordSysName: 'cartesian2d',
  29462. * coordSysDims: ['x', 'y', ...],
  29463. * axisMap: HashMap({
  29464. * x: xAxisModel,
  29465. * y: yAxisModel
  29466. * }),
  29467. * categoryAxisMap: HashMap({
  29468. * x: xAxisModel,
  29469. * y: undefined
  29470. * }),
  29471. * // The index of the first category axis in `coordSysDims`.
  29472. * // `null/undefined` means no category axis exists.
  29473. * firstCategoryDimIndex: 1,
  29474. * // To replace user specified encode.
  29475. * }
  29476. */
  29477. var CoordSysInfo =
  29478. /** @class */
  29479. function () {
  29480. function CoordSysInfo(coordSysName) {
  29481. this.coordSysDims = [];
  29482. this.axisMap = createHashMap();
  29483. this.categoryAxisMap = createHashMap();
  29484. this.coordSysName = coordSysName;
  29485. }
  29486. return CoordSysInfo;
  29487. }();
  29488. function getCoordSysInfoBySeries(seriesModel) {
  29489. var coordSysName = seriesModel.get('coordinateSystem');
  29490. var result = new CoordSysInfo(coordSysName);
  29491. var fetch = fetchers[coordSysName];
  29492. if (fetch) {
  29493. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29494. return result;
  29495. }
  29496. }
  29497. var fetchers = {
  29498. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29499. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29500. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29501. if ("development" !== 'production') {
  29502. if (!xAxisModel) {
  29503. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29504. }
  29505. if (!yAxisModel) {
  29506. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29507. }
  29508. }
  29509. result.coordSysDims = ['x', 'y'];
  29510. axisMap.set('x', xAxisModel);
  29511. axisMap.set('y', yAxisModel);
  29512. if (isCategory(xAxisModel)) {
  29513. categoryAxisMap.set('x', xAxisModel);
  29514. result.firstCategoryDimIndex = 0;
  29515. }
  29516. if (isCategory(yAxisModel)) {
  29517. categoryAxisMap.set('y', yAxisModel);
  29518. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29519. }
  29520. },
  29521. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29522. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29523. if ("development" !== 'production') {
  29524. if (!singleAxisModel) {
  29525. throw new Error('singleAxis should be specified.');
  29526. }
  29527. }
  29528. result.coordSysDims = ['single'];
  29529. axisMap.set('single', singleAxisModel);
  29530. if (isCategory(singleAxisModel)) {
  29531. categoryAxisMap.set('single', singleAxisModel);
  29532. result.firstCategoryDimIndex = 0;
  29533. }
  29534. },
  29535. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29536. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29537. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29538. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29539. if ("development" !== 'production') {
  29540. if (!angleAxisModel) {
  29541. throw new Error('angleAxis option not found');
  29542. }
  29543. if (!radiusAxisModel) {
  29544. throw new Error('radiusAxis option not found');
  29545. }
  29546. }
  29547. result.coordSysDims = ['radius', 'angle'];
  29548. axisMap.set('radius', radiusAxisModel);
  29549. axisMap.set('angle', angleAxisModel);
  29550. if (isCategory(radiusAxisModel)) {
  29551. categoryAxisMap.set('radius', radiusAxisModel);
  29552. result.firstCategoryDimIndex = 0;
  29553. }
  29554. if (isCategory(angleAxisModel)) {
  29555. categoryAxisMap.set('angle', angleAxisModel);
  29556. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29557. }
  29558. },
  29559. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29560. result.coordSysDims = ['lng', 'lat'];
  29561. },
  29562. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29563. var ecModel = seriesModel.ecModel;
  29564. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29565. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29566. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29567. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29568. var axisDim = coordSysDims[index];
  29569. axisMap.set(axisDim, axisModel);
  29570. if (isCategory(axisModel)) {
  29571. categoryAxisMap.set(axisDim, axisModel);
  29572. if (result.firstCategoryDimIndex == null) {
  29573. result.firstCategoryDimIndex = index;
  29574. }
  29575. }
  29576. });
  29577. }
  29578. };
  29579. function isCategory(axisModel) {
  29580. return axisModel.get('type') === 'category';
  29581. }
  29582. /**
  29583. * Note that it is too complicated to support 3d stack by value
  29584. * (have to create two-dimension inverted index), so in 3d case
  29585. * we just support that stacked by index.
  29586. *
  29587. * @param seriesModel
  29588. * @param dimensionsInput The same as the input of <module:echarts/data/SeriesData>.
  29589. * The input will be modified.
  29590. * @param opt
  29591. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29592. * @param opt.byIndex=false
  29593. * @return calculationInfo
  29594. * {
  29595. * stackedDimension: string
  29596. * stackedByDimension: string
  29597. * isStackedByIndex: boolean
  29598. * stackedOverDimension: string
  29599. * stackResultDimension: string
  29600. * }
  29601. */
  29602. function enableDataStack(seriesModel, dimensionsInput, opt) {
  29603. opt = opt || {};
  29604. var byIndex = opt.byIndex;
  29605. var stackedCoordDimension = opt.stackedCoordDimension;
  29606. var dimensionDefineList;
  29607. var schema;
  29608. var store;
  29609. if (isLegacyDimensionsInput(dimensionsInput)) {
  29610. dimensionDefineList = dimensionsInput;
  29611. } else {
  29612. schema = dimensionsInput.schema;
  29613. dimensionDefineList = schema.dimensions;
  29614. store = dimensionsInput.store;
  29615. } // Compatibal: when `stack` is set as '', do not stack.
  29616. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29617. var stackedByDimInfo;
  29618. var stackedDimInfo;
  29619. var stackResultDimension;
  29620. var stackedOverDimension;
  29621. each(dimensionDefineList, function (dimensionInfo, index) {
  29622. if (isString(dimensionInfo)) {
  29623. dimensionDefineList[index] = dimensionInfo = {
  29624. name: dimensionInfo
  29625. };
  29626. }
  29627. if (mayStack && !dimensionInfo.isExtraCoord) {
  29628. // Find the first ordinal dimension as the stackedByDimInfo.
  29629. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29630. stackedByDimInfo = dimensionInfo;
  29631. } // Find the first stackable dimension as the stackedDimInfo.
  29632. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29633. stackedDimInfo = dimensionInfo;
  29634. }
  29635. }
  29636. });
  29637. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29638. // Compatible with previous design, value axis (time axis) only stack by index.
  29639. // It may make sense if the user provides elaborately constructed data.
  29640. byIndex = true;
  29641. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29642. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29643. // might not be a good way.
  29644. if (stackedDimInfo) {
  29645. // Use a weird name that not duplicated with other names.
  29646. // Also need to use seriesModel.id as postfix because different
  29647. // series may share same data store. The stack dimension needs to be distinguished.
  29648. stackResultDimension = '__\0ecstackresult_' + seriesModel.id;
  29649. stackedOverDimension = '__\0ecstackedover_' + seriesModel.id; // Create inverted index to fast query index by value.
  29650. if (stackedByDimInfo) {
  29651. stackedByDimInfo.createInvertedIndices = true;
  29652. }
  29653. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29654. var stackedDimType = stackedDimInfo.type;
  29655. var stackedDimCoordIndex_1 = 0;
  29656. each(dimensionDefineList, function (dimensionInfo) {
  29657. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29658. stackedDimCoordIndex_1++;
  29659. }
  29660. });
  29661. var stackedOverDimensionDefine = {
  29662. name: stackResultDimension,
  29663. coordDim: stackedDimCoordDim_1,
  29664. coordDimIndex: stackedDimCoordIndex_1,
  29665. type: stackedDimType,
  29666. isExtraCoord: true,
  29667. isCalculationCoord: true,
  29668. storeDimIndex: dimensionDefineList.length
  29669. };
  29670. var stackResultDimensionDefine = {
  29671. name: stackedOverDimension,
  29672. // This dimension contains stack base (generally, 0), so do not set it as
  29673. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29674. coordDim: stackedOverDimension,
  29675. coordDimIndex: stackedDimCoordIndex_1 + 1,
  29676. type: stackedDimType,
  29677. isExtraCoord: true,
  29678. isCalculationCoord: true,
  29679. storeDimIndex: dimensionDefineList.length + 1
  29680. };
  29681. if (schema) {
  29682. if (store) {
  29683. stackedOverDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackedOverDimension, stackedDimType);
  29684. stackResultDimensionDefine.storeDimIndex = store.ensureCalculationDimension(stackResultDimension, stackedDimType);
  29685. }
  29686. schema.appendCalculationDimension(stackedOverDimensionDefine);
  29687. schema.appendCalculationDimension(stackResultDimensionDefine);
  29688. } else {
  29689. dimensionDefineList.push(stackedOverDimensionDefine);
  29690. dimensionDefineList.push(stackResultDimensionDefine);
  29691. }
  29692. }
  29693. return {
  29694. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29695. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29696. isStackedByIndex: byIndex,
  29697. stackedOverDimension: stackedOverDimension,
  29698. stackResultDimension: stackResultDimension
  29699. };
  29700. }
  29701. function isLegacyDimensionsInput(dimensionsInput) {
  29702. return !isSeriesDataSchema(dimensionsInput.schema);
  29703. }
  29704. function isDimensionStacked(data, stackedDim) {
  29705. // Each single series only maps to one pair of axis. So we do not need to
  29706. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29707. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  29708. }
  29709. function getStackedDimension(data, targetDim) {
  29710. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29711. }
  29712. function getCoordSysDimDefs(seriesModel, coordSysInfo) {
  29713. var coordSysName = seriesModel.get('coordinateSystem');
  29714. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29715. var coordSysDimDefs;
  29716. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29717. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29718. var dimInfo = {
  29719. name: dim
  29720. };
  29721. var axisModel = coordSysInfo.axisMap.get(dim);
  29722. if (axisModel) {
  29723. var axisType = axisModel.get('type');
  29724. dimInfo.type = getDimensionTypeByAxis(axisType);
  29725. }
  29726. return dimInfo;
  29727. });
  29728. }
  29729. if (!coordSysDimDefs) {
  29730. // Get dimensions from registered coordinate system
  29731. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29732. }
  29733. return coordSysDimDefs;
  29734. }
  29735. function injectOrdinalMeta(dimInfoList, createInvertedIndices, coordSysInfo) {
  29736. var firstCategoryDimIndex;
  29737. var hasNameEncode;
  29738. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29739. var coordDim = dimInfo.coordDim;
  29740. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29741. if (categoryAxisModel) {
  29742. if (firstCategoryDimIndex == null) {
  29743. firstCategoryDimIndex = dimIndex;
  29744. }
  29745. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29746. if (createInvertedIndices) {
  29747. dimInfo.createInvertedIndices = true;
  29748. }
  29749. }
  29750. if (dimInfo.otherDims.itemName != null) {
  29751. hasNameEncode = true;
  29752. }
  29753. });
  29754. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29755. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29756. }
  29757. return firstCategoryDimIndex;
  29758. }
  29759. /**
  29760. * Caution: there are side effects to `sourceManager` in this method.
  29761. * Should better only be called in `Series['getInitialData']`.
  29762. */
  29763. function createSeriesData(sourceRaw, seriesModel, opt) {
  29764. opt = opt || {};
  29765. var sourceManager = seriesModel.getSourceManager();
  29766. var source;
  29767. var isOriginalSource = false;
  29768. if (sourceRaw) {
  29769. isOriginalSource = true;
  29770. source = createSourceFromSeriesDataOption(sourceRaw);
  29771. } else {
  29772. source = sourceManager.getSource(); // Is series.data. not dataset.
  29773. isOriginalSource = source.sourceFormat === SOURCE_FORMAT_ORIGINAL;
  29774. }
  29775. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29776. var coordSysDimDefs = getCoordSysDimDefs(seriesModel, coordSysInfo);
  29777. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29778. var encodeDefaulter = isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null;
  29779. var createDimensionOptions = {
  29780. coordDimensions: coordSysDimDefs,
  29781. generateCoord: opt.generateCoord,
  29782. encodeDefine: seriesModel.getEncode(),
  29783. encodeDefaulter: encodeDefaulter,
  29784. canOmitUnusedDimensions: !isOriginalSource
  29785. };
  29786. var schema = prepareSeriesDataSchema(source, createDimensionOptions);
  29787. var firstCategoryDimIndex = injectOrdinalMeta(schema.dimensions, opt.createInvertedIndices, coordSysInfo);
  29788. var store = !isOriginalSource ? sourceManager.getSharedDataStore(schema) : null;
  29789. var stackCalculationInfo = enableDataStack(seriesModel, {
  29790. schema: schema,
  29791. store: store
  29792. });
  29793. var data = new SeriesData(schema, seriesModel);
  29794. data.setCalculationInfo(stackCalculationInfo);
  29795. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29796. // Use dataIndex as ordinal value in categoryAxis
  29797. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29798. } : null;
  29799. data.hasItemOption = false;
  29800. data.initData( // Try to reuse the data store in sourceManager if using dataset.
  29801. isOriginalSource ? source : store, null, dimValueGetter);
  29802. return data;
  29803. }
  29804. function isNeedCompleteOrdinalData(source) {
  29805. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29806. var sampleItem = firstDataNotNull(source.data || []);
  29807. return !isArray(getDataItemValue(sampleItem));
  29808. }
  29809. }
  29810. function firstDataNotNull(arr) {
  29811. var i = 0;
  29812. while (i < arr.length && arr[i] == null) {
  29813. i++;
  29814. }
  29815. return arr[i];
  29816. }
  29817. var Scale =
  29818. /** @class */
  29819. function () {
  29820. function Scale(setting) {
  29821. this._setting = setting || {};
  29822. this._extent = [Infinity, -Infinity];
  29823. }
  29824. Scale.prototype.getSetting = function (name) {
  29825. return this._setting[name];
  29826. };
  29827. /**
  29828. * Set extent from data
  29829. */
  29830. Scale.prototype.unionExtent = function (other) {
  29831. var extent = this._extent;
  29832. other[0] < extent[0] && (extent[0] = other[0]);
  29833. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29834. // this.setExtent(extent[0], extent[1]);
  29835. };
  29836. /**
  29837. * Set extent from data
  29838. */
  29839. Scale.prototype.unionExtentFromData = function (data, dim) {
  29840. this.unionExtent(data.getApproximateExtent(dim));
  29841. };
  29842. /**
  29843. * Get extent
  29844. *
  29845. * Extent is always in increase order.
  29846. */
  29847. Scale.prototype.getExtent = function () {
  29848. return this._extent.slice();
  29849. };
  29850. /**
  29851. * Set extent
  29852. */
  29853. Scale.prototype.setExtent = function (start, end) {
  29854. var thisExtent = this._extent;
  29855. if (!isNaN(start)) {
  29856. thisExtent[0] = start;
  29857. }
  29858. if (!isNaN(end)) {
  29859. thisExtent[1] = end;
  29860. }
  29861. };
  29862. /**
  29863. * If value is in extent range
  29864. */
  29865. Scale.prototype.isInExtentRange = function (value) {
  29866. return this._extent[0] <= value && this._extent[1] >= value;
  29867. };
  29868. /**
  29869. * When axis extent depends on data and no data exists,
  29870. * axis ticks should not be drawn, which is named 'blank'.
  29871. */
  29872. Scale.prototype.isBlank = function () {
  29873. return this._isBlank;
  29874. };
  29875. /**
  29876. * When axis extent depends on data and no data exists,
  29877. * axis ticks should not be drawn, which is named 'blank'.
  29878. */
  29879. Scale.prototype.setBlank = function (isBlank) {
  29880. this._isBlank = isBlank;
  29881. };
  29882. return Scale;
  29883. }();
  29884. enableClassManagement(Scale);
  29885. var uidBase = 0;
  29886. var OrdinalMeta =
  29887. /** @class */
  29888. function () {
  29889. function OrdinalMeta(opt) {
  29890. this.categories = opt.categories || [];
  29891. this._needCollect = opt.needCollect;
  29892. this._deduplication = opt.deduplication;
  29893. this.uid = ++uidBase;
  29894. }
  29895. OrdinalMeta.createByAxisModel = function (axisModel) {
  29896. var option = axisModel.option;
  29897. var data = option.data;
  29898. var categories = data && map(data, getName);
  29899. return new OrdinalMeta({
  29900. categories: categories,
  29901. needCollect: !categories,
  29902. // deduplication is default in axis.
  29903. deduplication: option.dedplication !== false
  29904. });
  29905. };
  29906. OrdinalMeta.prototype.getOrdinal = function (category) {
  29907. // @ts-ignore
  29908. return this._getOrCreateMap().get(category);
  29909. };
  29910. /**
  29911. * @return The ordinal. If not found, return NaN.
  29912. */
  29913. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29914. var index;
  29915. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29916. // This feature is only supported when !needCollect, because we should
  29917. // consider a common case: a value is 2017, which is a number but is
  29918. // expected to be tread as a category. This case usually happen in dataset,
  29919. // where it happent to be no need of the index feature.
  29920. if (!isString(category) && !needCollect) {
  29921. return category;
  29922. } // Optimize for the scenario:
  29923. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29924. // data has been ensured not duplicate and is large data.
  29925. // Notice, if a dataset dimension provide categroies, usually echarts
  29926. // should remove duplication except user tell echarts dont do that
  29927. // (set axis.deduplication = false), because echarts do not know whether
  29928. // the values in the category dimension has duplication (consider the
  29929. // parallel-aqi example)
  29930. if (needCollect && !this._deduplication) {
  29931. index = this.categories.length;
  29932. this.categories[index] = category;
  29933. return index;
  29934. }
  29935. var map = this._getOrCreateMap(); // @ts-ignore
  29936. index = map.get(category);
  29937. if (index == null) {
  29938. if (needCollect) {
  29939. index = this.categories.length;
  29940. this.categories[index] = category; // @ts-ignore
  29941. map.set(category, index);
  29942. } else {
  29943. index = NaN;
  29944. }
  29945. }
  29946. return index;
  29947. }; // Consider big data, do not create map until needed.
  29948. OrdinalMeta.prototype._getOrCreateMap = function () {
  29949. return this._map || (this._map = createHashMap(this.categories));
  29950. };
  29951. return OrdinalMeta;
  29952. }();
  29953. function getName(obj) {
  29954. if (isObject(obj) && obj.value != null) {
  29955. return obj.value;
  29956. } else {
  29957. return obj + '';
  29958. }
  29959. }
  29960. function isValueNice(val) {
  29961. var exp10 = Math.pow(10, quantityExponent(Math.abs(val)));
  29962. var f = Math.abs(val / exp10);
  29963. return f === 0 || f === 1 || f === 2 || f === 3 || f === 5;
  29964. }
  29965. function isIntervalOrLogScale(scale) {
  29966. return scale.type === 'interval' || scale.type === 'log';
  29967. }
  29968. /**
  29969. * @param extent Both extent[0] and extent[1] should be valid number.
  29970. * Should be extent[0] < extent[1].
  29971. * @param splitNumber splitNumber should be >= 1.
  29972. */
  29973. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29974. var result = {};
  29975. var span = extent[1] - extent[0];
  29976. var interval = result.interval = nice(span / splitNumber, true);
  29977. if (minInterval != null && interval < minInterval) {
  29978. interval = result.interval = minInterval;
  29979. }
  29980. if (maxInterval != null && interval > maxInterval) {
  29981. interval = result.interval = maxInterval;
  29982. } // Tow more digital for tick.
  29983. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29984. var niceTickExtent = result.niceTickExtent = [round(Math.ceil(extent[0] / interval) * interval, precision), round(Math.floor(extent[1] / interval) * interval, precision)];
  29985. fixExtent(niceTickExtent, extent);
  29986. return result;
  29987. }
  29988. function increaseInterval(interval) {
  29989. var exp10 = Math.pow(10, quantityExponent(interval)); // Increase interval
  29990. var f = interval / exp10;
  29991. if (!f) {
  29992. f = 1;
  29993. } else if (f === 2) {
  29994. f = 3;
  29995. } else if (f === 3) {
  29996. f = 5;
  29997. } else {
  29998. // f is 1 or 5
  29999. f *= 2;
  30000. }
  30001. return round(f * exp10);
  30002. }
  30003. /**
  30004. * @return interval precision
  30005. */
  30006. function getIntervalPrecision(interval) {
  30007. // Tow more digital for tick.
  30008. return getPrecision(interval) + 2;
  30009. }
  30010. function clamp(niceTickExtent, idx, extent) {
  30011. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  30012. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  30013. function fixExtent(niceTickExtent, extent) {
  30014. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  30015. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  30016. clamp(niceTickExtent, 0, extent);
  30017. clamp(niceTickExtent, 1, extent);
  30018. if (niceTickExtent[0] > niceTickExtent[1]) {
  30019. niceTickExtent[0] = niceTickExtent[1];
  30020. }
  30021. }
  30022. function contain$1(val, extent) {
  30023. return val >= extent[0] && val <= extent[1];
  30024. }
  30025. function normalize$1(val, extent) {
  30026. if (extent[1] === extent[0]) {
  30027. return 0.5;
  30028. }
  30029. return (val - extent[0]) / (extent[1] - extent[0]);
  30030. }
  30031. function scale$2(val, extent) {
  30032. return val * (extent[1] - extent[0]) + extent[0];
  30033. }
  30034. var OrdinalScale =
  30035. /** @class */
  30036. function (_super) {
  30037. __extends(OrdinalScale, _super);
  30038. function OrdinalScale(setting) {
  30039. var _this = _super.call(this, setting) || this;
  30040. _this.type = 'ordinal';
  30041. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  30042. // import approach to get OrdinalMeta class.
  30043. if (!ordinalMeta) {
  30044. ordinalMeta = new OrdinalMeta({});
  30045. }
  30046. if (isArray(ordinalMeta)) {
  30047. ordinalMeta = new OrdinalMeta({
  30048. categories: map(ordinalMeta, function (item) {
  30049. return isObject(item) ? item.value : item;
  30050. })
  30051. });
  30052. }
  30053. _this._ordinalMeta = ordinalMeta;
  30054. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  30055. return _this;
  30056. }
  30057. OrdinalScale.prototype.parse = function (val) {
  30058. // Caution: Math.round(null) will return `0` rather than `NaN`
  30059. if (val == null) {
  30060. return NaN;
  30061. }
  30062. return isString(val) ? this._ordinalMeta.getOrdinal(val) // val might be float.
  30063. : Math.round(val);
  30064. };
  30065. OrdinalScale.prototype.contain = function (rank) {
  30066. rank = this.parse(rank);
  30067. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  30068. };
  30069. /**
  30070. * Normalize given rank or name to linear [0, 1]
  30071. * @param val raw ordinal number.
  30072. * @return normalized value in [0, 1].
  30073. */
  30074. OrdinalScale.prototype.normalize = function (val) {
  30075. val = this._getTickNumber(this.parse(val));
  30076. return normalize$1(val, this._extent);
  30077. };
  30078. /**
  30079. * @param val normalized value in [0, 1].
  30080. * @return raw ordinal number.
  30081. */
  30082. OrdinalScale.prototype.scale = function (val) {
  30083. val = Math.round(scale$2(val, this._extent));
  30084. return this.getRawOrdinalNumber(val);
  30085. };
  30086. OrdinalScale.prototype.getTicks = function () {
  30087. var ticks = [];
  30088. var extent = this._extent;
  30089. var rank = extent[0];
  30090. while (rank <= extent[1]) {
  30091. ticks.push({
  30092. value: rank
  30093. });
  30094. rank++;
  30095. }
  30096. return ticks;
  30097. };
  30098. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  30099. // Not support.
  30100. return;
  30101. };
  30102. /**
  30103. * @see `Ordinal['_ordinalNumbersByTick']`
  30104. */
  30105. OrdinalScale.prototype.setSortInfo = function (info) {
  30106. if (info == null) {
  30107. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  30108. return;
  30109. }
  30110. var infoOrdinalNumbers = info.ordinalNumbers;
  30111. var ordinalsByTick = this._ordinalNumbersByTick = [];
  30112. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  30113. var tickNum = 0;
  30114. var allCategoryLen = this._ordinalMeta.categories.length;
  30115. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  30116. var ordinalNumber = infoOrdinalNumbers[tickNum];
  30117. ordinalsByTick[tickNum] = ordinalNumber;
  30118. ticksByOrdinal[ordinalNumber] = tickNum;
  30119. } // Handle that `series.data` only covers part of the `axis.category.data`.
  30120. var unusedOrdinal = 0;
  30121. for (; tickNum < allCategoryLen; ++tickNum) {
  30122. while (ticksByOrdinal[unusedOrdinal] != null) {
  30123. unusedOrdinal++;
  30124. }
  30125. ordinalsByTick.push(unusedOrdinal);
  30126. ticksByOrdinal[unusedOrdinal] = tickNum;
  30127. }
  30128. };
  30129. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  30130. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  30131. // where ordinal numbers are used as tick value directly.
  30132. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  30133. };
  30134. /**
  30135. * @usage
  30136. * ```js
  30137. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  30138. *
  30139. * // case0
  30140. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  30141. * // case1
  30142. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  30143. * // case2
  30144. * const coord = axis.dataToCoord(ordinalNumber);
  30145. * ```
  30146. *
  30147. * @param {OrdinalNumber} tickNumber index of display
  30148. */
  30149. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  30150. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  30151. // where ordinal numbers are used as tick value directly.
  30152. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  30153. };
  30154. /**
  30155. * Get item on tick
  30156. */
  30157. OrdinalScale.prototype.getLabel = function (tick) {
  30158. if (!this.isBlank()) {
  30159. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  30160. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  30161. // Return empty if it's not exist.
  30162. return cateogry == null ? '' : cateogry + '';
  30163. }
  30164. };
  30165. OrdinalScale.prototype.count = function () {
  30166. return this._extent[1] - this._extent[0] + 1;
  30167. };
  30168. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  30169. this.unionExtent(data.getApproximateExtent(dim));
  30170. };
  30171. /**
  30172. * @override
  30173. * If value is in extent range
  30174. */
  30175. OrdinalScale.prototype.isInExtentRange = function (value) {
  30176. value = this._getTickNumber(value);
  30177. return this._extent[0] <= value && this._extent[1] >= value;
  30178. };
  30179. OrdinalScale.prototype.getOrdinalMeta = function () {
  30180. return this._ordinalMeta;
  30181. };
  30182. OrdinalScale.prototype.calcNiceTicks = function () {};
  30183. OrdinalScale.prototype.calcNiceExtent = function () {};
  30184. OrdinalScale.type = 'ordinal';
  30185. return OrdinalScale;
  30186. }(Scale);
  30187. Scale.registerClass(OrdinalScale);
  30188. var roundNumber = round;
  30189. var IntervalScale =
  30190. /** @class */
  30191. function (_super) {
  30192. __extends(IntervalScale, _super);
  30193. function IntervalScale() {
  30194. var _this = _super !== null && _super.apply(this, arguments) || this;
  30195. _this.type = 'interval'; // Step is calculated in adjustExtent.
  30196. _this._interval = 0;
  30197. _this._intervalPrecision = 2;
  30198. return _this;
  30199. }
  30200. IntervalScale.prototype.parse = function (val) {
  30201. return val;
  30202. };
  30203. IntervalScale.prototype.contain = function (val) {
  30204. return contain$1(val, this._extent);
  30205. };
  30206. IntervalScale.prototype.normalize = function (val) {
  30207. return normalize$1(val, this._extent);
  30208. };
  30209. IntervalScale.prototype.scale = function (val) {
  30210. return scale$2(val, this._extent);
  30211. };
  30212. IntervalScale.prototype.setExtent = function (start, end) {
  30213. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  30214. if (!isNaN(start)) {
  30215. thisExtent[0] = parseFloat(start);
  30216. }
  30217. if (!isNaN(end)) {
  30218. thisExtent[1] = parseFloat(end);
  30219. }
  30220. };
  30221. IntervalScale.prototype.unionExtent = function (other) {
  30222. var extent = this._extent;
  30223. other[0] < extent[0] && (extent[0] = other[0]);
  30224. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  30225. this.setExtent(extent[0], extent[1]);
  30226. };
  30227. IntervalScale.prototype.getInterval = function () {
  30228. return this._interval;
  30229. };
  30230. IntervalScale.prototype.setInterval = function (interval) {
  30231. this._interval = interval; // Dropped auto calculated niceExtent and use user-set extent.
  30232. // We assume user wants to set both interval, min, max to get a better result.
  30233. this._niceExtent = this._extent.slice();
  30234. this._intervalPrecision = getIntervalPrecision(interval);
  30235. };
  30236. /**
  30237. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30238. */
  30239. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  30240. var interval = this._interval;
  30241. var extent = this._extent;
  30242. var niceTickExtent = this._niceExtent;
  30243. var intervalPrecision = this._intervalPrecision;
  30244. var ticks = []; // If interval is 0, return [];
  30245. if (!interval) {
  30246. return ticks;
  30247. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  30248. var safeLimit = 10000;
  30249. if (extent[0] < niceTickExtent[0]) {
  30250. if (expandToNicedExtent) {
  30251. ticks.push({
  30252. value: roundNumber(niceTickExtent[0] - interval, intervalPrecision)
  30253. });
  30254. } else {
  30255. ticks.push({
  30256. value: extent[0]
  30257. });
  30258. }
  30259. }
  30260. var tick = niceTickExtent[0];
  30261. while (tick <= niceTickExtent[1]) {
  30262. ticks.push({
  30263. value: tick
  30264. }); // Avoid rounding error
  30265. tick = roundNumber(tick + interval, intervalPrecision);
  30266. if (tick === ticks[ticks.length - 1].value) {
  30267. // Consider out of safe float point, e.g.,
  30268. // -3711126.9907707 + 2e-10 === -3711126.9907707
  30269. break;
  30270. }
  30271. if (ticks.length > safeLimit) {
  30272. return [];
  30273. }
  30274. } // Consider this case: the last item of ticks is smaller
  30275. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  30276. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  30277. if (extent[1] > lastNiceTick) {
  30278. if (expandToNicedExtent) {
  30279. ticks.push({
  30280. value: roundNumber(lastNiceTick + interval, intervalPrecision)
  30281. });
  30282. } else {
  30283. ticks.push({
  30284. value: extent[1]
  30285. });
  30286. }
  30287. }
  30288. return ticks;
  30289. };
  30290. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  30291. var ticks = this.getTicks(true);
  30292. var minorTicks = [];
  30293. var extent = this.getExtent();
  30294. for (var i = 1; i < ticks.length; i++) {
  30295. var nextTick = ticks[i];
  30296. var prevTick = ticks[i - 1];
  30297. var count = 0;
  30298. var minorTicksGroup = [];
  30299. var interval = nextTick.value - prevTick.value;
  30300. var minorInterval = interval / splitNumber;
  30301. while (count < splitNumber - 1) {
  30302. var minorTick = roundNumber(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  30303. if (minorTick > extent[0] && minorTick < extent[1]) {
  30304. minorTicksGroup.push(minorTick);
  30305. }
  30306. count++;
  30307. }
  30308. minorTicks.push(minorTicksGroup);
  30309. }
  30310. return minorTicks;
  30311. };
  30312. /**
  30313. * @param opt.precision If 'auto', use nice presision.
  30314. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  30315. */
  30316. IntervalScale.prototype.getLabel = function (data, opt) {
  30317. if (data == null) {
  30318. return '';
  30319. }
  30320. var precision = opt && opt.precision;
  30321. if (precision == null) {
  30322. precision = getPrecision(data.value) || 0;
  30323. } else if (precision === 'auto') {
  30324. // Should be more precise then tick.
  30325. precision = this._intervalPrecision;
  30326. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  30327. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  30328. var dataNum = roundNumber(data.value, precision, true);
  30329. return addCommas(dataNum);
  30330. };
  30331. /**
  30332. * @param splitNumber By default `5`.
  30333. */
  30334. IntervalScale.prototype.calcNiceTicks = function (splitNumber, minInterval, maxInterval) {
  30335. splitNumber = splitNumber || 5;
  30336. var extent = this._extent;
  30337. var span = extent[1] - extent[0];
  30338. if (!isFinite(span)) {
  30339. return;
  30340. } // User may set axis min 0 and data are all negative
  30341. // FIXME If it needs to reverse ?
  30342. if (span < 0) {
  30343. span = -span;
  30344. extent.reverse();
  30345. }
  30346. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  30347. this._intervalPrecision = result.intervalPrecision;
  30348. this._interval = result.interval;
  30349. this._niceExtent = result.niceTickExtent;
  30350. };
  30351. IntervalScale.prototype.calcNiceExtent = function (opt) {
  30352. var extent = this._extent; // If extent start and end are same, expand them
  30353. if (extent[0] === extent[1]) {
  30354. if (extent[0] !== 0) {
  30355. // Expand extent
  30356. // Note that extents can be both negative. See #13154
  30357. var expandSize = Math.abs(extent[0]); // In the fowllowing case
  30358. // Axis has been fixed max 100
  30359. // Plus data are all 100 and axis extent are [100, 100].
  30360. // Extend to the both side will cause expanded max is larger than fixed max.
  30361. // So only expand to the smaller side.
  30362. if (!opt.fixMax) {
  30363. extent[1] += expandSize / 2;
  30364. extent[0] -= expandSize / 2;
  30365. } else {
  30366. extent[0] -= expandSize / 2;
  30367. }
  30368. } else {
  30369. extent[1] = 1;
  30370. }
  30371. }
  30372. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  30373. if (!isFinite(span)) {
  30374. extent[0] = 0;
  30375. extent[1] = 1;
  30376. }
  30377. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  30378. var interval = this._interval;
  30379. if (!opt.fixMin) {
  30380. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  30381. }
  30382. if (!opt.fixMax) {
  30383. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  30384. }
  30385. };
  30386. IntervalScale.prototype.setNiceExtent = function (min, max) {
  30387. this._niceExtent = [min, max];
  30388. };
  30389. IntervalScale.type = 'interval';
  30390. return IntervalScale;
  30391. }(Scale);
  30392. Scale.registerClass(IntervalScale);
  30393. /* global Float32Array */
  30394. var supportFloat32Array = typeof Float32Array !== 'undefined';
  30395. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  30396. function createFloat32Array(arg) {
  30397. if (isArray(arg)) {
  30398. // Return self directly if don't support TypedArray.
  30399. return supportFloat32Array ? new Float32Array(arg) : arg;
  30400. } // Else is number
  30401. return new Float32ArrayCtor(arg);
  30402. }
  30403. var STACK_PREFIX = '__ec_stack_';
  30404. function getSeriesStackId(seriesModel) {
  30405. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  30406. }
  30407. function getAxisKey(axis) {
  30408. return axis.dim + axis.index;
  30409. }
  30410. /**
  30411. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  30412. */
  30413. function getLayoutOnAxis(opt) {
  30414. var params = [];
  30415. var baseAxis = opt.axis;
  30416. var axisKey = 'axis0';
  30417. if (baseAxis.type !== 'category') {
  30418. return;
  30419. }
  30420. var bandWidth = baseAxis.getBandWidth();
  30421. for (var i = 0; i < opt.count || 0; i++) {
  30422. params.push(defaults({
  30423. bandWidth: bandWidth,
  30424. axisKey: axisKey,
  30425. stackId: STACK_PREFIX + i
  30426. }, opt));
  30427. }
  30428. var widthAndOffsets = doCalBarWidthAndOffset(params);
  30429. var result = [];
  30430. for (var i = 0; i < opt.count; i++) {
  30431. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  30432. item.offsetCenter = item.offset + item.width / 2;
  30433. result.push(item);
  30434. }
  30435. return result;
  30436. }
  30437. function prepareLayoutBarSeries(seriesType, ecModel) {
  30438. var seriesModels = [];
  30439. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  30440. // Check series coordinate, do layout for cartesian2d only
  30441. if (isOnCartesian(seriesModel)) {
  30442. seriesModels.push(seriesModel);
  30443. }
  30444. });
  30445. return seriesModels;
  30446. }
  30447. /**
  30448. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  30449. * values.
  30450. * This works for time axes, value axes, and log axes.
  30451. * For a single time axis, return value is in the form like
  30452. * {'x_0': [1000000]}.
  30453. * The value of 1000000 is in milliseconds.
  30454. */
  30455. function getValueAxesMinGaps(barSeries) {
  30456. /**
  30457. * Map from axis.index to values.
  30458. * For a single time axis, axisValues is in the form like
  30459. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30460. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30461. * series.
  30462. */
  30463. var axisValues = {};
  30464. each(barSeries, function (seriesModel) {
  30465. var cartesian = seriesModel.coordinateSystem;
  30466. var baseAxis = cartesian.getBaseAxis();
  30467. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30468. return;
  30469. }
  30470. var data = seriesModel.getData();
  30471. var key = baseAxis.dim + '_' + baseAxis.index;
  30472. var dimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30473. var store = data.getStore();
  30474. for (var i = 0, cnt = store.count(); i < cnt; ++i) {
  30475. var value = store.get(dimIdx, i);
  30476. if (!axisValues[key]) {
  30477. // No previous data for the axis
  30478. axisValues[key] = [value];
  30479. } else {
  30480. // No value in previous series
  30481. axisValues[key].push(value);
  30482. } // Ignore duplicated time values in the same axis
  30483. }
  30484. });
  30485. var axisMinGaps = {};
  30486. for (var key in axisValues) {
  30487. if (axisValues.hasOwnProperty(key)) {
  30488. var valuesInAxis = axisValues[key];
  30489. if (valuesInAxis) {
  30490. // Sort axis values into ascending order to calculate gaps
  30491. valuesInAxis.sort(function (a, b) {
  30492. return a - b;
  30493. });
  30494. var min = null;
  30495. for (var j = 1; j < valuesInAxis.length; ++j) {
  30496. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30497. if (delta > 0) {
  30498. // Ignore 0 delta because they are of the same axis value
  30499. min = min === null ? delta : Math.min(min, delta);
  30500. }
  30501. } // Set to null if only have one data
  30502. axisMinGaps[key] = min;
  30503. }
  30504. }
  30505. }
  30506. return axisMinGaps;
  30507. }
  30508. function makeColumnLayout(barSeries) {
  30509. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30510. var seriesInfoList = [];
  30511. each(barSeries, function (seriesModel) {
  30512. var cartesian = seriesModel.coordinateSystem;
  30513. var baseAxis = cartesian.getBaseAxis();
  30514. var axisExtent = baseAxis.getExtent();
  30515. var bandWidth;
  30516. if (baseAxis.type === 'category') {
  30517. bandWidth = baseAxis.getBandWidth();
  30518. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30519. var key = baseAxis.dim + '_' + baseAxis.index;
  30520. var minGap = axisMinGaps[key];
  30521. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30522. var scale = baseAxis.scale.getExtent();
  30523. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30524. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30525. } else {
  30526. var data = seriesModel.getData();
  30527. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30528. }
  30529. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30530. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30531. var barMinWidth = parsePercent$1( // barMinWidth by default is 0.5 / 1 in cartesian. Because in value axis,
  30532. // the auto-calculated bar width might be less than 0.5 / 1.
  30533. seriesModel.get('barMinWidth') || (isInLargeMode(seriesModel) ? 0.5 : 1), bandWidth);
  30534. var barGap = seriesModel.get('barGap');
  30535. var barCategoryGap = seriesModel.get('barCategoryGap');
  30536. seriesInfoList.push({
  30537. bandWidth: bandWidth,
  30538. barWidth: barWidth,
  30539. barMaxWidth: barMaxWidth,
  30540. barMinWidth: barMinWidth,
  30541. barGap: barGap,
  30542. barCategoryGap: barCategoryGap,
  30543. axisKey: getAxisKey(baseAxis),
  30544. stackId: getSeriesStackId(seriesModel)
  30545. });
  30546. });
  30547. return doCalBarWidthAndOffset(seriesInfoList);
  30548. }
  30549. function doCalBarWidthAndOffset(seriesInfoList) {
  30550. // Columns info on each category axis. Key is cartesian name
  30551. var columnsMap = {};
  30552. each(seriesInfoList, function (seriesInfo, idx) {
  30553. var axisKey = seriesInfo.axisKey;
  30554. var bandWidth = seriesInfo.bandWidth;
  30555. var columnsOnAxis = columnsMap[axisKey] || {
  30556. bandWidth: bandWidth,
  30557. remainedWidth: bandWidth,
  30558. autoWidthCount: 0,
  30559. categoryGap: null,
  30560. gap: '20%',
  30561. stacks: {}
  30562. };
  30563. var stacks = columnsOnAxis.stacks;
  30564. columnsMap[axisKey] = columnsOnAxis;
  30565. var stackId = seriesInfo.stackId;
  30566. if (!stacks[stackId]) {
  30567. columnsOnAxis.autoWidthCount++;
  30568. }
  30569. stacks[stackId] = stacks[stackId] || {
  30570. width: 0,
  30571. maxWidth: 0
  30572. }; // Caution: In a single coordinate system, these barGrid attributes
  30573. // will be shared by series. Consider that they have default values,
  30574. // only the attributes set on the last series will work.
  30575. // Do not change this fact unless there will be a break change.
  30576. var barWidth = seriesInfo.barWidth;
  30577. if (barWidth && !stacks[stackId].width) {
  30578. // See #6312, do not restrict width.
  30579. stacks[stackId].width = barWidth;
  30580. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30581. columnsOnAxis.remainedWidth -= barWidth;
  30582. }
  30583. var barMaxWidth = seriesInfo.barMaxWidth;
  30584. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30585. var barMinWidth = seriesInfo.barMinWidth;
  30586. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30587. var barGap = seriesInfo.barGap;
  30588. barGap != null && (columnsOnAxis.gap = barGap);
  30589. var barCategoryGap = seriesInfo.barCategoryGap;
  30590. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30591. });
  30592. var result = {};
  30593. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30594. result[coordSysName] = {};
  30595. var stacks = columnsOnAxis.stacks;
  30596. var bandWidth = columnsOnAxis.bandWidth;
  30597. var categoryGapPercent = columnsOnAxis.categoryGap;
  30598. if (categoryGapPercent == null) {
  30599. var columnCount = keys(stacks).length; // More columns in one group
  30600. // the spaces between group is smaller. Or the column will be too thin.
  30601. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30602. }
  30603. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30604. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30605. var remainedWidth = columnsOnAxis.remainedWidth;
  30606. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30607. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30608. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30609. each(stacks, function (column) {
  30610. var maxWidth = column.maxWidth;
  30611. var minWidth = column.minWidth;
  30612. if (!column.width) {
  30613. var finalWidth = autoWidth;
  30614. if (maxWidth && maxWidth < finalWidth) {
  30615. finalWidth = Math.min(maxWidth, remainedWidth);
  30616. } // `minWidth` has higher priority. `minWidth` decide that whether the
  30617. // bar is able to be visible. So `minWidth` should not be restricted
  30618. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30619. // the extreme cases for `value` axis, bars are allowed to overlap
  30620. // with each other if `minWidth` specified.
  30621. if (minWidth && minWidth > finalWidth) {
  30622. finalWidth = minWidth;
  30623. }
  30624. if (finalWidth !== autoWidth) {
  30625. column.width = finalWidth;
  30626. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30627. autoWidthCount--;
  30628. }
  30629. } else {
  30630. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30631. // CSS does. Because barWidth can be a percent value, where
  30632. // `barMaxWidth` can be used to restrict the final width.
  30633. var finalWidth = column.width;
  30634. if (maxWidth) {
  30635. finalWidth = Math.min(finalWidth, maxWidth);
  30636. } // `minWidth` has higher priority, as described above
  30637. if (minWidth) {
  30638. finalWidth = Math.max(finalWidth, minWidth);
  30639. }
  30640. column.width = finalWidth;
  30641. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30642. autoWidthCount--;
  30643. }
  30644. }); // Recalculate width again
  30645. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30646. autoWidth = Math.max(autoWidth, 0);
  30647. var widthSum = 0;
  30648. var lastColumn;
  30649. each(stacks, function (column, idx) {
  30650. if (!column.width) {
  30651. column.width = autoWidth;
  30652. }
  30653. lastColumn = column;
  30654. widthSum += column.width * (1 + barGapPercent);
  30655. });
  30656. if (lastColumn) {
  30657. widthSum -= lastColumn.width * barGapPercent;
  30658. }
  30659. var offset = -widthSum / 2;
  30660. each(stacks, function (column, stackId) {
  30661. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30662. bandWidth: bandWidth,
  30663. offset: offset,
  30664. width: column.width
  30665. };
  30666. offset += column.width * (1 + barGapPercent);
  30667. });
  30668. });
  30669. return result;
  30670. }
  30671. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30672. if (barWidthAndOffset && axis) {
  30673. var result = barWidthAndOffset[getAxisKey(axis)];
  30674. if (result != null && seriesModel != null) {
  30675. return result[getSeriesStackId(seriesModel)];
  30676. }
  30677. return result;
  30678. }
  30679. }
  30680. function layout(seriesType, ecModel) {
  30681. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30682. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30683. each(seriesModels, function (seriesModel) {
  30684. var data = seriesModel.getData();
  30685. var cartesian = seriesModel.coordinateSystem;
  30686. var baseAxis = cartesian.getBaseAxis();
  30687. var stackId = getSeriesStackId(seriesModel);
  30688. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30689. var columnOffset = columnLayoutInfo.offset;
  30690. var columnWidth = columnLayoutInfo.width;
  30691. data.setLayout({
  30692. bandWidth: columnLayoutInfo.bandWidth,
  30693. offset: columnOffset,
  30694. size: columnWidth
  30695. });
  30696. });
  30697. } // TODO: Do not support stack in large mode yet.
  30698. function createProgressiveLayout(seriesType) {
  30699. return {
  30700. seriesType: seriesType,
  30701. plan: createRenderPlanner(),
  30702. reset: function (seriesModel) {
  30703. if (!isOnCartesian(seriesModel)) {
  30704. return;
  30705. }
  30706. var data = seriesModel.getData();
  30707. var cartesian = seriesModel.coordinateSystem;
  30708. var baseAxis = cartesian.getBaseAxis();
  30709. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30710. var valueDimIdx = data.getDimensionIndex(data.mapDimension(valueAxis.dim));
  30711. var baseDimIdx = data.getDimensionIndex(data.mapDimension(baseAxis.dim));
  30712. var drawBackground = seriesModel.get('showBackground', true);
  30713. var valueDim = data.mapDimension(valueAxis.dim);
  30714. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  30715. var stacked = isDimensionStacked(data, valueDim) && !!data.getCalculationInfo('stackedOnSeries');
  30716. var isValueAxisH = valueAxis.isHorizontal();
  30717. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30718. var isLarge = isInLargeMode(seriesModel);
  30719. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30720. var stackedDimIdx = stackResultDim && data.getDimensionIndex(stackResultDim); // Layout info.
  30721. var columnWidth = data.getLayout('size');
  30722. var columnOffset = data.getLayout('offset');
  30723. return {
  30724. progress: function (params, data) {
  30725. var count = params.count;
  30726. var largePoints = isLarge && createFloat32Array(count * 3);
  30727. var largeBackgroundPoints = isLarge && drawBackground && createFloat32Array(count * 3);
  30728. var largeDataIndices = isLarge && createFloat32Array(count);
  30729. var coordLayout = cartesian.master.getRect();
  30730. var bgSize = isValueAxisH ? coordLayout.width : coordLayout.height;
  30731. var dataIndex;
  30732. var store = data.getStore();
  30733. var idxOffset = 0;
  30734. while ((dataIndex = params.next()) != null) {
  30735. var value = store.get(stacked ? stackedDimIdx : valueDimIdx, dataIndex);
  30736. var baseValue = store.get(baseDimIdx, dataIndex);
  30737. var baseCoord = valueAxisStart;
  30738. var startValue = void 0; // Because of the barMinHeight, we can not use the value in
  30739. // stackResultDimension directly.
  30740. if (stacked) {
  30741. startValue = +value - store.get(valueDimIdx, dataIndex);
  30742. }
  30743. var x = void 0;
  30744. var y = void 0;
  30745. var width = void 0;
  30746. var height = void 0;
  30747. if (isValueAxisH) {
  30748. var coord = cartesian.dataToPoint([value, baseValue]);
  30749. if (stacked) {
  30750. var startCoord = cartesian.dataToPoint([startValue, baseValue]);
  30751. baseCoord = startCoord[0];
  30752. }
  30753. x = baseCoord;
  30754. y = coord[1] + columnOffset;
  30755. width = coord[0] - baseCoord;
  30756. height = columnWidth;
  30757. if (Math.abs(width) < barMinHeight) {
  30758. width = (width < 0 ? -1 : 1) * barMinHeight;
  30759. }
  30760. } else {
  30761. var coord = cartesian.dataToPoint([baseValue, value]);
  30762. if (stacked) {
  30763. var startCoord = cartesian.dataToPoint([baseValue, startValue]);
  30764. baseCoord = startCoord[1];
  30765. }
  30766. x = coord[0] + columnOffset;
  30767. y = baseCoord;
  30768. width = columnWidth;
  30769. height = coord[1] - baseCoord;
  30770. if (Math.abs(height) < barMinHeight) {
  30771. // Include zero to has a positive bar
  30772. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30773. }
  30774. }
  30775. if (!isLarge) {
  30776. data.setItemLayout(dataIndex, {
  30777. x: x,
  30778. y: y,
  30779. width: width,
  30780. height: height
  30781. });
  30782. } else {
  30783. largePoints[idxOffset] = x;
  30784. largePoints[idxOffset + 1] = y;
  30785. largePoints[idxOffset + 2] = isValueAxisH ? width : height;
  30786. if (largeBackgroundPoints) {
  30787. largeBackgroundPoints[idxOffset] = isValueAxisH ? coordLayout.x : x;
  30788. largeBackgroundPoints[idxOffset + 1] = isValueAxisH ? y : coordLayout.y;
  30789. largeBackgroundPoints[idxOffset + 2] = bgSize;
  30790. }
  30791. largeDataIndices[dataIndex] = dataIndex;
  30792. }
  30793. idxOffset += 3;
  30794. }
  30795. if (isLarge) {
  30796. data.setLayout({
  30797. largePoints: largePoints,
  30798. largeDataIndices: largeDataIndices,
  30799. largeBackgroundPoints: largeBackgroundPoints,
  30800. valueAxisHorizontal: isValueAxisH
  30801. });
  30802. }
  30803. }
  30804. };
  30805. }
  30806. };
  30807. }
  30808. function isOnCartesian(seriesModel) {
  30809. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30810. }
  30811. function isInLargeMode(seriesModel) {
  30812. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30813. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30814. function getValueAxisStart(baseAxis, valueAxis) {
  30815. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30816. }
  30817. var bisect = function (a, x, lo, hi) {
  30818. while (lo < hi) {
  30819. var mid = lo + hi >>> 1;
  30820. if (a[mid][1] < x) {
  30821. lo = mid + 1;
  30822. } else {
  30823. hi = mid;
  30824. }
  30825. }
  30826. return lo;
  30827. };
  30828. var TimeScale =
  30829. /** @class */
  30830. function (_super) {
  30831. __extends(TimeScale, _super);
  30832. function TimeScale(settings) {
  30833. var _this = _super.call(this, settings) || this;
  30834. _this.type = 'time';
  30835. return _this;
  30836. }
  30837. /**
  30838. * Get label is mainly for other components like dataZoom, tooltip.
  30839. */
  30840. TimeScale.prototype.getLabel = function (tick) {
  30841. var useUTC = this.getSetting('useUTC');
  30842. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30843. };
  30844. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30845. var isUTC = this.getSetting('useUTC');
  30846. var lang = this.getSetting('locale');
  30847. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30848. };
  30849. /**
  30850. * @override
  30851. */
  30852. TimeScale.prototype.getTicks = function () {
  30853. var interval = this._interval;
  30854. var extent = this._extent;
  30855. var ticks = []; // If interval is 0, return [];
  30856. if (!interval) {
  30857. return ticks;
  30858. }
  30859. ticks.push({
  30860. value: extent[0],
  30861. level: 0
  30862. });
  30863. var useUTC = this.getSetting('useUTC');
  30864. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30865. ticks = ticks.concat(innerTicks);
  30866. ticks.push({
  30867. value: extent[1],
  30868. level: 0
  30869. });
  30870. return ticks;
  30871. };
  30872. TimeScale.prototype.calcNiceExtent = function (opt) {
  30873. var extent = this._extent; // If extent start and end are same, expand them
  30874. if (extent[0] === extent[1]) {
  30875. // Expand extent
  30876. extent[0] -= ONE_DAY;
  30877. extent[1] += ONE_DAY;
  30878. } // If there are no data and extent are [Infinity, -Infinity]
  30879. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30880. var d = new Date();
  30881. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30882. extent[0] = extent[1] - ONE_DAY;
  30883. }
  30884. this.calcNiceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30885. };
  30886. TimeScale.prototype.calcNiceTicks = function (approxTickNum, minInterval, maxInterval) {
  30887. approxTickNum = approxTickNum || 10;
  30888. var extent = this._extent;
  30889. var span = extent[1] - extent[0];
  30890. this._approxInterval = span / approxTickNum;
  30891. if (minInterval != null && this._approxInterval < minInterval) {
  30892. this._approxInterval = minInterval;
  30893. }
  30894. if (maxInterval != null && this._approxInterval > maxInterval) {
  30895. this._approxInterval = maxInterval;
  30896. }
  30897. var scaleIntervalsLen = scaleIntervals.length;
  30898. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30899. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30900. // We check one more level to avoid the ticks are to sparse in some case.
  30901. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30902. };
  30903. TimeScale.prototype.parse = function (val) {
  30904. // val might be float.
  30905. return isNumber(val) ? val : +parseDate(val);
  30906. };
  30907. TimeScale.prototype.contain = function (val) {
  30908. return contain$1(this.parse(val), this._extent);
  30909. };
  30910. TimeScale.prototype.normalize = function (val) {
  30911. return normalize$1(this.parse(val), this._extent);
  30912. };
  30913. TimeScale.prototype.scale = function (val) {
  30914. return scale$2(val, this._extent);
  30915. };
  30916. TimeScale.type = 'time';
  30917. return TimeScale;
  30918. }(IntervalScale);
  30919. /**
  30920. * This implementation was originally copied from "d3.js"
  30921. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30922. * with some modifications made for this program.
  30923. * See the license statement at the head of this file.
  30924. */
  30925. var scaleIntervals = [// Format interval
  30926. ['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
  30927. ];
  30928. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30929. var dateA = parseDate(valueA);
  30930. var dateB = parseDate(valueB);
  30931. var isSame = function (unit) {
  30932. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30933. };
  30934. var isSameYear = function () {
  30935. return isSame('year');
  30936. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30937. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30938. var isSameMonth = function () {
  30939. return isSameYear() && isSame('month');
  30940. };
  30941. var isSameDay = function () {
  30942. return isSameMonth() && isSame('day');
  30943. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30944. var isSameHour = function () {
  30945. return isSameDay() && isSame('hour');
  30946. };
  30947. var isSameMinute = function () {
  30948. return isSameHour() && isSame('minute');
  30949. };
  30950. var isSameSecond = function () {
  30951. return isSameMinute() && isSame('second');
  30952. };
  30953. var isSameMilliSecond = function () {
  30954. return isSameSecond() && isSame('millisecond');
  30955. };
  30956. switch (unit) {
  30957. case 'year':
  30958. return isSameYear();
  30959. case 'month':
  30960. return isSameMonth();
  30961. case 'day':
  30962. return isSameDay();
  30963. case 'hour':
  30964. return isSameHour();
  30965. case 'minute':
  30966. return isSameMinute();
  30967. case 'second':
  30968. return isSameSecond();
  30969. case 'millisecond':
  30970. return isSameMilliSecond();
  30971. }
  30972. } // const primaryUnitGetters = {
  30973. // year: fullYearGetterName(),
  30974. // month: monthGetterName(),
  30975. // day: dateGetterName(),
  30976. // hour: hoursGetterName(),
  30977. // minute: minutesGetterName(),
  30978. // second: secondsGetterName(),
  30979. // millisecond: millisecondsGetterName()
  30980. // };
  30981. // const primaryUnitUTCGetters = {
  30982. // year: fullYearGetterName(true),
  30983. // month: monthGetterName(true),
  30984. // day: dateGetterName(true),
  30985. // hour: hoursGetterName(true),
  30986. // minute: minutesGetterName(true),
  30987. // second: secondsGetterName(true),
  30988. // millisecond: millisecondsGetterName(true)
  30989. // };
  30990. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30991. // step = step || 1;
  30992. // switch (getPrimaryTimeUnit(unitName)) {
  30993. // case 'year':
  30994. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30995. // break;
  30996. // case 'month':
  30997. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30998. // break;
  30999. // case 'day':
  31000. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  31001. // break;
  31002. // case 'hour':
  31003. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  31004. // break;
  31005. // case 'minute':
  31006. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  31007. // break;
  31008. // case 'second':
  31009. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  31010. // break;
  31011. // case 'millisecond':
  31012. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  31013. // break;
  31014. // }
  31015. // return date.getTime();
  31016. // }
  31017. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  31018. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  31019. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  31020. function getDateInterval(approxInterval, daysInMonth) {
  31021. approxInterval /= ONE_DAY;
  31022. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick between two months.
  31023. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  31024. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  31025. }
  31026. function getMonthInterval(approxInterval) {
  31027. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  31028. approxInterval /= APPROX_ONE_MONTH;
  31029. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  31030. }
  31031. function getHourInterval(approxInterval) {
  31032. approxInterval /= ONE_HOUR;
  31033. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  31034. }
  31035. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  31036. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  31037. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  31038. }
  31039. function getMillisecondsInterval(approxInterval) {
  31040. return nice(approxInterval, true);
  31041. }
  31042. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  31043. var outDate = new Date(date);
  31044. switch (getPrimaryTimeUnit(unitName)) {
  31045. case 'year':
  31046. case 'month':
  31047. outDate[monthSetterName(isUTC)](0);
  31048. case 'day':
  31049. outDate[dateSetterName(isUTC)](1);
  31050. case 'hour':
  31051. outDate[hoursSetterName(isUTC)](0);
  31052. case 'minute':
  31053. outDate[minutesSetterName(isUTC)](0);
  31054. case 'second':
  31055. outDate[secondsSetterName(isUTC)](0);
  31056. outDate[millisecondsSetterName(isUTC)](0);
  31057. }
  31058. return outDate.getTime();
  31059. }
  31060. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  31061. var safeLimit = 10000;
  31062. var unitNames = timeUnits;
  31063. var iter = 0;
  31064. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  31065. var date = new Date(minTimestamp);
  31066. var dateTime = minTimestamp;
  31067. var d = date[getMethodName](); // if (isDate) {
  31068. // d -= 1; // Starts with 0; PENDING
  31069. // }
  31070. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  31071. out.push({
  31072. value: dateTime
  31073. });
  31074. d += interval;
  31075. date[setMethodName](d);
  31076. dateTime = date.getTime();
  31077. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  31078. out.push({
  31079. value: dateTime,
  31080. notAdd: true
  31081. });
  31082. }
  31083. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  31084. var newAddedTicks = [];
  31085. var isFirstLevel = !lastLevelTicks.length;
  31086. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  31087. return;
  31088. }
  31089. if (isFirstLevel) {
  31090. lastLevelTicks = [{
  31091. // TODO Optimize. Not include so may ticks.
  31092. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  31093. }, {
  31094. value: extent[1]
  31095. }];
  31096. }
  31097. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  31098. var startTick = lastLevelTicks[i].value;
  31099. var endTick = lastLevelTicks[i + 1].value;
  31100. if (startTick === endTick) {
  31101. continue;
  31102. }
  31103. var interval = void 0;
  31104. var getterName = void 0;
  31105. var setterName = void 0;
  31106. var isDate = false;
  31107. switch (unitName) {
  31108. case 'year':
  31109. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  31110. getterName = fullYearGetterName(isUTC);
  31111. setterName = fullYearSetterName(isUTC);
  31112. break;
  31113. case 'half-year':
  31114. case 'quarter':
  31115. case 'month':
  31116. interval = getMonthInterval(approxInterval);
  31117. getterName = monthGetterName(isUTC);
  31118. setterName = monthSetterName(isUTC);
  31119. break;
  31120. case 'week': // PENDING If week is added. Ignore day.
  31121. case 'half-week':
  31122. case 'day':
  31123. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  31124. getterName = dateGetterName(isUTC);
  31125. setterName = dateSetterName(isUTC);
  31126. isDate = true;
  31127. break;
  31128. case 'half-day':
  31129. case 'quarter-day':
  31130. case 'hour':
  31131. interval = getHourInterval(approxInterval);
  31132. getterName = hoursGetterName(isUTC);
  31133. setterName = hoursSetterName(isUTC);
  31134. break;
  31135. case 'minute':
  31136. interval = getMinutesAndSecondsInterval(approxInterval, true);
  31137. getterName = minutesGetterName(isUTC);
  31138. setterName = minutesSetterName(isUTC);
  31139. break;
  31140. case 'second':
  31141. interval = getMinutesAndSecondsInterval(approxInterval, false);
  31142. getterName = secondsGetterName(isUTC);
  31143. setterName = secondsSetterName(isUTC);
  31144. break;
  31145. case 'millisecond':
  31146. interval = getMillisecondsInterval(approxInterval);
  31147. getterName = millisecondsGetterName(isUTC);
  31148. setterName = millisecondsSetterName(isUTC);
  31149. break;
  31150. }
  31151. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  31152. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  31153. // Add nearest years to the left extent.
  31154. levelTicks.unshift({
  31155. value: levelTicks[0].value - interval
  31156. });
  31157. }
  31158. }
  31159. for (var i = 0; i < newAddedTicks.length; i++) {
  31160. levelTicks.push(newAddedTicks[i]);
  31161. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  31162. return newAddedTicks;
  31163. }
  31164. var levelsTicks = [];
  31165. var currentLevelTicks = [];
  31166. var tickCount = 0;
  31167. var lastLevelTickCount = 0;
  31168. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  31169. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  31170. if (!isPrimaryTimeUnit(unitNames[i])) {
  31171. // TODO
  31172. continue;
  31173. }
  31174. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  31175. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  31176. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  31177. if (currentLevelTicks.length) {
  31178. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  31179. currentLevelTicks.sort(function (a, b) {
  31180. return a.value - b.value;
  31181. });
  31182. var levelTicksRemoveDuplicated = [];
  31183. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  31184. var tickValue = currentLevelTicks[i_1].value;
  31185. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  31186. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  31187. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  31188. tickCount++;
  31189. }
  31190. }
  31191. }
  31192. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  31193. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  31194. break;
  31195. } // Only treat primary time unit as one level.
  31196. levelsTicks.push(levelTicksRemoveDuplicated);
  31197. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  31198. break;
  31199. }
  31200. } // Reset if next unitName is primary
  31201. currentLevelTicks = [];
  31202. }
  31203. }
  31204. if ("development" !== 'production') {
  31205. if (iter >= safeLimit) {
  31206. warn('Exceed safe limit.');
  31207. }
  31208. }
  31209. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  31210. return filter(levelTicks, function (tick) {
  31211. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  31212. });
  31213. }), function (levelTicks) {
  31214. return levelTicks.length > 0;
  31215. });
  31216. var ticks = [];
  31217. var maxLevel = levelsTicksInExtent.length - 1;
  31218. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  31219. var levelTicks = levelsTicksInExtent[i];
  31220. for (var k = 0; k < levelTicks.length; ++k) {
  31221. ticks.push({
  31222. value: levelTicks[k].value,
  31223. level: maxLevel - i
  31224. });
  31225. }
  31226. }
  31227. ticks.sort(function (a, b) {
  31228. return a.value - b.value;
  31229. }); // Remove duplicates
  31230. var result = [];
  31231. for (var i = 0; i < ticks.length; ++i) {
  31232. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  31233. result.push(ticks[i]);
  31234. }
  31235. }
  31236. return result;
  31237. }
  31238. Scale.registerClass(TimeScale);
  31239. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  31240. var intervalScaleProto = IntervalScale.prototype;
  31241. var roundingErrorFix = round;
  31242. var mathFloor = Math.floor;
  31243. var mathCeil = Math.ceil;
  31244. var mathPow$1 = Math.pow;
  31245. var mathLog = Math.log;
  31246. var LogScale =
  31247. /** @class */
  31248. function (_super) {
  31249. __extends(LogScale, _super);
  31250. function LogScale() {
  31251. var _this = _super !== null && _super.apply(this, arguments) || this;
  31252. _this.type = 'log';
  31253. _this.base = 10;
  31254. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  31255. _this._interval = 0;
  31256. return _this;
  31257. }
  31258. /**
  31259. * @param Whether expand the ticks to niced extent.
  31260. */
  31261. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  31262. var originalScale = this._originalScale;
  31263. var extent = this._extent;
  31264. var originalExtent = originalScale.getExtent();
  31265. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  31266. return map(ticks, function (tick) {
  31267. var val = tick.value;
  31268. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  31269. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  31270. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  31271. return {
  31272. value: powVal
  31273. };
  31274. }, this);
  31275. };
  31276. LogScale.prototype.setExtent = function (start, end) {
  31277. var base = mathLog(this.base); // log(-Infinity) is NaN, so safe guard here
  31278. start = mathLog(Math.max(0, start)) / base;
  31279. end = mathLog(Math.max(0, end)) / base;
  31280. intervalScaleProto.setExtent.call(this, start, end);
  31281. };
  31282. /**
  31283. * @return {number} end
  31284. */
  31285. LogScale.prototype.getExtent = function () {
  31286. var base = this.base;
  31287. var extent = scaleProto.getExtent.call(this);
  31288. extent[0] = mathPow$1(base, extent[0]);
  31289. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  31290. var originalScale = this._originalScale;
  31291. var originalExtent = originalScale.getExtent();
  31292. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  31293. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  31294. return extent;
  31295. };
  31296. LogScale.prototype.unionExtent = function (extent) {
  31297. this._originalScale.unionExtent(extent);
  31298. var base = this.base;
  31299. extent[0] = mathLog(extent[0]) / mathLog(base);
  31300. extent[1] = mathLog(extent[1]) / mathLog(base);
  31301. scaleProto.unionExtent.call(this, extent);
  31302. };
  31303. LogScale.prototype.unionExtentFromData = function (data, dim) {
  31304. // TODO
  31305. // filter value that <= 0
  31306. this.unionExtent(data.getApproximateExtent(dim));
  31307. };
  31308. /**
  31309. * Update interval and extent of intervals for nice ticks
  31310. * @param approxTickNum default 10 Given approx tick number
  31311. */
  31312. LogScale.prototype.calcNiceTicks = function (approxTickNum) {
  31313. approxTickNum = approxTickNum || 10;
  31314. var extent = this._extent;
  31315. var span = extent[1] - extent[0];
  31316. if (span === Infinity || span <= 0) {
  31317. return;
  31318. }
  31319. var interval = quantity(span);
  31320. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  31321. if (err <= 0.5) {
  31322. interval *= 10;
  31323. } // Interval should be integer
  31324. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  31325. interval *= 10;
  31326. }
  31327. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor(extent[1] / interval) * interval)];
  31328. this._interval = interval;
  31329. this._niceExtent = niceExtent;
  31330. };
  31331. LogScale.prototype.calcNiceExtent = function (opt) {
  31332. intervalScaleProto.calcNiceExtent.call(this, opt);
  31333. this._fixMin = opt.fixMin;
  31334. this._fixMax = opt.fixMax;
  31335. };
  31336. LogScale.prototype.parse = function (val) {
  31337. return val;
  31338. };
  31339. LogScale.prototype.contain = function (val) {
  31340. val = mathLog(val) / mathLog(this.base);
  31341. return contain$1(val, this._extent);
  31342. };
  31343. LogScale.prototype.normalize = function (val) {
  31344. val = mathLog(val) / mathLog(this.base);
  31345. return normalize$1(val, this._extent);
  31346. };
  31347. LogScale.prototype.scale = function (val) {
  31348. val = scale$2(val, this._extent);
  31349. return mathPow$1(this.base, val);
  31350. };
  31351. LogScale.type = 'log';
  31352. return LogScale;
  31353. }(Scale);
  31354. var proto = LogScale.prototype;
  31355. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  31356. proto.getLabel = intervalScaleProto.getLabel;
  31357. function fixRoundingError(val, originalVal) {
  31358. return roundingErrorFix(val, getPrecision(originalVal));
  31359. }
  31360. Scale.registerClass(LogScale);
  31361. var ScaleRawExtentInfo =
  31362. /** @class */
  31363. function () {
  31364. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31365. originalExtent) {
  31366. this._prepareParams(scale, model, originalExtent);
  31367. }
  31368. /**
  31369. * Parameters depending on outside (like model, user callback)
  31370. * are prepared and fixed here.
  31371. */
  31372. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  31373. dataExtent) {
  31374. if (dataExtent[1] < dataExtent[0]) {
  31375. dataExtent = [NaN, NaN];
  31376. }
  31377. this._dataMin = dataExtent[0];
  31378. this._dataMax = dataExtent[1];
  31379. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  31380. this._needCrossZero = scale.type === 'interval' && model.getNeedCrossZero && model.getNeedCrossZero();
  31381. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  31382. if (isFunction(modelMinRaw)) {
  31383. // This callback always provides users the full data extent (before data is filtered).
  31384. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  31385. min: dataExtent[0],
  31386. max: dataExtent[1]
  31387. }));
  31388. } else if (modelMinRaw !== 'dataMin') {
  31389. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  31390. }
  31391. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  31392. if (isFunction(modelMaxRaw)) {
  31393. // This callback always provides users the full data extent (before data is filtered).
  31394. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  31395. min: dataExtent[0],
  31396. max: dataExtent[1]
  31397. }));
  31398. } else if (modelMaxRaw !== 'dataMax') {
  31399. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  31400. }
  31401. if (isOrdinal) {
  31402. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  31403. // and progressive rendering is using, here the category result might just only contain
  31404. // the processed chunk rather than the entire result.
  31405. this._axisDataLen = model.getCategories().length;
  31406. } else {
  31407. var boundaryGap = model.get('boundaryGap');
  31408. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  31409. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  31410. if ("development" !== 'production') {
  31411. 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.');
  31412. }
  31413. this._boundaryGapInner = [0, 0];
  31414. } else {
  31415. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  31416. }
  31417. }
  31418. };
  31419. /**
  31420. * Calculate extent by prepared parameters.
  31421. * This method has no external dependency and can be called duplicatedly,
  31422. * getting the same result.
  31423. * If parameters changed, should call this method to recalcuate.
  31424. */
  31425. ScaleRawExtentInfo.prototype.calculate = function () {
  31426. // Notice: When min/max is not set (that is, when there are null/undefined,
  31427. // which is the most common case), these cases should be ensured:
  31428. // (1) For 'ordinal', show all axis.data.
  31429. // (2) For others:
  31430. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  31431. // disabled).
  31432. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  31433. // be the result that originalExtent enlarged by boundaryGap.
  31434. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  31435. var isOrdinal = this._isOrdinal;
  31436. var dataMin = this._dataMin;
  31437. var dataMax = this._dataMax;
  31438. var axisDataLen = this._axisDataLen;
  31439. var boundaryGapInner = this._boundaryGapInner;
  31440. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  31441. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  31442. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  31443. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  31444. var minFixed = min != null;
  31445. var maxFixed = max != null;
  31446. if (min == null) {
  31447. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31448. }
  31449. if (max == null) {
  31450. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31451. }
  31452. (min == null || !isFinite(min)) && (min = NaN);
  31453. (max == null || !isFinite(max)) && (max = NaN);
  31454. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  31455. if (this._needCrossZero) {
  31456. // Axis is over zero and min is not set
  31457. if (min > 0 && max > 0 && !minFixed) {
  31458. min = 0; // minFixed = true;
  31459. } // Axis is under zero and max is not set
  31460. if (min < 0 && max < 0 && !maxFixed) {
  31461. max = 0; // maxFixed = true;
  31462. } // PENDING:
  31463. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31464. // that the results processed by boundaryGap are positive/negative?
  31465. // If so, here `minFixed`/`maxFixed` need to be set.
  31466. }
  31467. var determinedMin = this._determinedMin;
  31468. var determinedMax = this._determinedMax;
  31469. if (determinedMin != null) {
  31470. min = determinedMin;
  31471. minFixed = true;
  31472. }
  31473. if (determinedMax != null) {
  31474. max = determinedMax;
  31475. maxFixed = true;
  31476. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31477. // `NaN` means min/max axis is blank.
  31478. return {
  31479. min: min,
  31480. max: max,
  31481. minFixed: minFixed,
  31482. maxFixed: maxFixed,
  31483. isBlank: isBlank
  31484. };
  31485. };
  31486. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31487. if ("development" !== 'production') {
  31488. assert(!this.frozen);
  31489. }
  31490. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31491. };
  31492. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31493. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31494. if ("development" !== 'production') {
  31495. assert(!this.frozen // Earse them usually means logic flaw.
  31496. && this[attr] == null);
  31497. }
  31498. this[attr] = val;
  31499. };
  31500. ScaleRawExtentInfo.prototype.freeze = function () {
  31501. // @ts-ignore
  31502. this.frozen = true;
  31503. };
  31504. return ScaleRawExtentInfo;
  31505. }();
  31506. var DETERMINED_MIN_MAX_ATTR = {
  31507. min: '_determinedMin',
  31508. max: '_determinedMax'
  31509. };
  31510. var DATA_MIN_MAX_ATTR = {
  31511. min: '_dataMin',
  31512. max: '_dataMax'
  31513. };
  31514. /**
  31515. * Get scale min max and related info only depends on model settings.
  31516. * This method can be called after coordinate system created.
  31517. * For example, in data processing stage.
  31518. *
  31519. * Scale extent info probably be required multiple times during a workflow.
  31520. * For example:
  31521. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31522. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31523. * (3) `coordSys.update` use it to finally decide the scale extent.
  31524. * But the callback of `min`/`max` should not be called multiple times.
  31525. * The code below should not be implemented repeatedly either.
  31526. * So we cache the result in the scale instance, which will be recreated at the beginning
  31527. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31528. */
  31529. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31530. originalExtent) {
  31531. // Do not permit to recreate.
  31532. var rawExtentInfo = scale.rawExtentInfo;
  31533. if (rawExtentInfo) {
  31534. return rawExtentInfo;
  31535. }
  31536. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31537. scale.rawExtentInfo = rawExtentInfo;
  31538. return rawExtentInfo;
  31539. }
  31540. function parseAxisModelMinMax(scale, minMax) {
  31541. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31542. }
  31543. /**
  31544. * Get axis scale extent before niced.
  31545. * Item of returned array can only be number (including Infinity and NaN).
  31546. *
  31547. * Caution:
  31548. * Precondition of calling this method:
  31549. * The scale extent has been initialized using series data extent via
  31550. * `scale.setExtent` or `scale.unionExtentFromData`;
  31551. */
  31552. function getScaleExtent(scale, model) {
  31553. var scaleType = scale.type;
  31554. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31555. scale.setBlank(rawExtentResult.isBlank);
  31556. var min = rawExtentResult.min;
  31557. 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
  31558. // is base axis
  31559. // FIXME
  31560. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31561. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31562. // Should not depend on series type `bar`?
  31563. // (3) Fix that might overlap when using dataZoom.
  31564. // (4) Consider other chart types using `barGrid`?
  31565. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31566. var ecModel = model.ecModel;
  31567. if (ecModel && scaleType === 'time'
  31568. /* || scaleType === 'interval' */
  31569. ) {
  31570. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31571. var isBaseAxisAndHasBarSeries_1 = false;
  31572. each(barSeriesModels, function (seriesModel) {
  31573. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31574. });
  31575. if (isBaseAxisAndHasBarSeries_1) {
  31576. // Calculate placement of bars on axis. TODO should be decoupled
  31577. // with barLayout
  31578. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31579. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31580. min = adjustedScale.min;
  31581. max = adjustedScale.max;
  31582. }
  31583. }
  31584. return {
  31585. extent: [min, max],
  31586. // "fix" means "fixed", the value should not be
  31587. // changed in the subsequent steps.
  31588. fixMin: rawExtentResult.minFixed,
  31589. fixMax: rawExtentResult.maxFixed
  31590. };
  31591. }
  31592. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31593. barWidthAndOffset) {
  31594. // Get Axis Length
  31595. var axisExtent = model.axis.getExtent();
  31596. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31597. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31598. if (barsOnCurrentAxis === undefined) {
  31599. return {
  31600. min: min,
  31601. max: max
  31602. };
  31603. }
  31604. var minOverflow = Infinity;
  31605. each(barsOnCurrentAxis, function (item) {
  31606. minOverflow = Math.min(item.offset, minOverflow);
  31607. });
  31608. var maxOverflow = -Infinity;
  31609. each(barsOnCurrentAxis, function (item) {
  31610. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31611. });
  31612. minOverflow = Math.abs(minOverflow);
  31613. maxOverflow = Math.abs(maxOverflow);
  31614. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31615. var oldRange = max - min;
  31616. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31617. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31618. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31619. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31620. return {
  31621. min: min,
  31622. max: max
  31623. };
  31624. } // Precondition of calling this method:
  31625. // The scale extent has been initialized using series data extent via
  31626. // `scale.setExtent` or `scale.unionExtentFromData`;
  31627. function niceScaleExtent(scale, inModel) {
  31628. var model = inModel;
  31629. var extentInfo = getScaleExtent(scale, model);
  31630. var extent = extentInfo.extent;
  31631. var splitNumber = model.get('splitNumber');
  31632. if (scale instanceof LogScale) {
  31633. scale.base = model.get('logBase');
  31634. }
  31635. var scaleType = scale.type;
  31636. var interval = model.get('interval');
  31637. var isIntervalOrTime = scaleType === 'interval' || scaleType === 'time';
  31638. scale.setExtent(extent[0], extent[1]);
  31639. scale.calcNiceExtent({
  31640. splitNumber: splitNumber,
  31641. fixMin: extentInfo.fixMin,
  31642. fixMax: extentInfo.fixMax,
  31643. minInterval: isIntervalOrTime ? model.get('minInterval') : null,
  31644. maxInterval: isIntervalOrTime ? model.get('maxInterval') : null
  31645. }); // If some one specified the min, max. And the default calculated interval
  31646. // is not good enough. He can specify the interval. It is often appeared
  31647. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31648. // to be 60.
  31649. // FIXME
  31650. if (interval != null) {
  31651. scale.setInterval && scale.setInterval(interval);
  31652. }
  31653. }
  31654. /**
  31655. * @param axisType Default retrieve from model.type
  31656. */
  31657. function createScaleByModel(model, axisType) {
  31658. axisType = axisType || model.get('type');
  31659. if (axisType) {
  31660. switch (axisType) {
  31661. // Buildin scale
  31662. case 'category':
  31663. return new OrdinalScale({
  31664. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31665. extent: [Infinity, -Infinity]
  31666. });
  31667. case 'time':
  31668. return new TimeScale({
  31669. locale: model.ecModel.getLocaleModel(),
  31670. useUTC: model.ecModel.get('useUTC')
  31671. });
  31672. default:
  31673. // case 'value'/'interval', 'log', or others.
  31674. return new (Scale.getClass(axisType) || IntervalScale)();
  31675. }
  31676. }
  31677. }
  31678. /**
  31679. * Check if the axis cross 0
  31680. */
  31681. function ifAxisCrossZero(axis) {
  31682. var dataExtent = axis.scale.getExtent();
  31683. var min = dataExtent[0];
  31684. var max = dataExtent[1];
  31685. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31686. }
  31687. /**
  31688. * @param axis
  31689. * @return Label formatter function.
  31690. * param: {number} tickValue,
  31691. * param: {number} idx, the index in all ticks.
  31692. * If category axis, this param is not required.
  31693. * return: {string} label string.
  31694. */
  31695. function makeLabelFormatter(axis) {
  31696. var labelFormatter = axis.getLabelModel().get('formatter');
  31697. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31698. if (axis.scale.type === 'time') {
  31699. return function (tpl) {
  31700. return function (tick, idx) {
  31701. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31702. };
  31703. }(labelFormatter);
  31704. } else if (isString(labelFormatter)) {
  31705. return function (tpl) {
  31706. return function (tick) {
  31707. // For category axis, get raw value; for numeric axis,
  31708. // get formatted label like '1,333,444'.
  31709. var label = axis.scale.getLabel(tick);
  31710. var text = tpl.replace('{value}', label != null ? label : '');
  31711. return text;
  31712. };
  31713. }(labelFormatter);
  31714. } else if (isFunction(labelFormatter)) {
  31715. return function (cb) {
  31716. return function (tick, idx) {
  31717. // The original intention of `idx` is "the index of the tick in all ticks".
  31718. // But the previous implementation of category axis do not consider the
  31719. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31720. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31721. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31722. // the definition here for back compatibility.
  31723. if (categoryTickStart != null) {
  31724. idx = tick.value - categoryTickStart;
  31725. }
  31726. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31727. level: tick.level
  31728. } : null);
  31729. };
  31730. }(labelFormatter);
  31731. } else {
  31732. return function (tick) {
  31733. return axis.scale.getLabel(tick);
  31734. };
  31735. }
  31736. }
  31737. function getAxisRawValue(axis, tick) {
  31738. // In category axis with data zoom, tick is not the original
  31739. // index of axis.data. So tick should not be exposed to user
  31740. // in category axis.
  31741. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31742. }
  31743. /**
  31744. * @param axis
  31745. * @return Be null/undefined if no labels.
  31746. */
  31747. function estimateLabelUnionRect(axis) {
  31748. var axisModel = axis.model;
  31749. var scale = axis.scale;
  31750. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31751. return;
  31752. }
  31753. var realNumberScaleTicks;
  31754. var tickCount;
  31755. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31756. if (scale instanceof OrdinalScale) {
  31757. tickCount = scale.count();
  31758. } else {
  31759. realNumberScaleTicks = scale.getTicks();
  31760. tickCount = realNumberScaleTicks.length;
  31761. }
  31762. var axisLabelModel = axis.getLabelModel();
  31763. var labelFormatter = makeLabelFormatter(axis);
  31764. var rect;
  31765. var step = 1; // Simple optimization for large amount of labels
  31766. if (tickCount > 40) {
  31767. step = Math.ceil(tickCount / 40);
  31768. }
  31769. for (var i = 0; i < tickCount; i += step) {
  31770. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31771. value: categoryScaleExtent[0] + i
  31772. };
  31773. var label = labelFormatter(tick, i);
  31774. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31775. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31776. rect ? rect.union(singleRect) : rect = singleRect;
  31777. }
  31778. return rect;
  31779. }
  31780. function rotateTextRect(textRect, rotate) {
  31781. var rotateRadians = rotate * Math.PI / 180;
  31782. var beforeWidth = textRect.width;
  31783. var beforeHeight = textRect.height;
  31784. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31785. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31786. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31787. return rotatedRect;
  31788. }
  31789. /**
  31790. * @param model axisLabelModel or axisTickModel
  31791. * @return {number|String} Can be null|'auto'|number|function
  31792. */
  31793. function getOptionCategoryInterval(model) {
  31794. var interval = model.get('interval');
  31795. return interval == null ? 'auto' : interval;
  31796. }
  31797. /**
  31798. * Set `categoryInterval` as 0 implicitly indicates that
  31799. * show all labels regardless of overlap.
  31800. * @param {Object} axis axisModel.axis
  31801. */
  31802. function shouldShowAllLabels(axis) {
  31803. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31804. }
  31805. function getDataDimensionsOnAxis(data, axisDim) {
  31806. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31807. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31808. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31809. // there has been stacked result dim?
  31810. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31811. // For example, the extent of the original dimension
  31812. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31813. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31814. // because there is no graphic corresponding to [0.1, 0.5].
  31815. // See the case in `test/area-stack.html` `main1`, where area line
  31816. // stack needs `yAxis` not start from 0.
  31817. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31818. });
  31819. return keys(dataDimMap);
  31820. }
  31821. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31822. if (data) {
  31823. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31824. var seriesExtent = data.getApproximateExtent(dim);
  31825. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31826. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31827. });
  31828. }
  31829. }
  31830. /*
  31831. * Licensed to the Apache Software Foundation (ASF) under one
  31832. * or more contributor license agreements. See the NOTICE file
  31833. * distributed with this work for additional information
  31834. * regarding copyright ownership. The ASF licenses this file
  31835. * to you under the Apache License, Version 2.0 (the
  31836. * "License"); you may not use this file except in compliance
  31837. * with the License. You may obtain a copy of the License at
  31838. *
  31839. * http://www.apache.org/licenses/LICENSE-2.0
  31840. *
  31841. * Unless required by applicable law or agreed to in writing,
  31842. * software distributed under the License is distributed on an
  31843. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31844. * KIND, either express or implied. See the License for the
  31845. * specific language governing permissions and limitations
  31846. * under the License.
  31847. */
  31848. /**
  31849. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31850. */
  31851. /*
  31852. * Licensed to the Apache Software Foundation (ASF) under one
  31853. * or more contributor license agreements. See the NOTICE file
  31854. * distributed with this work for additional information
  31855. * regarding copyright ownership. The ASF licenses this file
  31856. * to you under the Apache License, Version 2.0 (the
  31857. * "License"); you may not use this file except in compliance
  31858. * with the License. You may obtain a copy of the License at
  31859. *
  31860. * http://www.apache.org/licenses/LICENSE-2.0
  31861. *
  31862. * Unless required by applicable law or agreed to in writing,
  31863. * software distributed under the License is distributed on an
  31864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31865. * KIND, either express or implied. See the License for the
  31866. * specific language governing permissions and limitations
  31867. * under the License.
  31868. */
  31869. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  31870. var AxisModelCommonMixin =
  31871. /** @class */
  31872. function () {
  31873. function AxisModelCommonMixin() {}
  31874. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31875. var option = this.option;
  31876. return !option.scale;
  31877. };
  31878. /**
  31879. * Should be implemented by each axis model if necessary.
  31880. * @return coordinate system model
  31881. */
  31882. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31883. return;
  31884. };
  31885. return AxisModelCommonMixin;
  31886. }();
  31887. /**
  31888. * Create a multi dimension List structure from seriesModel.
  31889. */
  31890. function createList(seriesModel) {
  31891. return createSeriesData(null, seriesModel);
  31892. } // export function createGraph(seriesModel) {
  31893. var dataStack$1 = {
  31894. isDimensionStacked: isDimensionStacked,
  31895. enableDataStack: enableDataStack,
  31896. getStackedDimension: getStackedDimension
  31897. };
  31898. /**
  31899. * Create scale
  31900. * @param {Array.<number>} dataExtent
  31901. * @param {Object|module:echarts/Model} option If `optoin.type`
  31902. * is secified, it can only be `'value'` currently.
  31903. */
  31904. function createScale(dataExtent, option) {
  31905. var axisModel = option;
  31906. if (!(option instanceof Model)) {
  31907. axisModel = new Model(option); // FIXME
  31908. // Currently AxisModelCommonMixin has nothing to do with the
  31909. // the requirements of `axisHelper.createScaleByModel`. For
  31910. // example the methods `getCategories` and `getOrdinalMeta`
  31911. // are required for `'category'` axis, and ecModel is required
  31912. // for `'time'` axis. But occasionally echarts-gl happened
  31913. // to only use `'value'` axis.
  31914. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31915. }
  31916. var scale = createScaleByModel(axisModel);
  31917. scale.setExtent(dataExtent[0], dataExtent[1]);
  31918. niceScaleExtent(scale, axisModel);
  31919. return scale;
  31920. }
  31921. /**
  31922. * Mixin common methods to axis model,
  31923. *
  31924. * Include methods
  31925. * `getFormattedLabels() => Array.<string>`
  31926. * `getCategories() => Array.<string>`
  31927. * `getMin(origin: boolean) => number`
  31928. * `getMax(origin: boolean) => number`
  31929. * `getNeedCrossZero() => boolean`
  31930. */
  31931. function mixinAxisModelCommonMethods(Model) {
  31932. mixin(Model, AxisModelCommonMixin);
  31933. }
  31934. function createTextStyle$1(textStyleModel, opts) {
  31935. opts = opts || {};
  31936. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31937. }
  31938. var helper = /*#__PURE__*/Object.freeze({
  31939. __proto__: null,
  31940. createList: createList,
  31941. getLayoutRect: getLayoutRect,
  31942. dataStack: dataStack$1,
  31943. createScale: createScale,
  31944. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31945. getECData: getECData,
  31946. createTextStyle: createTextStyle$1,
  31947. createDimensions: createDimensions,
  31948. createSymbol: createSymbol,
  31949. enableHoverEmphasis: enableHoverEmphasis
  31950. });
  31951. var EPSILON$4 = 1e-8;
  31952. function isAroundEqual$1(a, b) {
  31953. return Math.abs(a - b) < EPSILON$4;
  31954. }
  31955. function contain$2(points, x, y) {
  31956. var w = 0;
  31957. var p = points[0];
  31958. if (!p) {
  31959. return false;
  31960. }
  31961. for (var i = 1; i < points.length; i++) {
  31962. var p2 = points[i];
  31963. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31964. p = p2;
  31965. }
  31966. var p0 = points[0];
  31967. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31968. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31969. }
  31970. return w !== 0;
  31971. }
  31972. var TMP_TRANSFORM = [];
  31973. function transformPoints(points, transform) {
  31974. for (var p = 0; p < points.length; p++) {
  31975. applyTransform(points[p], points[p], transform);
  31976. }
  31977. }
  31978. function updateBBoxFromPoints(points, min$1, max$1, projection) {
  31979. for (var i = 0; i < points.length; i++) {
  31980. var p = points[i];
  31981. if (projection) {
  31982. // projection may return null point.
  31983. p = projection.project(p);
  31984. }
  31985. if (p && isFinite(p[0]) && isFinite(p[1])) {
  31986. min(min$1, min$1, p);
  31987. max(max$1, max$1, p);
  31988. }
  31989. }
  31990. }
  31991. function centroid(points) {
  31992. var signedArea = 0;
  31993. var cx = 0;
  31994. var cy = 0;
  31995. var len = points.length;
  31996. var x0 = points[len - 1][0];
  31997. var y0 = points[len - 1][1]; // Polygon should been closed.
  31998. for (var i = 0; i < len; i++) {
  31999. var x1 = points[i][0];
  32000. var y1 = points[i][1];
  32001. var a = x0 * y1 - x1 * y0;
  32002. signedArea += a;
  32003. cx += (x0 + x1) * a;
  32004. cy += (y0 + y1) * a;
  32005. x0 = x1;
  32006. y0 = y1;
  32007. }
  32008. return signedArea ? [cx / signedArea / 3, cy / signedArea / 3, signedArea] : [points[0][0] || 0, points[0][1] || 0];
  32009. }
  32010. var Region =
  32011. /** @class */
  32012. function () {
  32013. function Region(name) {
  32014. this.name = name;
  32015. }
  32016. Region.prototype.setCenter = function (center) {
  32017. this._center = center;
  32018. };
  32019. /**
  32020. * Get center point in data unit. That is,
  32021. * for GeoJSONRegion, the unit is lat/lng,
  32022. * for GeoSVGRegion, the unit is SVG local coord.
  32023. */
  32024. Region.prototype.getCenter = function () {
  32025. var center = this._center;
  32026. if (!center) {
  32027. // In most cases there are no need to calculate this center.
  32028. // So calculate only when called.
  32029. center = this._center = this.calcCenter();
  32030. }
  32031. return center;
  32032. };
  32033. return Region;
  32034. }();
  32035. var GeoJSONPolygonGeometry =
  32036. /** @class */
  32037. function () {
  32038. function GeoJSONPolygonGeometry(exterior, interiors) {
  32039. this.type = 'polygon';
  32040. this.exterior = exterior;
  32041. this.interiors = interiors;
  32042. }
  32043. return GeoJSONPolygonGeometry;
  32044. }();
  32045. var GeoJSONLineStringGeometry =
  32046. /** @class */
  32047. function () {
  32048. function GeoJSONLineStringGeometry(points) {
  32049. this.type = 'linestring';
  32050. this.points = points;
  32051. }
  32052. return GeoJSONLineStringGeometry;
  32053. }();
  32054. var GeoJSONRegion =
  32055. /** @class */
  32056. function (_super) {
  32057. __extends(GeoJSONRegion, _super);
  32058. function GeoJSONRegion(name, geometries, cp) {
  32059. var _this = _super.call(this, name) || this;
  32060. _this.type = 'geoJSON';
  32061. _this.geometries = geometries;
  32062. _this._center = cp && [cp[0], cp[1]];
  32063. return _this;
  32064. }
  32065. GeoJSONRegion.prototype.calcCenter = function () {
  32066. var geometries = this.geometries;
  32067. var largestGeo;
  32068. var largestGeoSize = 0;
  32069. for (var i = 0; i < geometries.length; i++) {
  32070. var geo = geometries[i];
  32071. var exterior = geo.exterior; // Simple trick to use points count instead of polygon area as region size.
  32072. // Ignore linestring
  32073. var size = exterior && exterior.length;
  32074. if (size > largestGeoSize) {
  32075. largestGeo = geo;
  32076. largestGeoSize = size;
  32077. }
  32078. }
  32079. if (largestGeo) {
  32080. return centroid(largestGeo.exterior);
  32081. } // from bounding rect by default.
  32082. var rect = this.getBoundingRect();
  32083. return [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32084. };
  32085. GeoJSONRegion.prototype.getBoundingRect = function (projection) {
  32086. var rect = this._rect; // Always recalculate if using projection.
  32087. if (rect && !projection) {
  32088. return rect;
  32089. }
  32090. var min = [Infinity, Infinity];
  32091. var max = [-Infinity, -Infinity];
  32092. var geometries = this.geometries;
  32093. each(geometries, function (geo) {
  32094. if (geo.type === 'polygon') {
  32095. // Doesn't consider hole
  32096. updateBBoxFromPoints(geo.exterior, min, max, projection);
  32097. } else {
  32098. each(geo.points, function (points) {
  32099. updateBBoxFromPoints(points, min, max, projection);
  32100. });
  32101. }
  32102. }); // Normalie invalid bounding.
  32103. if (!(isFinite(min[0]) && isFinite(min[1]) && isFinite(max[0]) && isFinite(max[1]))) {
  32104. min[0] = min[1] = max[0] = max[1] = 0;
  32105. }
  32106. rect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  32107. if (!projection) {
  32108. this._rect = rect;
  32109. }
  32110. return rect;
  32111. };
  32112. GeoJSONRegion.prototype.contain = function (coord) {
  32113. var rect = this.getBoundingRect();
  32114. var geometries = this.geometries;
  32115. if (!rect.contain(coord[0], coord[1])) {
  32116. return false;
  32117. }
  32118. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  32119. var geo = geometries[i]; // Only support polygon.
  32120. if (geo.type !== 'polygon') {
  32121. continue;
  32122. }
  32123. var exterior = geo.exterior;
  32124. var interiors = geo.interiors;
  32125. if (contain$2(exterior, coord[0], coord[1])) {
  32126. // Not in the region if point is in the hole.
  32127. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  32128. if (contain$2(interiors[k], coord[0], coord[1])) {
  32129. continue loopGeo;
  32130. }
  32131. }
  32132. return true;
  32133. }
  32134. }
  32135. return false;
  32136. };
  32137. /**
  32138. * Transform the raw coords to target bounding.
  32139. * @param x
  32140. * @param y
  32141. * @param width
  32142. * @param height
  32143. */
  32144. GeoJSONRegion.prototype.transformTo = function (x, y, width, height) {
  32145. var rect = this.getBoundingRect();
  32146. var aspect = rect.width / rect.height;
  32147. if (!width) {
  32148. width = aspect * height;
  32149. } else if (!height) {
  32150. height = width / aspect;
  32151. }
  32152. var target = new BoundingRect(x, y, width, height);
  32153. var transform = rect.calculateTransform(target);
  32154. var geometries = this.geometries;
  32155. for (var i = 0; i < geometries.length; i++) {
  32156. var geo = geometries[i];
  32157. if (geo.type === 'polygon') {
  32158. transformPoints(geo.exterior, transform);
  32159. each(geo.interiors, function (interior) {
  32160. transformPoints(interior, transform);
  32161. });
  32162. } else {
  32163. each(geo.points, function (points) {
  32164. transformPoints(points, transform);
  32165. });
  32166. }
  32167. }
  32168. rect = this._rect;
  32169. rect.copy(target); // Update center
  32170. this._center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32171. };
  32172. GeoJSONRegion.prototype.cloneShallow = function (name) {
  32173. name == null && (name = this.name);
  32174. var newRegion = new GeoJSONRegion(name, this.geometries, this._center);
  32175. newRegion._rect = this._rect;
  32176. newRegion.transformTo = null; // Simply avoid to be called.
  32177. return newRegion;
  32178. };
  32179. return GeoJSONRegion;
  32180. }(Region);
  32181. var GeoSVGRegion =
  32182. /** @class */
  32183. function (_super) {
  32184. __extends(GeoSVGRegion, _super);
  32185. function GeoSVGRegion(name, elOnlyForCalculate) {
  32186. var _this = _super.call(this, name) || this;
  32187. _this.type = 'geoSVG';
  32188. _this._elOnlyForCalculate = elOnlyForCalculate;
  32189. return _this;
  32190. }
  32191. GeoSVGRegion.prototype.calcCenter = function () {
  32192. var el = this._elOnlyForCalculate;
  32193. var rect = el.getBoundingRect();
  32194. var center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  32195. var mat = identity(TMP_TRANSFORM);
  32196. var target = el;
  32197. while (target && !target.isGeoSVGGraphicRoot) {
  32198. mul$1(mat, target.getLocalTransform(), mat);
  32199. target = target.parent;
  32200. }
  32201. invert(mat, mat);
  32202. applyTransform(center, center, mat);
  32203. return center;
  32204. };
  32205. return GeoSVGRegion;
  32206. }(Region);
  32207. function decode(json) {
  32208. if (!json.UTF8Encoding) {
  32209. return json;
  32210. }
  32211. var jsonCompressed = json;
  32212. var encodeScale = jsonCompressed.UTF8Scale;
  32213. if (encodeScale == null) {
  32214. encodeScale = 1024;
  32215. }
  32216. var features = jsonCompressed.features;
  32217. each(features, function (feature) {
  32218. var geometry = feature.geometry;
  32219. var encodeOffsets = geometry.encodeOffsets;
  32220. var coordinates = geometry.coordinates; // Geometry may be appeded manually in the script after json loaded.
  32221. // In this case this geometry is usually not encoded.
  32222. if (!encodeOffsets) {
  32223. return;
  32224. }
  32225. switch (geometry.type) {
  32226. case 'LineString':
  32227. geometry.coordinates = decodeRing(coordinates, encodeOffsets, encodeScale);
  32228. break;
  32229. case 'Polygon':
  32230. decodeRings(coordinates, encodeOffsets, encodeScale);
  32231. break;
  32232. case 'MultiLineString':
  32233. decodeRings(coordinates, encodeOffsets, encodeScale);
  32234. break;
  32235. case 'MultiPolygon':
  32236. each(coordinates, function (rings, idx) {
  32237. return decodeRings(rings, encodeOffsets[idx], encodeScale);
  32238. });
  32239. }
  32240. }); // Has been decoded
  32241. jsonCompressed.UTF8Encoding = false;
  32242. return jsonCompressed;
  32243. }
  32244. function decodeRings(rings, encodeOffsets, encodeScale) {
  32245. for (var c = 0; c < rings.length; c++) {
  32246. rings[c] = decodeRing(rings[c], encodeOffsets[c], encodeScale);
  32247. }
  32248. }
  32249. function decodeRing(coordinate, encodeOffsets, encodeScale) {
  32250. var result = [];
  32251. var prevX = encodeOffsets[0];
  32252. var prevY = encodeOffsets[1];
  32253. for (var i = 0; i < coordinate.length; i += 2) {
  32254. var x = coordinate.charCodeAt(i) - 64;
  32255. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  32256. x = x >> 1 ^ -(x & 1);
  32257. y = y >> 1 ^ -(y & 1); // Delta deocding
  32258. x += prevX;
  32259. y += prevY;
  32260. prevX = x;
  32261. prevY = y; // Dequantize
  32262. result.push([x / encodeScale, y / encodeScale]);
  32263. }
  32264. return result;
  32265. }
  32266. function parseGeoJSON(geoJson, nameProperty) {
  32267. geoJson = decode(geoJson);
  32268. return map(filter(geoJson.features, function (featureObj) {
  32269. // Output of mapshaper may have geometry null
  32270. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  32271. }), function (featureObj) {
  32272. var properties = featureObj.properties;
  32273. var geo = featureObj.geometry;
  32274. var geometries = [];
  32275. switch (geo.type) {
  32276. case 'Polygon':
  32277. var coordinates = geo.coordinates; // According to the GeoJSON specification.
  32278. // First must be exterior, and the rest are all interior(holes).
  32279. geometries.push(new GeoJSONPolygonGeometry(coordinates[0], coordinates.slice(1)));
  32280. break;
  32281. case 'MultiPolygon':
  32282. each(geo.coordinates, function (item) {
  32283. if (item[0]) {
  32284. geometries.push(new GeoJSONPolygonGeometry(item[0], item.slice(1)));
  32285. }
  32286. });
  32287. break;
  32288. case 'LineString':
  32289. geometries.push(new GeoJSONLineStringGeometry([geo.coordinates]));
  32290. break;
  32291. case 'MultiLineString':
  32292. geometries.push(new GeoJSONLineStringGeometry(geo.coordinates));
  32293. }
  32294. var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp);
  32295. region.properties = properties;
  32296. return region;
  32297. });
  32298. }
  32299. var number = /*#__PURE__*/Object.freeze({
  32300. __proto__: null,
  32301. linearMap: linearMap,
  32302. round: round,
  32303. asc: asc,
  32304. getPrecision: getPrecision,
  32305. getPrecisionSafe: getPrecisionSafe,
  32306. getPixelPrecision: getPixelPrecision,
  32307. getPercentWithPrecision: getPercentWithPrecision,
  32308. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  32309. remRadian: remRadian,
  32310. isRadianAroundZero: isRadianAroundZero,
  32311. parseDate: parseDate,
  32312. quantity: quantity,
  32313. quantityExponent: quantityExponent,
  32314. nice: nice,
  32315. quantile: quantile,
  32316. reformIntervals: reformIntervals,
  32317. isNumeric: isNumeric,
  32318. numericToNumber: numericToNumber
  32319. });
  32320. var time = /*#__PURE__*/Object.freeze({
  32321. __proto__: null,
  32322. parse: parseDate,
  32323. format: format
  32324. });
  32325. var graphic$1 = /*#__PURE__*/Object.freeze({
  32326. __proto__: null,
  32327. extendShape: extendShape,
  32328. extendPath: extendPath,
  32329. makePath: makePath,
  32330. makeImage: makeImage,
  32331. mergePath: mergePath$1,
  32332. resizePath: resizePath,
  32333. createIcon: createIcon,
  32334. updateProps: updateProps,
  32335. initProps: initProps,
  32336. getTransform: getTransform,
  32337. clipPointsByRect: clipPointsByRect,
  32338. clipRectByRect: clipRectByRect,
  32339. registerShape: registerShape,
  32340. getShapeClass: getShapeClass,
  32341. Group: Group,
  32342. Image: ZRImage,
  32343. Text: ZRText,
  32344. Circle: Circle,
  32345. Ellipse: Ellipse,
  32346. Sector: Sector,
  32347. Ring: Ring,
  32348. Polygon: Polygon,
  32349. Polyline: Polyline,
  32350. Rect: Rect,
  32351. Line: Line,
  32352. BezierCurve: BezierCurve,
  32353. Arc: Arc,
  32354. IncrementalDisplayable: IncrementalDisplayable,
  32355. CompoundPath: CompoundPath,
  32356. LinearGradient: LinearGradient,
  32357. RadialGradient: RadialGradient,
  32358. BoundingRect: BoundingRect
  32359. });
  32360. var format$1 = /*#__PURE__*/Object.freeze({
  32361. __proto__: null,
  32362. addCommas: addCommas,
  32363. toCamelCase: toCamelCase,
  32364. normalizeCssArray: normalizeCssArray$1,
  32365. encodeHTML: encodeHTML,
  32366. formatTpl: formatTpl,
  32367. getTooltipMarker: getTooltipMarker,
  32368. formatTime: formatTime,
  32369. capitalFirst: capitalFirst,
  32370. truncateText: truncateText,
  32371. getTextRect: getTextRect
  32372. });
  32373. var util$1 = /*#__PURE__*/Object.freeze({
  32374. __proto__: null,
  32375. map: map,
  32376. each: each,
  32377. indexOf: indexOf,
  32378. inherits: inherits,
  32379. reduce: reduce,
  32380. filter: filter,
  32381. bind: bind,
  32382. curry: curry,
  32383. isArray: isArray,
  32384. isString: isString,
  32385. isObject: isObject,
  32386. isFunction: isFunction,
  32387. extend: extend,
  32388. defaults: defaults,
  32389. clone: clone,
  32390. merge: merge
  32391. });
  32392. var inner$5 = makeInner();
  32393. function createAxisLabels(axis) {
  32394. // Only ordinal scale support tick interval
  32395. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  32396. }
  32397. /**
  32398. * @param {module:echats/coord/Axis} axis
  32399. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  32400. * @return {Object} {
  32401. * ticks: Array.<number>
  32402. * tickCategoryInterval: number
  32403. * }
  32404. */
  32405. function createAxisTicks(axis, tickModel) {
  32406. // Only ordinal scale support tick interval
  32407. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  32408. ticks: map(axis.scale.getTicks(), function (tick) {
  32409. return tick.value;
  32410. })
  32411. };
  32412. }
  32413. function makeCategoryLabels(axis) {
  32414. var labelModel = axis.getLabelModel();
  32415. var result = makeCategoryLabelsActually(axis, labelModel);
  32416. return !labelModel.get('show') || axis.scale.isBlank() ? {
  32417. labels: [],
  32418. labelCategoryInterval: result.labelCategoryInterval
  32419. } : result;
  32420. }
  32421. function makeCategoryLabelsActually(axis, labelModel) {
  32422. var labelsCache = getListCache(axis, 'labels');
  32423. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  32424. var result = listCacheGet(labelsCache, optionLabelInterval);
  32425. if (result) {
  32426. return result;
  32427. }
  32428. var labels;
  32429. var numericLabelInterval;
  32430. if (isFunction(optionLabelInterval)) {
  32431. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  32432. } else {
  32433. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  32434. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  32435. } // Cache to avoid calling interval function repeatedly.
  32436. return listCacheSet(labelsCache, optionLabelInterval, {
  32437. labels: labels,
  32438. labelCategoryInterval: numericLabelInterval
  32439. });
  32440. }
  32441. function makeCategoryTicks(axis, tickModel) {
  32442. var ticksCache = getListCache(axis, 'ticks');
  32443. var optionTickInterval = getOptionCategoryInterval(tickModel);
  32444. var result = listCacheGet(ticksCache, optionTickInterval);
  32445. if (result) {
  32446. return result;
  32447. }
  32448. var ticks;
  32449. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  32450. // we should not return all ticks.
  32451. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32452. ticks = [];
  32453. }
  32454. if (isFunction(optionTickInterval)) {
  32455. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  32456. } // Always use label interval by default despite label show. Consider this
  32457. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  32458. // labels. `splitLine` and `axisTick` should be consistent in this case.
  32459. else if (optionTickInterval === 'auto') {
  32460. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  32461. tickCategoryInterval = labelsResult.labelCategoryInterval;
  32462. ticks = map(labelsResult.labels, function (labelItem) {
  32463. return labelItem.tickValue;
  32464. });
  32465. } else {
  32466. tickCategoryInterval = optionTickInterval;
  32467. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  32468. } // Cache to avoid calling interval function repeatedly.
  32469. return listCacheSet(ticksCache, optionTickInterval, {
  32470. ticks: ticks,
  32471. tickCategoryInterval: tickCategoryInterval
  32472. });
  32473. }
  32474. function makeRealNumberLabels(axis) {
  32475. var ticks = axis.scale.getTicks();
  32476. var labelFormatter = makeLabelFormatter(axis);
  32477. return {
  32478. labels: map(ticks, function (tick, idx) {
  32479. return {
  32480. level: tick.level,
  32481. formattedLabel: labelFormatter(tick, idx),
  32482. rawLabel: axis.scale.getLabel(tick),
  32483. tickValue: tick.value
  32484. };
  32485. })
  32486. };
  32487. }
  32488. function getListCache(axis, prop) {
  32489. // Because key can be a function, and cache size always is small, we use array cache.
  32490. return inner$5(axis)[prop] || (inner$5(axis)[prop] = []);
  32491. }
  32492. function listCacheGet(cache, key) {
  32493. for (var i = 0; i < cache.length; i++) {
  32494. if (cache[i].key === key) {
  32495. return cache[i].value;
  32496. }
  32497. }
  32498. }
  32499. function listCacheSet(cache, key, value) {
  32500. cache.push({
  32501. key: key,
  32502. value: value
  32503. });
  32504. return value;
  32505. }
  32506. function makeAutoCategoryInterval(axis) {
  32507. var result = inner$5(axis).autoInterval;
  32508. return result != null ? result : inner$5(axis).autoInterval = axis.calculateCategoryInterval();
  32509. }
  32510. /**
  32511. * Calculate interval for category axis ticks and labels.
  32512. * To get precise result, at least one of `getRotate` and `isHorizontal`
  32513. * should be implemented in axis.
  32514. */
  32515. function calculateCategoryInterval(axis) {
  32516. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  32517. var labelFormatter = makeLabelFormatter(axis);
  32518. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  32519. var ordinalScale = axis.scale;
  32520. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  32521. // avoid generating a long array by `getTicks`
  32522. // in large category data case.
  32523. var tickCount = ordinalScale.count();
  32524. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  32525. return 0;
  32526. }
  32527. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  32528. if (tickCount > 40) {
  32529. step = Math.max(1, Math.floor(tickCount / 40));
  32530. }
  32531. var tickValue = ordinalExtent[0];
  32532. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  32533. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  32534. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  32535. var maxW = 0;
  32536. var maxH = 0; // Caution: Performance sensitive for large category data.
  32537. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  32538. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32539. var width = 0;
  32540. var height = 0; // Not precise, do not consider align and vertical align
  32541. // and each distance from axis line yet.
  32542. var rect = getBoundingRect(labelFormatter({
  32543. value: tickValue
  32544. }), params.font, 'center', 'top'); // Magic number
  32545. width = rect.width * 1.3;
  32546. height = rect.height * 1.3; // Min size, void long loop.
  32547. maxW = Math.max(maxW, width, 7);
  32548. maxH = Math.max(maxH, height, 7);
  32549. }
  32550. var dw = maxW / unitW;
  32551. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  32552. isNaN(dw) && (dw = Infinity);
  32553. isNaN(dh) && (dh = Infinity);
  32554. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  32555. var cache = inner$5(axis.model);
  32556. var axisExtent = axis.getExtent();
  32557. var lastAutoInterval = cache.lastAutoInterval;
  32558. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  32559. // otherwise the calculated interval might jitter when the zoom
  32560. // window size is close to the interval-changing size.
  32561. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  32562. // The jitter will cause that sometimes the displayed labels are
  32563. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  32564. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  32565. // point is not the same when zooming in or zooming out.
  32566. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  32567. // be used. Otherwise some hidden labels might not be shown again.
  32568. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  32569. interval = lastAutoInterval;
  32570. } // Only update cache if cache not used, otherwise the
  32571. // changing of interval is too insensitive.
  32572. else {
  32573. cache.lastTickCount = tickCount;
  32574. cache.lastAutoInterval = interval;
  32575. cache.axisExtent0 = axisExtent[0];
  32576. cache.axisExtent1 = axisExtent[1];
  32577. }
  32578. return interval;
  32579. }
  32580. function fetchAutoCategoryIntervalCalculationParams(axis) {
  32581. var labelModel = axis.getLabelModel();
  32582. return {
  32583. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32584. labelRotate: labelModel.get('rotate') || 0,
  32585. font: labelModel.getFont()
  32586. };
  32587. }
  32588. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32589. var labelFormatter = makeLabelFormatter(axis);
  32590. var ordinalScale = axis.scale;
  32591. var ordinalExtent = ordinalScale.getExtent();
  32592. var labelModel = axis.getLabelModel();
  32593. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32594. var step = Math.max((categoryInterval || 0) + 1, 1);
  32595. var startTick = ordinalExtent[0];
  32596. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32597. // while zooming and moving while interval > 0. Otherwise the selection
  32598. // of displayable ticks and symbols probably keep changing.
  32599. // 3 is empirical value.
  32600. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32601. startTick = Math.round(Math.ceil(startTick / step) * step);
  32602. } // (1) Only add min max label here but leave overlap checking
  32603. // to render stage, which also ensure the returned list
  32604. // suitable for splitLine and splitArea rendering.
  32605. // (2) Scales except category always contain min max label so
  32606. // do not need to perform this process.
  32607. var showAllLabel = shouldShowAllLabels(axis);
  32608. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32609. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32610. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32611. addItem(ordinalExtent[0]);
  32612. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32613. var tickValue = startTick;
  32614. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32615. addItem(tickValue);
  32616. }
  32617. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32618. addItem(ordinalExtent[1]);
  32619. }
  32620. function addItem(tickValue) {
  32621. var tickObj = {
  32622. value: tickValue
  32623. };
  32624. result.push(onlyTick ? tickValue : {
  32625. formattedLabel: labelFormatter(tickObj),
  32626. rawLabel: ordinalScale.getLabel(tickObj),
  32627. tickValue: tickValue
  32628. });
  32629. }
  32630. return result;
  32631. }
  32632. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32633. var ordinalScale = axis.scale;
  32634. var labelFormatter = makeLabelFormatter(axis);
  32635. var result = [];
  32636. each(ordinalScale.getTicks(), function (tick) {
  32637. var rawLabel = ordinalScale.getLabel(tick);
  32638. var tickValue = tick.value;
  32639. if (categoryInterval(tick.value, rawLabel)) {
  32640. result.push(onlyTick ? tickValue : {
  32641. formattedLabel: labelFormatter(tick),
  32642. rawLabel: rawLabel,
  32643. tickValue: tickValue
  32644. });
  32645. }
  32646. });
  32647. return result;
  32648. }
  32649. var NORMALIZED_EXTENT = [0, 1];
  32650. /**
  32651. * Base class of Axis.
  32652. */
  32653. var Axis =
  32654. /** @class */
  32655. function () {
  32656. function Axis(dim, scale, extent) {
  32657. this.onBand = false;
  32658. this.inverse = false;
  32659. this.dim = dim;
  32660. this.scale = scale;
  32661. this._extent = extent || [0, 0];
  32662. }
  32663. /**
  32664. * If axis extent contain given coord
  32665. */
  32666. Axis.prototype.contain = function (coord) {
  32667. var extent = this._extent;
  32668. var min = Math.min(extent[0], extent[1]);
  32669. var max = Math.max(extent[0], extent[1]);
  32670. return coord >= min && coord <= max;
  32671. };
  32672. /**
  32673. * If axis extent contain given data
  32674. */
  32675. Axis.prototype.containData = function (data) {
  32676. return this.scale.contain(data);
  32677. };
  32678. /**
  32679. * Get coord extent.
  32680. */
  32681. Axis.prototype.getExtent = function () {
  32682. return this._extent.slice();
  32683. };
  32684. /**
  32685. * Get precision used for formatting
  32686. */
  32687. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32688. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32689. };
  32690. /**
  32691. * Set coord extent
  32692. */
  32693. Axis.prototype.setExtent = function (start, end) {
  32694. var extent = this._extent;
  32695. extent[0] = start;
  32696. extent[1] = end;
  32697. };
  32698. /**
  32699. * Convert data to coord. Data is the rank if it has an ordinal scale
  32700. */
  32701. Axis.prototype.dataToCoord = function (data, clamp) {
  32702. var extent = this._extent;
  32703. var scale = this.scale;
  32704. data = scale.normalize(data);
  32705. if (this.onBand && scale.type === 'ordinal') {
  32706. extent = extent.slice();
  32707. fixExtentWithBands(extent, scale.count());
  32708. }
  32709. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32710. };
  32711. /**
  32712. * Convert coord to data. Data is the rank if it has an ordinal scale
  32713. */
  32714. Axis.prototype.coordToData = function (coord, clamp) {
  32715. var extent = this._extent;
  32716. var scale = this.scale;
  32717. if (this.onBand && scale.type === 'ordinal') {
  32718. extent = extent.slice();
  32719. fixExtentWithBands(extent, scale.count());
  32720. }
  32721. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32722. return this.scale.scale(t);
  32723. };
  32724. /**
  32725. * Convert pixel point to data in axis
  32726. */
  32727. Axis.prototype.pointToData = function (point, clamp) {
  32728. // Should be implemented in derived class if necessary.
  32729. return;
  32730. };
  32731. /**
  32732. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32733. * `axis.getTicksCoords` considers `onBand`, which is used by
  32734. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32735. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32736. * @param opt.clamp If `true`, the first and the last
  32737. * tick must be at the axis end points. Otherwise, clip ticks
  32738. * that outside the axis extent.
  32739. */
  32740. Axis.prototype.getTicksCoords = function (opt) {
  32741. opt = opt || {};
  32742. var tickModel = opt.tickModel || this.getTickModel();
  32743. var result = createAxisTicks(this, tickModel);
  32744. var ticks = result.ticks;
  32745. var ticksCoords = map(ticks, function (tickVal) {
  32746. return {
  32747. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32748. tickValue: tickVal
  32749. };
  32750. }, this);
  32751. var alignWithLabel = tickModel.get('alignWithLabel');
  32752. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32753. return ticksCoords;
  32754. };
  32755. Axis.prototype.getMinorTicksCoords = function () {
  32756. if (this.scale.type === 'ordinal') {
  32757. // Category axis doesn't support minor ticks
  32758. return [];
  32759. }
  32760. var minorTickModel = this.model.getModel('minorTick');
  32761. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32762. if (!(splitNumber > 0 && splitNumber < 100)) {
  32763. splitNumber = 5;
  32764. }
  32765. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32766. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32767. return map(minorTicksGroup, function (minorTick) {
  32768. return {
  32769. coord: this.dataToCoord(minorTick),
  32770. tickValue: minorTick
  32771. };
  32772. }, this);
  32773. }, this);
  32774. return minorTicksCoords;
  32775. };
  32776. Axis.prototype.getViewLabels = function () {
  32777. return createAxisLabels(this).labels;
  32778. };
  32779. Axis.prototype.getLabelModel = function () {
  32780. return this.model.getModel('axisLabel');
  32781. };
  32782. /**
  32783. * Notice here we only get the default tick model. For splitLine
  32784. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32785. * manually when calling `getTicksCoords`.
  32786. * In GL, this method may be overridden to:
  32787. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32788. */
  32789. Axis.prototype.getTickModel = function () {
  32790. return this.model.getModel('axisTick');
  32791. };
  32792. /**
  32793. * Get width of band
  32794. */
  32795. Axis.prototype.getBandWidth = function () {
  32796. var axisExtent = this._extent;
  32797. var dataExtent = this.scale.getExtent();
  32798. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32799. len === 0 && (len = 1);
  32800. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32801. return Math.abs(size) / len;
  32802. };
  32803. /**
  32804. * Only be called in category axis.
  32805. * Can be overridden, consider other axes like in 3D.
  32806. * @return Auto interval for cateogry axis tick and label
  32807. */
  32808. Axis.prototype.calculateCategoryInterval = function () {
  32809. return calculateCategoryInterval(this);
  32810. };
  32811. return Axis;
  32812. }();
  32813. function fixExtentWithBands(extent, nTick) {
  32814. var size = extent[1] - extent[0];
  32815. var len = nTick;
  32816. var margin = size / len / 2;
  32817. extent[0] += margin;
  32818. extent[1] -= margin;
  32819. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32820. // |---1---|---2---|---3---|---4---|.
  32821. // So the displayed ticks and splitLine/splitArea should between
  32822. // each data item, otherwise cause misleading (e.g., split tow bars
  32823. // of a single data item when there are two bar series).
  32824. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32825. // splitLine/spliteArea should layout appropriately corresponding
  32826. // to displayed labels. (So we should not use `getBandWidth` in this
  32827. // case).
  32828. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32829. var ticksLen = ticksCoords.length;
  32830. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32831. return;
  32832. }
  32833. var axisExtent = axis.getExtent();
  32834. var last;
  32835. var diffSize;
  32836. if (ticksLen === 1) {
  32837. ticksCoords[0].coord = axisExtent[0];
  32838. last = ticksCoords[1] = {
  32839. coord: axisExtent[1]
  32840. };
  32841. } else {
  32842. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32843. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32844. each(ticksCoords, function (ticksItem) {
  32845. ticksItem.coord -= shift_1 / 2;
  32846. });
  32847. var dataExtent = axis.scale.getExtent();
  32848. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32849. last = {
  32850. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32851. };
  32852. ticksCoords.push(last);
  32853. }
  32854. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32855. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32856. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32857. }
  32858. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32859. ticksCoords.unshift({
  32860. coord: axisExtent[0]
  32861. });
  32862. }
  32863. if (littleThan(axisExtent[1], last.coord)) {
  32864. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32865. }
  32866. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32867. ticksCoords.push({
  32868. coord: axisExtent[1]
  32869. });
  32870. }
  32871. function littleThan(a, b) {
  32872. // Avoid rounding error cause calculated tick coord different with extent.
  32873. // It may cause an extra unnecessary tick added.
  32874. a = round(a);
  32875. b = round(b);
  32876. return inverse ? a > b : a < b;
  32877. }
  32878. }
  32879. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32880. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32881. // class Bar3DModel extends ComponentModel {}
  32882. // export function install(registers) { registers.registerComponentModel(Bar3DModel); }
  32883. // echarts.use(install);
  32884. function extendComponentModel(proto) {
  32885. var Model = ComponentModel.extend(proto);
  32886. ComponentModel.registerClass(Model);
  32887. return Model;
  32888. }
  32889. function extendComponentView(proto) {
  32890. var View = ComponentView.extend(proto);
  32891. ComponentView.registerClass(View);
  32892. return View;
  32893. }
  32894. function extendSeriesModel(proto) {
  32895. var Model = SeriesModel.extend(proto);
  32896. SeriesModel.registerClass(Model);
  32897. return Model;
  32898. }
  32899. function extendChartView(proto) {
  32900. var View = ChartView.extend(proto);
  32901. ChartView.registerClass(View);
  32902. return View;
  32903. }
  32904. var PI2$6 = Math.PI * 2;
  32905. var CMD$3 = PathProxy.CMD;
  32906. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  32907. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  32908. var width = rect.width;
  32909. var height = rect.height;
  32910. switch (pos) {
  32911. case 'top':
  32912. outPt.set(rect.x + width / 2, rect.y - distance);
  32913. outDir.set(0, -1);
  32914. break;
  32915. case 'bottom':
  32916. outPt.set(rect.x + width / 2, rect.y + height + distance);
  32917. outDir.set(0, 1);
  32918. break;
  32919. case 'left':
  32920. outPt.set(rect.x - distance, rect.y + height / 2);
  32921. outDir.set(-1, 0);
  32922. break;
  32923. case 'right':
  32924. outPt.set(rect.x + width + distance, rect.y + height / 2);
  32925. outDir.set(1, 0);
  32926. break;
  32927. }
  32928. }
  32929. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  32930. x -= cx;
  32931. y -= cy;
  32932. var d = Math.sqrt(x * x + y * y);
  32933. x /= d;
  32934. y /= d; // Intersect point.
  32935. var ox = x * r + cx;
  32936. var oy = y * r + cy;
  32937. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  32938. // Is a circle
  32939. out[0] = ox;
  32940. out[1] = oy;
  32941. return d - r;
  32942. }
  32943. if (anticlockwise) {
  32944. var tmp = startAngle;
  32945. startAngle = normalizeRadian(endAngle);
  32946. endAngle = normalizeRadian(tmp);
  32947. } else {
  32948. startAngle = normalizeRadian(startAngle);
  32949. endAngle = normalizeRadian(endAngle);
  32950. }
  32951. if (startAngle > endAngle) {
  32952. endAngle += PI2$6;
  32953. }
  32954. var angle = Math.atan2(y, x);
  32955. if (angle < 0) {
  32956. angle += PI2$6;
  32957. }
  32958. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  32959. // Project point is on the arc.
  32960. out[0] = ox;
  32961. out[1] = oy;
  32962. return d - r;
  32963. }
  32964. var x1 = r * Math.cos(startAngle) + cx;
  32965. var y1 = r * Math.sin(startAngle) + cy;
  32966. var x2 = r * Math.cos(endAngle) + cx;
  32967. var y2 = r * Math.sin(endAngle) + cy;
  32968. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  32969. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  32970. if (d1 < d2) {
  32971. out[0] = x1;
  32972. out[1] = y1;
  32973. return Math.sqrt(d1);
  32974. } else {
  32975. out[0] = x2;
  32976. out[1] = y2;
  32977. return Math.sqrt(d2);
  32978. }
  32979. }
  32980. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  32981. var dx = x - x1;
  32982. var dy = y - y1;
  32983. var dx1 = x2 - x1;
  32984. var dy1 = y2 - y1;
  32985. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  32986. dx1 /= lineLen;
  32987. dy1 /= lineLen; // dot product
  32988. var projectedLen = dx * dx1 + dy * dy1;
  32989. var t = projectedLen / lineLen;
  32990. if (limitToEnds) {
  32991. t = Math.min(Math.max(t, 0), 1);
  32992. }
  32993. t *= lineLen;
  32994. var ox = out[0] = x1 + t * dx1;
  32995. var oy = out[1] = y1 + t * dy1;
  32996. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  32997. }
  32998. function projectPointToRect(x1, y1, width, height, x, y, out) {
  32999. if (width < 0) {
  33000. x1 = x1 + width;
  33001. width = -width;
  33002. }
  33003. if (height < 0) {
  33004. y1 = y1 + height;
  33005. height = -height;
  33006. }
  33007. var x2 = x1 + width;
  33008. var y2 = y1 + height;
  33009. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  33010. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  33011. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  33012. }
  33013. var tmpPt = [];
  33014. function nearestPointOnRect(pt, rect, out) {
  33015. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  33016. out.set(tmpPt[0], tmpPt[1]);
  33017. return dist;
  33018. }
  33019. /**
  33020. * Calculate min distance corresponding point.
  33021. * This method won't evaluate if point is in the path.
  33022. */
  33023. function nearestPointOnPath(pt, path, out) {
  33024. var xi = 0;
  33025. var yi = 0;
  33026. var x0 = 0;
  33027. var y0 = 0;
  33028. var x1;
  33029. var y1;
  33030. var minDist = Infinity;
  33031. var data = path.data;
  33032. var x = pt.x;
  33033. var y = pt.y;
  33034. for (var i = 0; i < data.length;) {
  33035. var cmd = data[i++];
  33036. if (i === 1) {
  33037. xi = data[i];
  33038. yi = data[i + 1];
  33039. x0 = xi;
  33040. y0 = yi;
  33041. }
  33042. var d = minDist;
  33043. switch (cmd) {
  33044. case CMD$3.M:
  33045. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  33046. // 在 closePath 的时候使用
  33047. x0 = data[i++];
  33048. y0 = data[i++];
  33049. xi = x0;
  33050. yi = y0;
  33051. break;
  33052. case CMD$3.L:
  33053. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  33054. xi = data[i++];
  33055. yi = data[i++];
  33056. break;
  33057. case CMD$3.C:
  33058. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33059. xi = data[i++];
  33060. yi = data[i++];
  33061. break;
  33062. case CMD$3.Q:
  33063. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  33064. xi = data[i++];
  33065. yi = data[i++];
  33066. break;
  33067. case CMD$3.A:
  33068. // TODO Arc 判断的开销比较大
  33069. var cx = data[i++];
  33070. var cy = data[i++];
  33071. var rx = data[i++];
  33072. var ry = data[i++];
  33073. var theta = data[i++];
  33074. var dTheta = data[i++]; // TODO Arc 旋转
  33075. i += 1;
  33076. var anticlockwise = !!(1 - data[i++]);
  33077. x1 = Math.cos(theta) * rx + cx;
  33078. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  33079. if (i <= 1) {
  33080. // 第一个命令起点还未定义
  33081. x0 = x1;
  33082. y0 = y1;
  33083. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  33084. var _x = (x - cx) * ry / rx + cx;
  33085. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  33086. xi = Math.cos(theta + dTheta) * rx + cx;
  33087. yi = Math.sin(theta + dTheta) * ry + cy;
  33088. break;
  33089. case CMD$3.R:
  33090. x0 = xi = data[i++];
  33091. y0 = yi = data[i++];
  33092. var width = data[i++];
  33093. var height = data[i++];
  33094. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  33095. break;
  33096. case CMD$3.Z:
  33097. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  33098. xi = x0;
  33099. yi = y0;
  33100. break;
  33101. }
  33102. if (d < minDist) {
  33103. minDist = d;
  33104. out.set(tmpPt[0], tmpPt[1]);
  33105. }
  33106. }
  33107. return minDist;
  33108. } // Temporal variable for intermediate usage.
  33109. var pt0 = new Point();
  33110. var pt1 = new Point();
  33111. var pt2 = new Point();
  33112. var dir = new Point();
  33113. var dir2 = new Point();
  33114. /**
  33115. * Calculate a proper guide line based on the label position and graphic element definition
  33116. * @param label
  33117. * @param labelRect
  33118. * @param target
  33119. * @param targetRect
  33120. */
  33121. function updateLabelLinePoints(target, labelLineModel) {
  33122. if (!target) {
  33123. return;
  33124. }
  33125. var labelLine = target.getTextGuideLine();
  33126. var label = target.getTextContent(); // Needs to create text guide in each charts.
  33127. if (!(label && labelLine)) {
  33128. return;
  33129. }
  33130. var labelGuideConfig = target.textGuideLineConfig || {};
  33131. var points = [[0, 0], [0, 0], [0, 0]];
  33132. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  33133. var labelRect = label.getBoundingRect().clone();
  33134. labelRect.applyTransform(label.getComputedTransform());
  33135. var minDist = Infinity;
  33136. var anchorPoint = labelGuideConfig.anchor;
  33137. var targetTransform = target.getComputedTransform();
  33138. var targetInversedTransform = targetTransform && invert([], targetTransform);
  33139. var len = labelLineModel.get('length2') || 0;
  33140. if (anchorPoint) {
  33141. pt2.copy(anchorPoint);
  33142. }
  33143. for (var i = 0; i < searchSpace.length; i++) {
  33144. var candidate = searchSpace[i];
  33145. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  33146. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  33147. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  33148. var boundingRect = target.getBoundingRect();
  33149. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  33150. if (dist < minDist) {
  33151. minDist = dist; // Transform back to global space.
  33152. pt1.transform(targetTransform);
  33153. pt2.transform(targetTransform);
  33154. pt2.toArray(points[0]);
  33155. pt1.toArray(points[1]);
  33156. pt0.toArray(points[2]);
  33157. }
  33158. }
  33159. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  33160. labelLine.setShape({
  33161. points: points
  33162. });
  33163. } // Temporal variable for the limitTurnAngle function
  33164. var tmpArr = [];
  33165. var tmpProjPoint = new Point();
  33166. /**
  33167. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  33168. * @param linePoints
  33169. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  33170. */
  33171. function limitTurnAngle(linePoints, minTurnAngle) {
  33172. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  33173. return;
  33174. }
  33175. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  33176. // /pt1----pt2 (label)
  33177. // /
  33178. // pt0/
  33179. pt0.fromArray(linePoints[0]);
  33180. pt1.fromArray(linePoints[1]);
  33181. pt2.fromArray(linePoints[2]);
  33182. Point.sub(dir, pt0, pt1);
  33183. Point.sub(dir2, pt2, pt1);
  33184. var len1 = dir.len();
  33185. var len2 = dir2.len();
  33186. if (len1 < 1e-3 || len2 < 1e-3) {
  33187. return;
  33188. }
  33189. dir.scale(1 / len1);
  33190. dir2.scale(1 / len2);
  33191. var angleCos = dir.dot(dir2);
  33192. var minTurnAngleCos = Math.cos(minTurnAngle);
  33193. if (minTurnAngleCos < angleCos) {
  33194. // Smaller than minTurnAngle
  33195. // Calculate project point of pt0 on pt1-pt2
  33196. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33197. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  33198. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33199. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33200. if (isNaN(t)) {
  33201. return;
  33202. }
  33203. if (t < 0) {
  33204. Point.copy(tmpProjPoint, pt1);
  33205. } else if (t > 1) {
  33206. Point.copy(tmpProjPoint, pt2);
  33207. }
  33208. tmpProjPoint.toArray(linePoints[1]);
  33209. }
  33210. }
  33211. /**
  33212. * Limit the angle of line and the surface
  33213. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  33214. */
  33215. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  33216. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  33217. return;
  33218. }
  33219. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  33220. pt0.fromArray(linePoints[0]);
  33221. pt1.fromArray(linePoints[1]);
  33222. pt2.fromArray(linePoints[2]);
  33223. Point.sub(dir, pt1, pt0);
  33224. Point.sub(dir2, pt2, pt1);
  33225. var len1 = dir.len();
  33226. var len2 = dir2.len();
  33227. if (len1 < 1e-3 || len2 < 1e-3) {
  33228. return;
  33229. }
  33230. dir.scale(1 / len1);
  33231. dir2.scale(1 / len2);
  33232. var angleCos = dir.dot(surfaceNormal);
  33233. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  33234. if (angleCos < maxSurfaceAngleCos) {
  33235. // Calculate project point of pt0 on pt1-pt2
  33236. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  33237. tmpProjPoint.fromArray(tmpArr);
  33238. var HALF_PI = Math.PI / 2;
  33239. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  33240. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  33241. if (newAngle >= HALF_PI) {
  33242. // parallel
  33243. Point.copy(tmpProjPoint, pt2);
  33244. } else {
  33245. // Calculate new projected length with limited minTurnAngle and get the new connect point
  33246. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  33247. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  33248. if (isNaN(t)) {
  33249. return;
  33250. }
  33251. if (t < 0) {
  33252. Point.copy(tmpProjPoint, pt1);
  33253. } else if (t > 1) {
  33254. Point.copy(tmpProjPoint, pt2);
  33255. }
  33256. }
  33257. tmpProjPoint.toArray(linePoints[1]);
  33258. }
  33259. }
  33260. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  33261. var isNormal = stateName === 'normal';
  33262. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  33263. stateObj.ignore = ignore; // Set smooth
  33264. var smooth = stateModel.get('smooth');
  33265. if (smooth && smooth === true) {
  33266. smooth = 0.3;
  33267. }
  33268. stateObj.shape = stateObj.shape || {};
  33269. if (smooth > 0) {
  33270. stateObj.shape.smooth = smooth;
  33271. }
  33272. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  33273. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  33274. }
  33275. function buildLabelLinePath(path, shape) {
  33276. var smooth = shape.smooth;
  33277. var points = shape.points;
  33278. if (!points) {
  33279. return;
  33280. }
  33281. path.moveTo(points[0][0], points[0][1]);
  33282. if (smooth > 0 && points.length >= 3) {
  33283. var len1 = dist(points[0], points[1]);
  33284. var len2 = dist(points[1], points[2]);
  33285. if (!len1 || !len2) {
  33286. path.lineTo(points[1][0], points[1][1]);
  33287. path.lineTo(points[2][0], points[2][1]);
  33288. return;
  33289. }
  33290. var moveLen = Math.min(len1, len2) * smooth;
  33291. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  33292. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  33293. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  33294. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  33295. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  33296. } else {
  33297. for (var i = 1; i < points.length; i++) {
  33298. path.lineTo(points[i][0], points[i][1]);
  33299. }
  33300. }
  33301. }
  33302. /**
  33303. * Create a label line if necessary and set it's style.
  33304. */
  33305. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  33306. var labelLine = targetEl.getTextGuideLine();
  33307. var label = targetEl.getTextContent();
  33308. if (!label) {
  33309. // Not show label line if there is no label.
  33310. if (labelLine) {
  33311. targetEl.removeTextGuideLine();
  33312. }
  33313. return;
  33314. }
  33315. var normalModel = statesModels.normal;
  33316. var showNormal = normalModel.get('show');
  33317. var labelIgnoreNormal = label.ignore;
  33318. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  33319. var stateName = DISPLAY_STATES[i];
  33320. var stateModel = statesModels[stateName];
  33321. var isNormal = stateName === 'normal';
  33322. if (stateModel) {
  33323. var stateShow = stateModel.get('show');
  33324. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  33325. if (isLabelIgnored // Not show when label is not shown in this state.
  33326. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  33327. ) {
  33328. var stateObj = isNormal ? labelLine : labelLine && labelLine.states[stateName];
  33329. if (stateObj) {
  33330. stateObj.ignore = true;
  33331. }
  33332. continue;
  33333. } // Create labelLine if not exists
  33334. if (!labelLine) {
  33335. labelLine = new Polyline();
  33336. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  33337. // NOTE: NORMAL should always been the first!
  33338. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  33339. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  33340. } // Use same state proxy.
  33341. if (targetEl.stateProxy) {
  33342. labelLine.stateProxy = targetEl.stateProxy;
  33343. }
  33344. }
  33345. setLabelLineState(labelLine, false, stateName, stateModel);
  33346. }
  33347. }
  33348. if (labelLine) {
  33349. defaults(labelLine.style, defaultStyle); // Not fill.
  33350. labelLine.style.fill = null;
  33351. var showAbove = normalModel.get('showAbove');
  33352. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  33353. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  33354. labelLine.buildPath = buildLabelLinePath;
  33355. }
  33356. }
  33357. function getLabelLineStatesModels(itemModel, labelLineName) {
  33358. labelLineName = labelLineName || 'labelLine';
  33359. var statesModels = {
  33360. normal: itemModel.getModel(labelLineName)
  33361. };
  33362. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  33363. var stateName = SPECIAL_STATES[i];
  33364. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  33365. }
  33366. return statesModels;
  33367. }
  33368. function prepareLayoutList(input) {
  33369. var list = [];
  33370. for (var i = 0; i < input.length; i++) {
  33371. var rawItem = input[i];
  33372. if (rawItem.defaultAttr.ignore) {
  33373. continue;
  33374. }
  33375. var label = rawItem.label;
  33376. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  33377. var localRect = label.getBoundingRect();
  33378. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  33379. var minMargin = label.style.margin || 0;
  33380. var globalRect = localRect.clone();
  33381. globalRect.applyTransform(transform);
  33382. globalRect.x -= minMargin / 2;
  33383. globalRect.y -= minMargin / 2;
  33384. globalRect.width += minMargin;
  33385. globalRect.height += minMargin;
  33386. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  33387. list.push({
  33388. label: label,
  33389. labelLine: rawItem.labelLine,
  33390. rect: globalRect,
  33391. localRect: localRect,
  33392. obb: obb,
  33393. priority: rawItem.priority,
  33394. defaultAttr: rawItem.defaultAttr,
  33395. layoutOption: rawItem.computedLayoutOption,
  33396. axisAligned: isAxisAligned,
  33397. transform: transform
  33398. });
  33399. }
  33400. return list;
  33401. }
  33402. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  33403. var len = list.length;
  33404. if (len < 2) {
  33405. return;
  33406. }
  33407. list.sort(function (a, b) {
  33408. return a.rect[xyDim] - b.rect[xyDim];
  33409. });
  33410. var lastPos = 0;
  33411. var delta;
  33412. var adjusted = false;
  33413. var totalShifts = 0;
  33414. for (var i = 0; i < len; i++) {
  33415. var item = list[i];
  33416. var rect = item.rect;
  33417. delta = rect[xyDim] - lastPos;
  33418. if (delta < 0) {
  33419. // shiftForward(i, len, -delta);
  33420. rect[xyDim] -= delta;
  33421. item.label[xyDim] -= delta;
  33422. adjusted = true;
  33423. }
  33424. var shift = Math.max(-delta, 0);
  33425. totalShifts += shift;
  33426. lastPos = rect[xyDim] + rect[sizeDim];
  33427. }
  33428. if (totalShifts > 0 && balanceShift) {
  33429. // Shift back to make the distribution more equally.
  33430. shiftList(-totalShifts / len, 0, len);
  33431. } // TODO bleedMargin?
  33432. var first = list[0];
  33433. var last = list[len - 1];
  33434. var minGap;
  33435. var maxGap;
  33436. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  33437. minGap < 0 && squeezeGaps(-minGap, 0.8);
  33438. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  33439. updateMinMaxGap();
  33440. takeBoundsGap(minGap, maxGap, 1);
  33441. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  33442. updateMinMaxGap();
  33443. if (minGap < 0) {
  33444. squeezeWhenBailout(-minGap);
  33445. }
  33446. if (maxGap < 0) {
  33447. squeezeWhenBailout(maxGap);
  33448. }
  33449. function updateMinMaxGap() {
  33450. minGap = first.rect[xyDim] - minBound;
  33451. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  33452. }
  33453. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  33454. if (gapThisBound < 0) {
  33455. // Move from other gap if can.
  33456. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  33457. if (moveFromMaxGap > 0) {
  33458. shiftList(moveFromMaxGap * moveDir, 0, len);
  33459. var remained = moveFromMaxGap + gapThisBound;
  33460. if (remained < 0) {
  33461. squeezeGaps(-remained * moveDir, 1);
  33462. }
  33463. } else {
  33464. squeezeGaps(-gapThisBound * moveDir, 1);
  33465. }
  33466. }
  33467. }
  33468. function shiftList(delta, start, end) {
  33469. if (delta !== 0) {
  33470. adjusted = true;
  33471. }
  33472. for (var i = start; i < end; i++) {
  33473. var item = list[i];
  33474. var rect = item.rect;
  33475. rect[xyDim] += delta;
  33476. item.label[xyDim] += delta;
  33477. }
  33478. } // Squeeze gaps if the labels exceed margin.
  33479. function squeezeGaps(delta, maxSqeezePercent) {
  33480. var gaps = [];
  33481. var totalGaps = 0;
  33482. for (var i = 1; i < len; i++) {
  33483. var prevItemRect = list[i - 1].rect;
  33484. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  33485. gaps.push(gap);
  33486. totalGaps += gap;
  33487. }
  33488. if (!totalGaps) {
  33489. return;
  33490. }
  33491. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  33492. if (delta > 0) {
  33493. for (var i = 0; i < len - 1; i++) {
  33494. // Distribute the shift delta to all gaps.
  33495. var movement = gaps[i] * squeezePercent; // Forward
  33496. shiftList(movement, 0, i + 1);
  33497. }
  33498. } else {
  33499. // Backward
  33500. for (var i = len - 1; i > 0; i--) {
  33501. // Distribute the shift delta to all gaps.
  33502. var movement = gaps[i - 1] * squeezePercent;
  33503. shiftList(-movement, i, len);
  33504. }
  33505. }
  33506. }
  33507. /**
  33508. * Squeeze to allow overlap if there is no more space available.
  33509. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  33510. */
  33511. function squeezeWhenBailout(delta) {
  33512. var dir = delta < 0 ? -1 : 1;
  33513. delta = Math.abs(delta);
  33514. var moveForEachLabel = Math.ceil(delta / (len - 1));
  33515. for (var i = 0; i < len - 1; i++) {
  33516. if (dir > 0) {
  33517. // Forward
  33518. shiftList(moveForEachLabel, 0, i + 1);
  33519. } else {
  33520. // Backward
  33521. shiftList(-moveForEachLabel, len - i - 1, len);
  33522. }
  33523. delta -= moveForEachLabel;
  33524. if (delta <= 0) {
  33525. return;
  33526. }
  33527. }
  33528. }
  33529. return adjusted;
  33530. }
  33531. /**
  33532. * Adjust labels on x direction to avoid overlap.
  33533. */
  33534. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  33535. // TODO: Not sure if should enable it.
  33536. // Pros: The angle of lines will distribute more equally
  33537. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  33538. balanceShift) {
  33539. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  33540. }
  33541. /**
  33542. * Adjust labels on y direction to avoid overlap.
  33543. */
  33544. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  33545. balanceShift) {
  33546. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  33547. }
  33548. function hideOverlap(labelList) {
  33549. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  33550. labelList.sort(function (a, b) {
  33551. return b.priority - a.priority;
  33552. });
  33553. var globalRect = new BoundingRect(0, 0, 0, 0);
  33554. function hideEl(el) {
  33555. if (!el.ignore) {
  33556. // Show on emphasis.
  33557. var emphasisState = el.ensureState('emphasis');
  33558. if (emphasisState.ignore == null) {
  33559. emphasisState.ignore = false;
  33560. }
  33561. }
  33562. el.ignore = true;
  33563. }
  33564. for (var i = 0; i < labelList.length; i++) {
  33565. var labelItem = labelList[i];
  33566. var isAxisAligned = labelItem.axisAligned;
  33567. var localRect = labelItem.localRect;
  33568. var transform = labelItem.transform;
  33569. var label = labelItem.label;
  33570. var labelLine = labelItem.labelLine;
  33571. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  33572. globalRect.width -= 0.1;
  33573. globalRect.height -= 0.1;
  33574. globalRect.x += 0.05;
  33575. globalRect.y += 0.05;
  33576. var obb = labelItem.obb;
  33577. var overlapped = false;
  33578. for (var j = 0; j < displayedLabels.length; j++) {
  33579. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  33580. if (!globalRect.intersect(existsTextCfg.rect)) {
  33581. continue;
  33582. }
  33583. if (isAxisAligned && existsTextCfg.axisAligned) {
  33584. // Is overlapped
  33585. overlapped = true;
  33586. break;
  33587. }
  33588. if (!existsTextCfg.obb) {
  33589. // If self is not axis aligned. But other is.
  33590. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  33591. }
  33592. if (!obb) {
  33593. // If self is axis aligned. But other is not.
  33594. obb = new OrientedBoundingRect(localRect, transform);
  33595. }
  33596. if (obb.intersect(existsTextCfg.obb)) {
  33597. overlapped = true;
  33598. break;
  33599. }
  33600. } // TODO Callback to determine if this overlap should be handled?
  33601. if (overlapped) {
  33602. hideEl(label);
  33603. labelLine && hideEl(labelLine);
  33604. } else {
  33605. label.attr('ignore', labelItem.defaultAttr.ignore);
  33606. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  33607. displayedLabels.push(labelItem);
  33608. }
  33609. }
  33610. }
  33611. function cloneArr(points) {
  33612. if (points) {
  33613. var newPoints = [];
  33614. for (var i = 0; i < points.length; i++) {
  33615. newPoints.push(points[i].slice());
  33616. }
  33617. return newPoints;
  33618. }
  33619. }
  33620. function prepareLayoutCallbackParams(labelItem, hostEl) {
  33621. var label = labelItem.label;
  33622. var labelLine = hostEl && hostEl.getTextGuideLine();
  33623. return {
  33624. dataIndex: labelItem.dataIndex,
  33625. dataType: labelItem.dataType,
  33626. seriesIndex: labelItem.seriesModel.seriesIndex,
  33627. text: labelItem.label.style.text,
  33628. rect: labelItem.hostRect,
  33629. labelRect: labelItem.rect,
  33630. // x: labelAttr.x,
  33631. // y: labelAttr.y,
  33632. align: label.style.align,
  33633. verticalAlign: label.style.verticalAlign,
  33634. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  33635. };
  33636. }
  33637. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  33638. var dummyTransformable = new Transformable();
  33639. var labelLayoutInnerStore = makeInner();
  33640. var labelLineAnimationStore = makeInner();
  33641. function extendWithKeys(target, source, keys) {
  33642. for (var i = 0; i < keys.length; i++) {
  33643. var key = keys[i];
  33644. if (source[key] != null) {
  33645. target[key] = source[key];
  33646. }
  33647. }
  33648. }
  33649. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  33650. var LabelManager =
  33651. /** @class */
  33652. function () {
  33653. function LabelManager() {
  33654. this._labelList = [];
  33655. this._chartViewList = [];
  33656. }
  33657. LabelManager.prototype.clearLabels = function () {
  33658. this._labelList = [];
  33659. this._chartViewList = [];
  33660. };
  33661. /**
  33662. * Add label to manager
  33663. */
  33664. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  33665. var labelStyle = label.style;
  33666. var hostEl = label.__hostTarget;
  33667. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  33668. var labelTransform = label.getComputedTransform();
  33669. var labelRect = label.getBoundingRect().plain();
  33670. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  33671. if (labelTransform) {
  33672. dummyTransformable.setLocalTransform(labelTransform);
  33673. } else {
  33674. // Identity transform.
  33675. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  33676. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  33677. }
  33678. dummyTransformable.rotation = normalizeRadian(dummyTransformable.rotation);
  33679. var host = label.__hostTarget;
  33680. var hostRect;
  33681. if (host) {
  33682. hostRect = host.getBoundingRect().plain();
  33683. var transform = host.getComputedTransform();
  33684. BoundingRect.applyTransform(hostRect, hostRect, transform);
  33685. }
  33686. var labelGuide = hostRect && host.getTextGuideLine();
  33687. this._labelList.push({
  33688. label: label,
  33689. labelLine: labelGuide,
  33690. seriesModel: seriesModel,
  33691. dataIndex: dataIndex,
  33692. dataType: dataType,
  33693. layoutOption: layoutOption,
  33694. computedLayoutOption: null,
  33695. rect: labelRect,
  33696. hostRect: hostRect,
  33697. // Label with lower priority will be hidden when overlapped
  33698. // Use rect size as default priority
  33699. priority: hostRect ? hostRect.width * hostRect.height : 0,
  33700. // Save default label attributes.
  33701. // For restore if developers want get back to default value in callback.
  33702. defaultAttr: {
  33703. ignore: label.ignore,
  33704. labelGuideIgnore: labelGuide && labelGuide.ignore,
  33705. x: dummyTransformable.x,
  33706. y: dummyTransformable.y,
  33707. scaleX: dummyTransformable.scaleX,
  33708. scaleY: dummyTransformable.scaleY,
  33709. rotation: dummyTransformable.rotation,
  33710. style: {
  33711. x: labelStyle.x,
  33712. y: labelStyle.y,
  33713. align: labelStyle.align,
  33714. verticalAlign: labelStyle.verticalAlign,
  33715. width: labelStyle.width,
  33716. height: labelStyle.height,
  33717. fontSize: labelStyle.fontSize
  33718. },
  33719. cursor: label.cursor,
  33720. attachedPos: textConfig.position,
  33721. attachedRot: textConfig.rotation
  33722. }
  33723. });
  33724. };
  33725. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  33726. var _this = this;
  33727. this._chartViewList.push(chartView);
  33728. var seriesModel = chartView.__model;
  33729. var layoutOption = seriesModel.get('labelLayout');
  33730. /**
  33731. * Ignore layouting if it's not specified anything.
  33732. */
  33733. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  33734. return;
  33735. }
  33736. chartView.group.traverse(function (child) {
  33737. if (child.ignore) {
  33738. return true; // Stop traverse descendants.
  33739. } // Only support label being hosted on graphic elements.
  33740. var textEl = child.getTextContent();
  33741. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  33742. if (textEl && !textEl.disableLabelLayout) {
  33743. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  33744. }
  33745. });
  33746. };
  33747. LabelManager.prototype.updateLayoutConfig = function (api) {
  33748. var width = api.getWidth();
  33749. var height = api.getHeight();
  33750. function createDragHandler(el, labelLineModel) {
  33751. return function () {
  33752. updateLabelLinePoints(el, labelLineModel);
  33753. };
  33754. }
  33755. for (var i = 0; i < this._labelList.length; i++) {
  33756. var labelItem = this._labelList[i];
  33757. var label = labelItem.label;
  33758. var hostEl = label.__hostTarget;
  33759. var defaultLabelAttr = labelItem.defaultAttr;
  33760. var layoutOption = void 0; // TODO A global layout option?
  33761. if (isFunction(labelItem.layoutOption)) {
  33762. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  33763. } else {
  33764. layoutOption = labelItem.layoutOption;
  33765. }
  33766. layoutOption = layoutOption || {};
  33767. labelItem.computedLayoutOption = layoutOption;
  33768. var degreeToRadian = Math.PI / 180; // TODO hostEl should always exists.
  33769. // Or label should not have parent because the x, y is all in global space.
  33770. if (hostEl) {
  33771. hostEl.setTextConfig({
  33772. // Force to set local false.
  33773. local: false,
  33774. // Ignore position and rotation config on the host el if x or y is changed.
  33775. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  33776. // Ignore rotation config on the host el if rotation is changed.
  33777. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  33778. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  33779. });
  33780. }
  33781. var needsUpdateLabelLine = false;
  33782. if (layoutOption.x != null) {
  33783. // TODO width of chart view.
  33784. label.x = parsePercent$1(layoutOption.x, width);
  33785. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  33786. needsUpdateLabelLine = true;
  33787. } else {
  33788. label.x = defaultLabelAttr.x;
  33789. label.setStyle('x', defaultLabelAttr.style.x);
  33790. }
  33791. if (layoutOption.y != null) {
  33792. // TODO height of chart view.
  33793. label.y = parsePercent$1(layoutOption.y, height);
  33794. label.setStyle('y', 0); // Ignore movement in style.
  33795. needsUpdateLabelLine = true;
  33796. } else {
  33797. label.y = defaultLabelAttr.y;
  33798. label.setStyle('y', defaultLabelAttr.style.y);
  33799. }
  33800. if (layoutOption.labelLinePoints) {
  33801. var guideLine = hostEl.getTextGuideLine();
  33802. if (guideLine) {
  33803. guideLine.setShape({
  33804. points: layoutOption.labelLinePoints
  33805. }); // Not update
  33806. needsUpdateLabelLine = false;
  33807. }
  33808. }
  33809. var labelLayoutStore = labelLayoutInnerStore(label);
  33810. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  33811. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  33812. label.scaleX = defaultLabelAttr.scaleX;
  33813. label.scaleY = defaultLabelAttr.scaleY;
  33814. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  33815. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  33816. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  33817. }
  33818. if (layoutOption.draggable) {
  33819. label.draggable = true;
  33820. label.cursor = 'move';
  33821. if (hostEl) {
  33822. var hostModel = labelItem.seriesModel;
  33823. if (labelItem.dataIndex != null) {
  33824. var data = labelItem.seriesModel.getData(labelItem.dataType);
  33825. hostModel = data.getItemModel(labelItem.dataIndex);
  33826. }
  33827. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  33828. }
  33829. } else {
  33830. // TODO Other drag functions?
  33831. label.off('drag');
  33832. label.cursor = defaultLabelAttr.cursor;
  33833. }
  33834. }
  33835. };
  33836. LabelManager.prototype.layout = function (api) {
  33837. var width = api.getWidth();
  33838. var height = api.getHeight();
  33839. var labelList = prepareLayoutList(this._labelList);
  33840. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  33841. return item.layoutOption.moveOverlap === 'shiftX';
  33842. });
  33843. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  33844. return item.layoutOption.moveOverlap === 'shiftY';
  33845. });
  33846. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  33847. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  33848. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  33849. return item.layoutOption.hideOverlap;
  33850. });
  33851. hideOverlap(labelsNeedsHideOverlap);
  33852. };
  33853. /**
  33854. * Process all labels. Not only labels with layoutOption.
  33855. */
  33856. LabelManager.prototype.processLabelsOverall = function () {
  33857. var _this = this;
  33858. each(this._chartViewList, function (chartView) {
  33859. var seriesModel = chartView.__model;
  33860. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  33861. var animationEnabled = seriesModel.isAnimationEnabled();
  33862. chartView.group.traverse(function (child) {
  33863. if (child.ignore && !child.forceLabelAnimation) {
  33864. return true; // Stop traverse descendants.
  33865. }
  33866. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  33867. var label = child.getTextContent();
  33868. if (!needsUpdateLabelLine && label) {
  33869. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  33870. }
  33871. if (needsUpdateLabelLine) {
  33872. _this._updateLabelLine(child, seriesModel);
  33873. }
  33874. if (animationEnabled) {
  33875. _this._animateLabels(child, seriesModel);
  33876. }
  33877. });
  33878. });
  33879. };
  33880. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  33881. // Only support label being hosted on graphic elements.
  33882. var textEl = el.getTextContent(); // Update label line style.
  33883. var ecData = getECData(el);
  33884. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  33885. if (textEl && dataIndex != null) {
  33886. var data = seriesModel.getData(ecData.dataType);
  33887. var itemModel = data.getItemModel(dataIndex);
  33888. var defaultStyle = {};
  33889. var visualStyle = data.getItemVisual(dataIndex, 'style');
  33890. if (visualStyle) {
  33891. var visualType = data.getVisual('drawType'); // Default to be same with main color
  33892. defaultStyle.stroke = visualStyle[visualType];
  33893. }
  33894. var labelLineModel = itemModel.getModel('labelLine');
  33895. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  33896. updateLabelLinePoints(el, labelLineModel);
  33897. }
  33898. };
  33899. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  33900. var textEl = el.getTextContent();
  33901. var guideLine = el.getTextGuideLine(); // Animate
  33902. if (textEl // `forceLabelAnimation` has the highest priority
  33903. && (el.forceLabelAnimation || !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el))) {
  33904. var layoutStore = labelLayoutInnerStore(textEl);
  33905. var oldLayout = layoutStore.oldLayout;
  33906. var ecData = getECData(el);
  33907. var dataIndex = ecData.dataIndex;
  33908. var newProps = {
  33909. x: textEl.x,
  33910. y: textEl.y,
  33911. rotation: textEl.rotation
  33912. };
  33913. var data = seriesModel.getData(ecData.dataType);
  33914. if (!oldLayout) {
  33915. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  33916. if (!labelInner(textEl).valueAnimation) {
  33917. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  33918. textEl.style.opacity = 0;
  33919. initProps(textEl, {
  33920. style: {
  33921. opacity: oldOpacity
  33922. }
  33923. }, seriesModel, dataIndex);
  33924. }
  33925. } else {
  33926. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  33927. var prevStates = el.prevStates;
  33928. if (prevStates) {
  33929. if (indexOf(prevStates, 'select') >= 0) {
  33930. textEl.attr(layoutStore.oldLayoutSelect);
  33931. }
  33932. if (indexOf(prevStates, 'emphasis') >= 0) {
  33933. textEl.attr(layoutStore.oldLayoutEmphasis);
  33934. }
  33935. }
  33936. updateProps(textEl, newProps, seriesModel, dataIndex);
  33937. }
  33938. layoutStore.oldLayout = newProps;
  33939. if (textEl.states.select) {
  33940. var layoutSelect = layoutStore.oldLayoutSelect = {};
  33941. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  33942. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  33943. }
  33944. if (textEl.states.emphasis) {
  33945. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  33946. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  33947. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  33948. }
  33949. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  33950. }
  33951. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  33952. var layoutStore = labelLineAnimationStore(guideLine);
  33953. var oldLayout = layoutStore.oldLayout;
  33954. var newLayout = {
  33955. points: guideLine.shape.points
  33956. };
  33957. if (!oldLayout) {
  33958. guideLine.setShape(newLayout);
  33959. guideLine.style.strokePercent = 0;
  33960. initProps(guideLine, {
  33961. style: {
  33962. strokePercent: 1
  33963. }
  33964. }, seriesModel);
  33965. } else {
  33966. guideLine.attr({
  33967. shape: oldLayout
  33968. });
  33969. updateProps(guideLine, {
  33970. shape: newLayout
  33971. }, seriesModel);
  33972. }
  33973. layoutStore.oldLayout = newLayout;
  33974. }
  33975. };
  33976. return LabelManager;
  33977. }();
  33978. var getLabelManager = makeInner();
  33979. function installLabelLayout(registers) {
  33980. registers.registerUpdateLifecycle('series:beforeupdate', function (ecModel, api, params) {
  33981. // TODO api provide an namespace that can save stuff per instance
  33982. var labelManager = getLabelManager(api).labelManager;
  33983. if (!labelManager) {
  33984. labelManager = getLabelManager(api).labelManager = new LabelManager();
  33985. }
  33986. labelManager.clearLabels();
  33987. });
  33988. registers.registerUpdateLifecycle('series:layoutlabels', function (ecModel, api, params) {
  33989. var labelManager = getLabelManager(api).labelManager;
  33990. params.updatedSeries.forEach(function (series) {
  33991. labelManager.addLabelsOfSeries(api.getViewOfSeriesModel(series));
  33992. });
  33993. labelManager.updateLayoutConfig(api);
  33994. labelManager.layout(api);
  33995. labelManager.processLabelsOverall();
  33996. });
  33997. }
  33998. var mathSin$4 = Math.sin;
  33999. var mathCos$4 = Math.cos;
  34000. var PI$4 = Math.PI;
  34001. var PI2$7 = Math.PI * 2;
  34002. var degree = 180 / PI$4;
  34003. var SVGPathRebuilder = (function () {
  34004. function SVGPathRebuilder() {
  34005. }
  34006. SVGPathRebuilder.prototype.reset = function (precision) {
  34007. this._start = true;
  34008. this._d = [];
  34009. this._str = '';
  34010. this._p = Math.pow(10, precision || 4);
  34011. };
  34012. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  34013. this._add('M', x, y);
  34014. };
  34015. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  34016. this._add('L', x, y);
  34017. };
  34018. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  34019. this._add('C', x, y, x2, y2, x3, y3);
  34020. };
  34021. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  34022. this._add('Q', x, y, x2, y2);
  34023. };
  34024. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  34025. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  34026. };
  34027. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  34028. var dTheta = endAngle - startAngle;
  34029. var clockwise = !anticlockwise;
  34030. var dThetaPositive = Math.abs(dTheta);
  34031. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  34032. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  34033. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  34034. var large = false;
  34035. if (isCircle) {
  34036. large = true;
  34037. }
  34038. else if (isAroundZero$1(dThetaPositive)) {
  34039. large = false;
  34040. }
  34041. else {
  34042. large = (unifiedTheta >= PI$4) === !!clockwise;
  34043. }
  34044. var x0 = cx + rx * mathCos$4(startAngle);
  34045. var y0 = cy + ry * mathSin$4(startAngle);
  34046. if (this._start) {
  34047. this._add('M', x0, y0);
  34048. }
  34049. var xRot = Math.round(psi * degree);
  34050. if (isCircle) {
  34051. var p = 1 / this._p;
  34052. var dTheta_1 = (clockwise ? 1 : -1) * (PI2$7 - p);
  34053. this._add('A', rx, ry, xRot, 1, +clockwise, cx + rx * mathCos$4(startAngle + dTheta_1), cy + ry * mathSin$4(startAngle + dTheta_1));
  34054. if (p > 1e-2) {
  34055. this._add('A', rx, ry, xRot, 0, +clockwise, x0, y0);
  34056. }
  34057. }
  34058. else {
  34059. var x = cx + rx * mathCos$4(endAngle);
  34060. var y = cy + ry * mathSin$4(endAngle);
  34061. this._add('A', rx, ry, xRot, +large, +clockwise, x, y);
  34062. }
  34063. };
  34064. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  34065. this._add('M', x, y);
  34066. this._add('l', w, 0);
  34067. this._add('l', 0, h);
  34068. this._add('l', -w, 0);
  34069. this._add('Z');
  34070. };
  34071. SVGPathRebuilder.prototype.closePath = function () {
  34072. if (this._d.length > 0) {
  34073. this._add('Z');
  34074. }
  34075. };
  34076. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  34077. var vals = [];
  34078. var p = this._p;
  34079. for (var i = 1; i < arguments.length; i++) {
  34080. var val = arguments[i];
  34081. if (isNaN(val)) {
  34082. this._invalid = true;
  34083. return;
  34084. }
  34085. vals.push(Math.round(val * p) / p);
  34086. }
  34087. this._d.push(cmd + vals.join(' '));
  34088. this._start = cmd === 'Z';
  34089. };
  34090. SVGPathRebuilder.prototype.generateStr = function () {
  34091. this._str = this._invalid ? '' : this._d.join('');
  34092. this._d = [];
  34093. };
  34094. SVGPathRebuilder.prototype.getStr = function () {
  34095. return this._str;
  34096. };
  34097. return SVGPathRebuilder;
  34098. }());
  34099. var NONE = 'none';
  34100. var mathRound$1 = Math.round;
  34101. function pathHasFill(style) {
  34102. var fill = style.fill;
  34103. return fill != null && fill !== NONE;
  34104. }
  34105. function pathHasStroke(style) {
  34106. var stroke = style.stroke;
  34107. return stroke != null && stroke !== NONE;
  34108. }
  34109. var strokeProps = ['lineCap', 'miterLimit', 'lineJoin'];
  34110. var svgStrokeProps = map(strokeProps, function (prop) { return "stroke-" + prop.toLowerCase(); });
  34111. function mapStyleToAttrs(updateAttr, style, el, forceUpdate) {
  34112. var opacity = style.opacity == null ? 1 : style.opacity;
  34113. if (el instanceof ZRImage) {
  34114. updateAttr('opacity', opacity);
  34115. return;
  34116. }
  34117. if (pathHasFill(style)) {
  34118. var fill = normalizeColor(style.fill);
  34119. updateAttr('fill', fill.color);
  34120. var fillOpacity = style.fillOpacity != null
  34121. ? style.fillOpacity * fill.opacity * opacity
  34122. : fill.opacity * opacity;
  34123. if (forceUpdate || fillOpacity < 1) {
  34124. updateAttr('fill-opacity', fillOpacity);
  34125. }
  34126. }
  34127. else {
  34128. updateAttr('fill', NONE);
  34129. }
  34130. if (pathHasStroke(style)) {
  34131. var stroke = normalizeColor(style.stroke);
  34132. updateAttr('stroke', stroke.color);
  34133. var strokeScale = style.strokeNoScale
  34134. ? el.getLineScale()
  34135. : 1;
  34136. var strokeWidth = (strokeScale ? (style.lineWidth || 0) / strokeScale : 0);
  34137. var strokeOpacity = style.strokeOpacity != null
  34138. ? style.strokeOpacity * stroke.opacity * opacity
  34139. : stroke.opacity * opacity;
  34140. var strokeFirst = style.strokeFirst;
  34141. if (forceUpdate || strokeWidth !== 1) {
  34142. updateAttr('stroke-width', strokeWidth);
  34143. }
  34144. if (forceUpdate || strokeFirst) {
  34145. updateAttr('paint-order', strokeFirst ? 'stroke' : 'fill');
  34146. }
  34147. if (forceUpdate || strokeOpacity < 1) {
  34148. updateAttr('stroke-opacity', strokeOpacity);
  34149. }
  34150. if (style.lineDash) {
  34151. var _a = getLineDash(el), lineDash = _a[0], lineDashOffset = _a[1];
  34152. if (lineDash) {
  34153. lineDashOffset = mathRound$1(lineDashOffset || 0);
  34154. updateAttr('stroke-dasharray', lineDash.join(','));
  34155. if (lineDashOffset || forceUpdate) {
  34156. updateAttr('stroke-dashoffset', lineDashOffset);
  34157. }
  34158. }
  34159. }
  34160. else if (forceUpdate) {
  34161. updateAttr('stroke-dasharray', NONE);
  34162. }
  34163. for (var i = 0; i < strokeProps.length; i++) {
  34164. var propName = strokeProps[i];
  34165. if (forceUpdate || style[propName] !== DEFAULT_PATH_STYLE[propName]) {
  34166. var val = style[propName] || DEFAULT_PATH_STYLE[propName];
  34167. val && updateAttr(svgStrokeProps[i], val);
  34168. }
  34169. }
  34170. }
  34171. else if (forceUpdate) {
  34172. updateAttr('stroke', NONE);
  34173. }
  34174. }
  34175. var SVGNS = 'http://www.w3.org/2000/svg';
  34176. var XLINKNS = 'http://www.w3.org/1999/xlink';
  34177. var XMLNS = 'http://www.w3.org/2000/xmlns/';
  34178. var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace';
  34179. function createElement(name) {
  34180. return document.createElementNS(SVGNS, name);
  34181. }
  34182. function createVNode(tag, key, attrs, children, text) {
  34183. return {
  34184. tag: tag,
  34185. attrs: attrs || {},
  34186. children: children,
  34187. text: text,
  34188. key: key
  34189. };
  34190. }
  34191. function createElementOpen(name, attrs) {
  34192. var attrsStr = [];
  34193. if (attrs) {
  34194. for (var key in attrs) {
  34195. var val = attrs[key];
  34196. var part = key;
  34197. if (val === false) {
  34198. continue;
  34199. }
  34200. else if (val !== true && val != null) {
  34201. part += "=\"" + val + "\"";
  34202. }
  34203. attrsStr.push(part);
  34204. }
  34205. }
  34206. return "<" + name + " " + attrsStr.join(' ') + ">";
  34207. }
  34208. function createElementClose(name) {
  34209. return "</" + name + ">";
  34210. }
  34211. function vNodeToString(el, opts) {
  34212. opts = opts || {};
  34213. var S = opts.newline ? '\n' : '';
  34214. function convertElToString(el) {
  34215. var children = el.children, tag = el.tag, attrs = el.attrs, text = el.text;
  34216. return createElementOpen(tag, attrs)
  34217. + (tag !== 'style' ? encodeHTML(text) : text || '')
  34218. + (children ? "" + S + map(children, function (child) { return convertElToString(child); }).join(S) + S : '')
  34219. + createElementClose(tag);
  34220. }
  34221. return convertElToString(el);
  34222. }
  34223. function getCssString(selectorNodes, animationNodes, opts) {
  34224. opts = opts || {};
  34225. var S = opts.newline ? '\n' : '';
  34226. var bracketBegin = " {" + S;
  34227. var bracketEnd = S + "}";
  34228. var selectors = map(keys(selectorNodes), function (className) {
  34229. return className + bracketBegin + map(keys(selectorNodes[className]), function (attrName) {
  34230. return attrName + ":" + selectorNodes[className][attrName] + ";";
  34231. }).join(S) + bracketEnd;
  34232. }).join(S);
  34233. var animations = map(keys(animationNodes), function (animationName) {
  34234. return "@keyframes " + animationName + bracketBegin + map(keys(animationNodes[animationName]), function (percent) {
  34235. return percent + bracketBegin + map(keys(animationNodes[animationName][percent]), function (attrName) {
  34236. var val = animationNodes[animationName][percent][attrName];
  34237. if (attrName === 'd') {
  34238. val = "path(\"" + val + "\")";
  34239. }
  34240. return attrName + ":" + val + ";";
  34241. }).join(S) + bracketEnd;
  34242. }).join(S) + bracketEnd;
  34243. }).join(S);
  34244. if (!selectors && !animations) {
  34245. return '';
  34246. }
  34247. return ['<![CDATA[', selectors, animations, ']]>'].join(S);
  34248. }
  34249. function createBrushScope(zrId) {
  34250. return {
  34251. zrId: zrId,
  34252. shadowCache: {},
  34253. patternCache: {},
  34254. gradientCache: {},
  34255. clipPathCache: {},
  34256. defs: {},
  34257. cssNodes: {},
  34258. cssAnims: {},
  34259. cssClassIdx: 0,
  34260. cssAnimIdx: 0,
  34261. shadowIdx: 0,
  34262. gradientIdx: 0,
  34263. patternIdx: 0,
  34264. clipPathIdx: 0
  34265. };
  34266. }
  34267. function createSVGVNode(width, height, children, useViewBox) {
  34268. return createVNode('svg', 'root', {
  34269. 'width': width,
  34270. 'height': height,
  34271. 'xmlns': SVGNS,
  34272. 'xmlns:xlink': XLINKNS,
  34273. 'version': '1.1',
  34274. 'baseProfile': 'full',
  34275. 'viewBox': useViewBox ? "0 0 " + width + " " + height : false
  34276. }, children);
  34277. }
  34278. var EASING_MAP = {
  34279. cubicIn: '0.32,0,0.67,0',
  34280. cubicOut: '0.33,1,0.68,1',
  34281. cubicInOut: '0.65,0,0.35,1',
  34282. quadraticIn: '0.11,0,0.5,0',
  34283. quadraticOut: '0.5,1,0.89,1',
  34284. quadraticInOut: '0.45,0,0.55,1',
  34285. quarticIn: '0.5,0,0.75,0',
  34286. quarticOut: '0.25,1,0.5,1',
  34287. quarticInOut: '0.76,0,0.24,1',
  34288. quinticIn: '0.64,0,0.78,0',
  34289. quinticOut: '0.22,1,0.36,1',
  34290. quinticInOut: '0.83,0,0.17,1',
  34291. sinusoidalIn: '0.12,0,0.39,0',
  34292. sinusoidalOut: '0.61,1,0.88,1',
  34293. sinusoidalInOut: '0.37,0,0.63,1',
  34294. exponentialIn: '0.7,0,0.84,0',
  34295. exponentialOut: '0.16,1,0.3,1',
  34296. exponentialInOut: '0.87,0,0.13,1',
  34297. circularIn: '0.55,0,1,0.45',
  34298. circularOut: '0,0.55,0.45,1',
  34299. circularInOut: '0.85,0,0.15,1'
  34300. };
  34301. var transformOriginKey = 'transform-origin';
  34302. function buildPathString(el, kfShape, path) {
  34303. var shape = extend({}, el.shape);
  34304. extend(shape, kfShape);
  34305. el.buildPath(path, shape);
  34306. var svgPathBuilder = new SVGPathRebuilder();
  34307. svgPathBuilder.reset(getPathPrecision(el));
  34308. path.rebuildPath(svgPathBuilder, 1);
  34309. svgPathBuilder.generateStr();
  34310. return svgPathBuilder.getStr();
  34311. }
  34312. function setTransformOrigin(target, transform) {
  34313. var originX = transform.originX, originY = transform.originY;
  34314. if (originX || originY) {
  34315. target[transformOriginKey] = originX + "px " + originY + "px";
  34316. }
  34317. }
  34318. var ANIMATE_STYLE_MAP = {
  34319. fill: 'fill',
  34320. opacity: 'opacity',
  34321. lineWidth: 'stroke-width',
  34322. lineDashOffset: 'stroke-dashoffset'
  34323. };
  34324. function addAnimation(cssAnim, scope) {
  34325. var animationName = scope.zrId + '-ani-' + scope.cssAnimIdx++;
  34326. scope.cssAnims[animationName] = cssAnim;
  34327. return animationName;
  34328. }
  34329. function createCompoundPathCSSAnimation(el, attrs, scope) {
  34330. var paths = el.shape.paths;
  34331. var composedAnim = {};
  34332. var cssAnimationCfg;
  34333. var cssAnimationName;
  34334. each(paths, function (path) {
  34335. var subScope = createBrushScope(scope.zrId);
  34336. subScope.animation = true;
  34337. createCSSAnimation(path, {}, subScope, true);
  34338. var cssAnims = subScope.cssAnims;
  34339. var cssNodes = subScope.cssNodes;
  34340. var animNames = keys(cssAnims);
  34341. var len = animNames.length;
  34342. if (!len) {
  34343. return;
  34344. }
  34345. cssAnimationName = animNames[len - 1];
  34346. var lastAnim = cssAnims[cssAnimationName];
  34347. for (var percent in lastAnim) {
  34348. var kf = lastAnim[percent];
  34349. composedAnim[percent] = composedAnim[percent] || { d: '' };
  34350. composedAnim[percent].d += kf.d || '';
  34351. }
  34352. for (var className in cssNodes) {
  34353. var val = cssNodes[className].animation;
  34354. if (val.indexOf(cssAnimationName) >= 0) {
  34355. cssAnimationCfg = val;
  34356. }
  34357. }
  34358. });
  34359. if (!cssAnimationCfg) {
  34360. return;
  34361. }
  34362. attrs.d = false;
  34363. var animationName = addAnimation(composedAnim, scope);
  34364. return cssAnimationCfg.replace(cssAnimationName, animationName);
  34365. }
  34366. function getEasingFunc(easing) {
  34367. return isString(easing)
  34368. ? EASING_MAP[easing]
  34369. ? "cubic-bezier(" + EASING_MAP[easing] + ")"
  34370. : createCubicEasingFunc(easing) ? easing : ''
  34371. : '';
  34372. }
  34373. function createCSSAnimation(el, attrs, scope, onlyShape) {
  34374. var animators = el.animators;
  34375. var len = animators.length;
  34376. var cssAnimations = [];
  34377. if (el instanceof CompoundPath) {
  34378. var animationCfg = createCompoundPathCSSAnimation(el, attrs, scope);
  34379. if (animationCfg) {
  34380. cssAnimations.push(animationCfg);
  34381. }
  34382. else if (!len) {
  34383. return;
  34384. }
  34385. }
  34386. else if (!len) {
  34387. return;
  34388. }
  34389. var groupAnimators = {};
  34390. for (var i = 0; i < len; i++) {
  34391. var animator = animators[i];
  34392. var cfgArr = [animator.getMaxTime() / 1000 + 's'];
  34393. var easing = getEasingFunc(animator.getClip().easing);
  34394. var delay = animator.getDelay();
  34395. if (easing) {
  34396. cfgArr.push(easing);
  34397. }
  34398. else {
  34399. cfgArr.push('linear');
  34400. }
  34401. if (delay) {
  34402. cfgArr.push(delay / 1000 + 's');
  34403. }
  34404. if (animator.getLoop()) {
  34405. cfgArr.push('infinite');
  34406. }
  34407. var cfg = cfgArr.join(' ');
  34408. groupAnimators[cfg] = groupAnimators[cfg] || [cfg, []];
  34409. groupAnimators[cfg][1].push(animator);
  34410. }
  34411. function createSingleCSSAnimation(groupAnimator) {
  34412. var animators = groupAnimator[1];
  34413. var len = animators.length;
  34414. var transformKfs = {};
  34415. var shapeKfs = {};
  34416. var finalKfs = {};
  34417. var animationTimingFunctionAttrName = 'animation-timing-function';
  34418. function saveAnimatorTrackToCssKfs(animator, cssKfs, toCssAttrName) {
  34419. var tracks = animator.getTracks();
  34420. var maxTime = animator.getMaxTime();
  34421. for (var k = 0; k < tracks.length; k++) {
  34422. var track = tracks[k];
  34423. if (track.needsAnimate()) {
  34424. var kfs = track.keyframes;
  34425. var attrName = track.propName;
  34426. toCssAttrName && (attrName = toCssAttrName(attrName));
  34427. if (attrName) {
  34428. for (var i = 0; i < kfs.length; i++) {
  34429. var kf = kfs[i];
  34430. var percent = Math.round(kf.time / maxTime * 100) + '%';
  34431. var kfEasing = getEasingFunc(kf.easing);
  34432. var rawValue = kf.rawValue;
  34433. if (isString(rawValue) || isNumber(rawValue)) {
  34434. cssKfs[percent] = cssKfs[percent] || {};
  34435. cssKfs[percent][attrName] = kf.rawValue;
  34436. if (kfEasing) {
  34437. cssKfs[percent][animationTimingFunctionAttrName] = kfEasing;
  34438. }
  34439. }
  34440. }
  34441. }
  34442. }
  34443. }
  34444. }
  34445. for (var i = 0; i < len; i++) {
  34446. var animator = animators[i];
  34447. var targetProp = animator.targetName;
  34448. if (!targetProp) {
  34449. !onlyShape && saveAnimatorTrackToCssKfs(animator, transformKfs);
  34450. }
  34451. else if (targetProp === 'shape') {
  34452. saveAnimatorTrackToCssKfs(animator, shapeKfs);
  34453. }
  34454. }
  34455. for (var percent in transformKfs) {
  34456. var transform = {};
  34457. copyTransform(transform, el);
  34458. extend(transform, transformKfs[percent]);
  34459. var str = getSRTTransformString(transform);
  34460. var timingFunction = transformKfs[percent][animationTimingFunctionAttrName];
  34461. finalKfs[percent] = str ? {
  34462. transform: str
  34463. } : {};
  34464. setTransformOrigin(finalKfs[percent], transform);
  34465. if (timingFunction) {
  34466. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34467. }
  34468. }
  34469. var path;
  34470. var canAnimateShape = true;
  34471. for (var percent in shapeKfs) {
  34472. finalKfs[percent] = finalKfs[percent] || {};
  34473. var isFirst = !path;
  34474. var timingFunction = shapeKfs[percent][animationTimingFunctionAttrName];
  34475. if (isFirst) {
  34476. path = new PathProxy();
  34477. }
  34478. var len_1 = path.len();
  34479. path.reset();
  34480. finalKfs[percent].d = buildPathString(el, shapeKfs[percent], path);
  34481. var newLen = path.len();
  34482. if (!isFirst && len_1 !== newLen) {
  34483. canAnimateShape = false;
  34484. break;
  34485. }
  34486. if (timingFunction) {
  34487. finalKfs[percent][animationTimingFunctionAttrName] = timingFunction;
  34488. }
  34489. }
  34490. if (!canAnimateShape) {
  34491. for (var percent in finalKfs) {
  34492. delete finalKfs[percent].d;
  34493. }
  34494. }
  34495. if (!onlyShape) {
  34496. for (var i = 0; i < len; i++) {
  34497. var animator = animators[i];
  34498. var targetProp = animator.targetName;
  34499. if (targetProp === 'style') {
  34500. saveAnimatorTrackToCssKfs(animator, finalKfs, function (propName) { return ANIMATE_STYLE_MAP[propName]; });
  34501. }
  34502. }
  34503. }
  34504. var percents = keys(finalKfs);
  34505. var allTransformOriginSame = true;
  34506. var transformOrigin;
  34507. for (var i = 1; i < percents.length; i++) {
  34508. var p0 = percents[i - 1];
  34509. var p1 = percents[i];
  34510. if (finalKfs[p0][transformOriginKey] !== finalKfs[p1][transformOriginKey]) {
  34511. allTransformOriginSame = false;
  34512. break;
  34513. }
  34514. transformOrigin = finalKfs[p0][transformOriginKey];
  34515. }
  34516. if (allTransformOriginSame && transformOrigin) {
  34517. for (var percent in finalKfs) {
  34518. if (finalKfs[percent][transformOriginKey]) {
  34519. delete finalKfs[percent][transformOriginKey];
  34520. }
  34521. }
  34522. attrs[transformOriginKey] = transformOrigin;
  34523. }
  34524. if (filter(percents, function (percent) { return keys(finalKfs[percent]).length > 0; }).length) {
  34525. var animationName = addAnimation(finalKfs, scope);
  34526. return animationName + " " + groupAnimator[0] + " both";
  34527. }
  34528. }
  34529. for (var key in groupAnimators) {
  34530. var animationCfg = createSingleCSSAnimation(groupAnimators[key]);
  34531. if (animationCfg) {
  34532. cssAnimations.push(animationCfg);
  34533. }
  34534. }
  34535. if (cssAnimations.length) {
  34536. var className = scope.zrId + '-cls-' + scope.cssClassIdx++;
  34537. scope.cssNodes['.' + className] = {
  34538. animation: cssAnimations.join(',')
  34539. };
  34540. attrs["class"] = className;
  34541. }
  34542. }
  34543. var round$2 = Math.round;
  34544. function isImageLike$1(val) {
  34545. return val && isString(val.src);
  34546. }
  34547. function isCanvasLike(val) {
  34548. return val && isFunction(val.toDataURL);
  34549. }
  34550. function setStyleAttrs(attrs, style, el, scope) {
  34551. mapStyleToAttrs(function (key, val) {
  34552. var isFillStroke = key === 'fill' || key === 'stroke';
  34553. if (isFillStroke && isGradient(val)) {
  34554. setGradient(style, attrs, key, scope);
  34555. }
  34556. else if (isFillStroke && isPattern(val)) {
  34557. setPattern(el, attrs, key, scope);
  34558. }
  34559. else {
  34560. attrs[key] = val;
  34561. }
  34562. }, style, el, false);
  34563. setShadow(el, attrs, scope);
  34564. }
  34565. function noRotateScale(m) {
  34566. return isAroundZero$1(m[0] - 1)
  34567. && isAroundZero$1(m[1])
  34568. && isAroundZero$1(m[2])
  34569. && isAroundZero$1(m[3] - 1);
  34570. }
  34571. function noTranslate(m) {
  34572. return isAroundZero$1(m[4]) && isAroundZero$1(m[5]);
  34573. }
  34574. function setTransform(attrs, m, compress) {
  34575. if (m && !(noTranslate(m) && noRotateScale(m))) {
  34576. var mul = compress ? 10 : 1e4;
  34577. attrs.transform = noRotateScale(m)
  34578. ? "translate(" + round$2(m[4] * mul) / mul + " " + round$2(m[5] * mul) / mul + ")" : getMatrixStr(m);
  34579. }
  34580. }
  34581. function convertPolyShape(shape, attrs, mul) {
  34582. var points = shape.points;
  34583. var strArr = [];
  34584. for (var i = 0; i < points.length; i++) {
  34585. strArr.push(round$2(points[i][0] * mul) / mul);
  34586. strArr.push(round$2(points[i][1] * mul) / mul);
  34587. }
  34588. attrs.points = strArr.join(' ');
  34589. }
  34590. function validatePolyShape(shape) {
  34591. return !shape.smooth;
  34592. }
  34593. function createAttrsConvert(desc) {
  34594. var normalizedDesc = map(desc, function (item) {
  34595. return (typeof item === 'string' ? [item, item] : item);
  34596. });
  34597. return function (shape, attrs, mul) {
  34598. for (var i = 0; i < normalizedDesc.length; i++) {
  34599. var item = normalizedDesc[i];
  34600. var val = shape[item[0]];
  34601. if (val != null) {
  34602. attrs[item[1]] = round$2(val * mul) / mul;
  34603. }
  34604. }
  34605. };
  34606. }
  34607. var builtinShapesDef = {
  34608. circle: [createAttrsConvert(['cx', 'cy', 'r'])],
  34609. polyline: [convertPolyShape, validatePolyShape],
  34610. polygon: [convertPolyShape, validatePolyShape]
  34611. };
  34612. function hasShapeAnimation(el) {
  34613. var animators = el.animators;
  34614. for (var i = 0; i < animators.length; i++) {
  34615. if (animators[i].targetName === 'shape') {
  34616. return true;
  34617. }
  34618. }
  34619. return false;
  34620. }
  34621. function brushSVGPath(el, scope) {
  34622. var style = el.style;
  34623. var shape = el.shape;
  34624. var builtinShpDef = builtinShapesDef[el.type];
  34625. var attrs = {};
  34626. var needsAnimate = scope.animation;
  34627. var svgElType = 'path';
  34628. var strokePercent = el.style.strokePercent;
  34629. var precision = (scope.compress && getPathPrecision(el)) || 4;
  34630. if (builtinShpDef
  34631. && !scope.willUpdate
  34632. && !(builtinShpDef[1] && !builtinShpDef[1](shape))
  34633. && !(needsAnimate && hasShapeAnimation(el))
  34634. && !(strokePercent < 1)) {
  34635. svgElType = el.type;
  34636. var mul = Math.pow(10, precision);
  34637. builtinShpDef[0](shape, attrs, mul);
  34638. }
  34639. else {
  34640. var needBuildPath = !el.path || el.shapeChanged();
  34641. if (!el.path) {
  34642. el.createPathProxy();
  34643. }
  34644. var path = el.path;
  34645. if (needBuildPath) {
  34646. path.beginPath();
  34647. el.buildPath(path, el.shape);
  34648. el.pathUpdated();
  34649. }
  34650. var pathVersion = path.getVersion();
  34651. var elExt = el;
  34652. var svgPathBuilder = elExt.__svgPathBuilder;
  34653. if (elExt.__svgPathVersion !== pathVersion
  34654. || !svgPathBuilder
  34655. || strokePercent !== elExt.__svgPathStrokePercent) {
  34656. if (!svgPathBuilder) {
  34657. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  34658. }
  34659. svgPathBuilder.reset(precision);
  34660. path.rebuildPath(svgPathBuilder, strokePercent);
  34661. svgPathBuilder.generateStr();
  34662. elExt.__svgPathVersion = pathVersion;
  34663. elExt.__svgPathStrokePercent = strokePercent;
  34664. }
  34665. attrs.d = svgPathBuilder.getStr();
  34666. }
  34667. setTransform(attrs, el.transform);
  34668. setStyleAttrs(attrs, style, el, scope);
  34669. scope.animation && createCSSAnimation(el, attrs, scope);
  34670. return createVNode(svgElType, el.id + '', attrs);
  34671. }
  34672. function brushSVGImage(el, scope) {
  34673. var style = el.style;
  34674. var image = style.image;
  34675. if (image && !isString(image)) {
  34676. if (isImageLike$1(image)) {
  34677. image = image.src;
  34678. }
  34679. else if (isCanvasLike(image)) {
  34680. image = image.toDataURL();
  34681. }
  34682. }
  34683. if (!image) {
  34684. return;
  34685. }
  34686. var x = style.x || 0;
  34687. var y = style.y || 0;
  34688. var dw = style.width;
  34689. var dh = style.height;
  34690. var attrs = {
  34691. href: image,
  34692. width: dw,
  34693. height: dh
  34694. };
  34695. if (x) {
  34696. attrs.x = x;
  34697. }
  34698. if (y) {
  34699. attrs.y = y;
  34700. }
  34701. setTransform(attrs, el.transform);
  34702. setStyleAttrs(attrs, style, el, scope);
  34703. scope.animation && createCSSAnimation(el, attrs, scope);
  34704. return createVNode('image', el.id + '', attrs);
  34705. }
  34706. function brushSVGTSpan(el, scope) {
  34707. var style = el.style;
  34708. var text = style.text;
  34709. text != null && (text += '');
  34710. if (!text || isNaN(style.x) || isNaN(style.y)) {
  34711. return;
  34712. }
  34713. var font = style.font || DEFAULT_FONT;
  34714. var x = style.x || 0;
  34715. var y = adjustTextY(style.y || 0, getLineHeight(font), style.textBaseline);
  34716. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  34717. || style.textAlign;
  34718. var attrs = {
  34719. 'dominant-baseline': 'central',
  34720. 'text-anchor': textAlign
  34721. };
  34722. if (hasSeparateFont(style)) {
  34723. var separatedFontStr = '';
  34724. var fontStyle = style.fontStyle;
  34725. var fontSize = parseFontSize(style.fontSize);
  34726. if (!parseFloat(fontSize)) {
  34727. return;
  34728. }
  34729. var fontFamily = style.fontFamily || DEFAULT_FONT_FAMILY;
  34730. var fontWeight = style.fontWeight;
  34731. separatedFontStr += "font-size:" + fontSize + ";font-family:" + fontFamily + ";";
  34732. if (fontStyle && fontStyle !== 'normal') {
  34733. separatedFontStr += "font-style:" + fontStyle + ";";
  34734. }
  34735. if (fontWeight && fontWeight !== 'normal') {
  34736. separatedFontStr += "font-weight:" + fontWeight + ";";
  34737. }
  34738. attrs.style = separatedFontStr;
  34739. }
  34740. else {
  34741. attrs.style = "font: " + font;
  34742. }
  34743. if (text.match(/\s/)) {
  34744. attrs['xml:space'] = 'preserve';
  34745. }
  34746. if (x) {
  34747. attrs.x = x;
  34748. }
  34749. if (y) {
  34750. attrs.y = y;
  34751. }
  34752. setTransform(attrs, el.transform);
  34753. setStyleAttrs(attrs, style, el, scope);
  34754. scope.animation && createCSSAnimation(el, attrs, scope);
  34755. return createVNode('text', el.id + '', attrs, undefined, text);
  34756. }
  34757. function brush$1(el, scope) {
  34758. if (el instanceof Path) {
  34759. return brushSVGPath(el, scope);
  34760. }
  34761. else if (el instanceof ZRImage) {
  34762. return brushSVGImage(el, scope);
  34763. }
  34764. else if (el instanceof TSpan) {
  34765. return brushSVGTSpan(el, scope);
  34766. }
  34767. }
  34768. function setShadow(el, attrs, scope) {
  34769. var style = el.style;
  34770. if (hasShadow(style)) {
  34771. var shadowKey = getShadowKey(el);
  34772. var shadowCache = scope.shadowCache;
  34773. var shadowId = shadowCache[shadowKey];
  34774. if (!shadowId) {
  34775. var globalScale = el.getGlobalScale();
  34776. var scaleX = globalScale[0];
  34777. var scaleY = globalScale[1];
  34778. if (!scaleX || !scaleY) {
  34779. return;
  34780. }
  34781. var offsetX = style.shadowOffsetX || 0;
  34782. var offsetY = style.shadowOffsetY || 0;
  34783. var blur_1 = style.shadowBlur;
  34784. var _a = normalizeColor(style.shadowColor), opacity = _a.opacity, color = _a.color;
  34785. var stdDx = blur_1 / 2 / scaleX;
  34786. var stdDy = blur_1 / 2 / scaleY;
  34787. var stdDeviation = stdDx + ' ' + stdDy;
  34788. shadowId = scope.zrId + '-s' + scope.shadowIdx++;
  34789. scope.defs[shadowId] = createVNode('filter', shadowId, {
  34790. 'id': shadowId,
  34791. 'x': '-100%',
  34792. 'y': '-100%',
  34793. 'width': '300%',
  34794. 'height': '300%'
  34795. }, [
  34796. createVNode('feDropShadow', '', {
  34797. 'dx': offsetX / scaleX,
  34798. 'dy': offsetY / scaleY,
  34799. 'stdDeviation': stdDeviation,
  34800. 'flood-color': color,
  34801. 'flood-opacity': opacity
  34802. })
  34803. ]);
  34804. shadowCache[shadowKey] = shadowId;
  34805. }
  34806. attrs.filter = getIdURL(shadowId);
  34807. }
  34808. }
  34809. function setGradient(style, attrs, target, scope) {
  34810. var val = style[target];
  34811. var gradientTag;
  34812. var gradientAttrs = {
  34813. 'gradientUnits': val.global
  34814. ? 'userSpaceOnUse'
  34815. : 'objectBoundingBox'
  34816. };
  34817. if (isLinearGradient(val)) {
  34818. gradientTag = 'linearGradient';
  34819. gradientAttrs.x1 = val.x;
  34820. gradientAttrs.y1 = val.y;
  34821. gradientAttrs.x2 = val.x2;
  34822. gradientAttrs.y2 = val.y2;
  34823. }
  34824. else if (isRadialGradient(val)) {
  34825. gradientTag = 'radialGradient';
  34826. gradientAttrs.cx = retrieve2(val.x, 0.5);
  34827. gradientAttrs.cy = retrieve2(val.y, 0.5);
  34828. gradientAttrs.r = retrieve2(val.r, 0.5);
  34829. }
  34830. else {
  34831. if ("development" !== 'production') {
  34832. logError('Illegal gradient type.');
  34833. }
  34834. return;
  34835. }
  34836. var colors = val.colorStops;
  34837. var colorStops = [];
  34838. for (var i = 0, len = colors.length; i < len; ++i) {
  34839. var offset = round4(colors[i].offset) * 100 + '%';
  34840. var stopColor = colors[i].color;
  34841. var _a = normalizeColor(stopColor), color = _a.color, opacity = _a.opacity;
  34842. var stopsAttrs = {
  34843. 'offset': offset
  34844. };
  34845. stopsAttrs['stop-color'] = color;
  34846. if (opacity < 1) {
  34847. stopsAttrs['stop-opacity'] = opacity;
  34848. }
  34849. colorStops.push(createVNode('stop', i + '', stopsAttrs));
  34850. }
  34851. var gradientVNode = createVNode(gradientTag, '', gradientAttrs, colorStops);
  34852. var gradientKey = vNodeToString(gradientVNode);
  34853. var gradientCache = scope.gradientCache;
  34854. var gradientId = gradientCache[gradientKey];
  34855. if (!gradientId) {
  34856. gradientId = scope.zrId + '-g' + scope.gradientIdx++;
  34857. gradientCache[gradientKey] = gradientId;
  34858. gradientAttrs.id = gradientId;
  34859. scope.defs[gradientId] = createVNode(gradientTag, gradientId, gradientAttrs, colorStops);
  34860. }
  34861. attrs[target] = getIdURL(gradientId);
  34862. }
  34863. function setPattern(el, attrs, target, scope) {
  34864. var val = el.style[target];
  34865. var boundingRect = el.getBoundingRect();
  34866. var patternAttrs = {};
  34867. var repeat = val.repeat;
  34868. var noRepeat = repeat === 'no-repeat';
  34869. var repeatX = repeat === 'repeat-x';
  34870. var repeatY = repeat === 'repeat-y';
  34871. var child;
  34872. if (isImagePattern(val)) {
  34873. var imageWidth_1 = val.imageWidth;
  34874. var imageHeight_1 = val.imageHeight;
  34875. var imageSrc = void 0;
  34876. var patternImage = val.image;
  34877. if (isString(patternImage)) {
  34878. imageSrc = patternImage;
  34879. }
  34880. else if (isImageLike$1(patternImage)) {
  34881. imageSrc = patternImage.src;
  34882. }
  34883. else if (isCanvasLike(patternImage)) {
  34884. imageSrc = patternImage.toDataURL();
  34885. }
  34886. if (typeof Image === 'undefined') {
  34887. var errMsg = 'Image width/height must been given explictly in svg-ssr renderer.';
  34888. assert(imageWidth_1, errMsg);
  34889. assert(imageHeight_1, errMsg);
  34890. }
  34891. else if (imageWidth_1 == null || imageHeight_1 == null) {
  34892. var setSizeToVNode_1 = function (vNode, img) {
  34893. if (vNode) {
  34894. var svgEl = vNode.elm;
  34895. var width = imageWidth_1 || img.width;
  34896. var height = imageHeight_1 || img.height;
  34897. if (vNode.tag === 'pattern') {
  34898. if (repeatX) {
  34899. height = 1;
  34900. width /= boundingRect.width;
  34901. }
  34902. else if (repeatY) {
  34903. width = 1;
  34904. height /= boundingRect.height;
  34905. }
  34906. }
  34907. vNode.attrs.width = width;
  34908. vNode.attrs.height = height;
  34909. if (svgEl) {
  34910. svgEl.setAttribute('width', width);
  34911. svgEl.setAttribute('height', height);
  34912. }
  34913. }
  34914. };
  34915. var createdImage = createOrUpdateImage(imageSrc, null, el, function (img) {
  34916. noRepeat || setSizeToVNode_1(patternVNode, img);
  34917. setSizeToVNode_1(child, img);
  34918. });
  34919. if (createdImage && createdImage.width && createdImage.height) {
  34920. imageWidth_1 = imageWidth_1 || createdImage.width;
  34921. imageHeight_1 = imageHeight_1 || createdImage.height;
  34922. }
  34923. }
  34924. child = createVNode('image', 'img', {
  34925. href: imageSrc,
  34926. width: imageWidth_1,
  34927. height: imageHeight_1
  34928. });
  34929. patternAttrs.width = imageWidth_1;
  34930. patternAttrs.height = imageHeight_1;
  34931. }
  34932. else if (val.svgElement) {
  34933. child = clone(val.svgElement);
  34934. patternAttrs.width = val.svgWidth;
  34935. patternAttrs.height = val.svgHeight;
  34936. }
  34937. if (!child) {
  34938. return;
  34939. }
  34940. var patternWidth;
  34941. var patternHeight;
  34942. if (noRepeat) {
  34943. patternWidth = patternHeight = 1;
  34944. }
  34945. else if (repeatX) {
  34946. patternHeight = 1;
  34947. patternWidth = patternAttrs.width / boundingRect.width;
  34948. }
  34949. else if (repeatY) {
  34950. patternWidth = 1;
  34951. patternHeight = patternAttrs.height / boundingRect.height;
  34952. }
  34953. else {
  34954. patternAttrs.patternUnits = 'userSpaceOnUse';
  34955. }
  34956. if (patternWidth != null && !isNaN(patternWidth)) {
  34957. patternAttrs.width = patternWidth;
  34958. }
  34959. if (patternHeight != null && !isNaN(patternHeight)) {
  34960. patternAttrs.height = patternHeight;
  34961. }
  34962. var patternTransform = getSRTTransformString(val);
  34963. patternTransform && (patternAttrs.patternTransform = patternTransform);
  34964. var patternVNode = createVNode('pattern', '', patternAttrs, [child]);
  34965. var patternKey = vNodeToString(patternVNode);
  34966. var patternCache = scope.patternCache;
  34967. var patternId = patternCache[patternKey];
  34968. if (!patternId) {
  34969. patternId = scope.zrId + '-p' + scope.patternIdx++;
  34970. patternCache[patternKey] = patternId;
  34971. patternAttrs.id = patternId;
  34972. patternVNode = scope.defs[patternId] = createVNode('pattern', patternId, patternAttrs, [child]);
  34973. }
  34974. attrs[target] = getIdURL(patternId);
  34975. }
  34976. function setClipPath(clipPath, attrs, scope) {
  34977. var clipPathCache = scope.clipPathCache, defs = scope.defs;
  34978. var clipPathId = clipPathCache[clipPath.id];
  34979. if (!clipPathId) {
  34980. clipPathId = scope.zrId + '-c' + scope.clipPathIdx++;
  34981. var clipPathAttrs = {
  34982. id: clipPathId
  34983. };
  34984. clipPathCache[clipPath.id] = clipPathId;
  34985. defs[clipPathId] = createVNode('clipPath', clipPathId, clipPathAttrs, [brushSVGPath(clipPath, scope)]);
  34986. }
  34987. attrs['clip-path'] = getIdURL(clipPathId);
  34988. }
  34989. function createTextNode(text) {
  34990. return document.createTextNode(text);
  34991. }
  34992. function insertBefore(parentNode, newNode, referenceNode) {
  34993. parentNode.insertBefore(newNode, referenceNode);
  34994. }
  34995. function removeChild(node, child) {
  34996. node.removeChild(child);
  34997. }
  34998. function appendChild(node, child) {
  34999. node.appendChild(child);
  35000. }
  35001. function parentNode(node) {
  35002. return node.parentNode;
  35003. }
  35004. function nextSibling(node) {
  35005. return node.nextSibling;
  35006. }
  35007. function setTextContent(node, text) {
  35008. node.textContent = text;
  35009. }
  35010. var colonChar = 58;
  35011. var xChar = 120;
  35012. var emptyNode = createVNode('', '');
  35013. function isUndef(s) {
  35014. return s === undefined;
  35015. }
  35016. function isDef(s) {
  35017. return s !== undefined;
  35018. }
  35019. function createKeyToOldIdx(children, beginIdx, endIdx) {
  35020. var map = {};
  35021. for (var i = beginIdx; i <= endIdx; ++i) {
  35022. var key = children[i].key;
  35023. if (key !== undefined) {
  35024. if ("development" !== 'production') {
  35025. if (map[key] != null) {
  35026. console.error("Duplicate key " + key);
  35027. }
  35028. }
  35029. map[key] = i;
  35030. }
  35031. }
  35032. return map;
  35033. }
  35034. function sameVnode(vnode1, vnode2) {
  35035. var isSameKey = vnode1.key === vnode2.key;
  35036. var isSameTag = vnode1.tag === vnode2.tag;
  35037. return isSameTag && isSameKey;
  35038. }
  35039. function createElm(vnode) {
  35040. var i;
  35041. var children = vnode.children;
  35042. var tag = vnode.tag;
  35043. if (isDef(tag)) {
  35044. var elm = (vnode.elm = createElement(tag));
  35045. updateAttrs(emptyNode, vnode);
  35046. if (isArray(children)) {
  35047. for (i = 0; i < children.length; ++i) {
  35048. var ch = children[i];
  35049. if (ch != null) {
  35050. appendChild(elm, createElm(ch));
  35051. }
  35052. }
  35053. }
  35054. else if (isDef(vnode.text) && !isObject(vnode.text)) {
  35055. appendChild(elm, createTextNode(vnode.text));
  35056. }
  35057. }
  35058. else {
  35059. vnode.elm = createTextNode(vnode.text);
  35060. }
  35061. return vnode.elm;
  35062. }
  35063. function addVnodes(parentElm, before, vnodes, startIdx, endIdx) {
  35064. for (; startIdx <= endIdx; ++startIdx) {
  35065. var ch = vnodes[startIdx];
  35066. if (ch != null) {
  35067. insertBefore(parentElm, createElm(ch), before);
  35068. }
  35069. }
  35070. }
  35071. function removeVnodes(parentElm, vnodes, startIdx, endIdx) {
  35072. for (; startIdx <= endIdx; ++startIdx) {
  35073. var ch = vnodes[startIdx];
  35074. if (ch != null) {
  35075. if (isDef(ch.tag)) {
  35076. var parent_1 = parentNode(ch.elm);
  35077. removeChild(parent_1, ch.elm);
  35078. }
  35079. else {
  35080. removeChild(parentElm, ch.elm);
  35081. }
  35082. }
  35083. }
  35084. }
  35085. function updateAttrs(oldVnode, vnode) {
  35086. var key;
  35087. var elm = vnode.elm;
  35088. var oldAttrs = oldVnode && oldVnode.attrs || {};
  35089. var attrs = vnode.attrs || {};
  35090. if (oldAttrs === attrs) {
  35091. return;
  35092. }
  35093. for (key in attrs) {
  35094. var cur = attrs[key];
  35095. var old = oldAttrs[key];
  35096. if (old !== cur) {
  35097. if (cur === true) {
  35098. elm.setAttribute(key, '');
  35099. }
  35100. else if (cur === false) {
  35101. elm.removeAttribute(key);
  35102. }
  35103. else {
  35104. if (key.charCodeAt(0) !== xChar) {
  35105. elm.setAttribute(key, cur);
  35106. }
  35107. else if (key === 'xmlns:xlink' || key === 'xmlns') {
  35108. elm.setAttributeNS(XMLNS, key, cur);
  35109. }
  35110. else if (key.charCodeAt(3) === colonChar) {
  35111. elm.setAttributeNS(XML_NAMESPACE, key, cur);
  35112. }
  35113. else if (key.charCodeAt(5) === colonChar) {
  35114. elm.setAttributeNS(XLINKNS, key, cur);
  35115. }
  35116. else {
  35117. elm.setAttribute(key, cur);
  35118. }
  35119. }
  35120. }
  35121. }
  35122. for (key in oldAttrs) {
  35123. if (!(key in attrs)) {
  35124. elm.removeAttribute(key);
  35125. }
  35126. }
  35127. }
  35128. function updateChildren(parentElm, oldCh, newCh) {
  35129. var oldStartIdx = 0;
  35130. var newStartIdx = 0;
  35131. var oldEndIdx = oldCh.length - 1;
  35132. var oldStartVnode = oldCh[0];
  35133. var oldEndVnode = oldCh[oldEndIdx];
  35134. var newEndIdx = newCh.length - 1;
  35135. var newStartVnode = newCh[0];
  35136. var newEndVnode = newCh[newEndIdx];
  35137. var oldKeyToIdx;
  35138. var idxInOld;
  35139. var elmToMove;
  35140. var before;
  35141. while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
  35142. if (oldStartVnode == null) {
  35143. oldStartVnode = oldCh[++oldStartIdx];
  35144. }
  35145. else if (oldEndVnode == null) {
  35146. oldEndVnode = oldCh[--oldEndIdx];
  35147. }
  35148. else if (newStartVnode == null) {
  35149. newStartVnode = newCh[++newStartIdx];
  35150. }
  35151. else if (newEndVnode == null) {
  35152. newEndVnode = newCh[--newEndIdx];
  35153. }
  35154. else if (sameVnode(oldStartVnode, newStartVnode)) {
  35155. patchVnode(oldStartVnode, newStartVnode);
  35156. oldStartVnode = oldCh[++oldStartIdx];
  35157. newStartVnode = newCh[++newStartIdx];
  35158. }
  35159. else if (sameVnode(oldEndVnode, newEndVnode)) {
  35160. patchVnode(oldEndVnode, newEndVnode);
  35161. oldEndVnode = oldCh[--oldEndIdx];
  35162. newEndVnode = newCh[--newEndIdx];
  35163. }
  35164. else if (sameVnode(oldStartVnode, newEndVnode)) {
  35165. patchVnode(oldStartVnode, newEndVnode);
  35166. insertBefore(parentElm, oldStartVnode.elm, nextSibling(oldEndVnode.elm));
  35167. oldStartVnode = oldCh[++oldStartIdx];
  35168. newEndVnode = newCh[--newEndIdx];
  35169. }
  35170. else if (sameVnode(oldEndVnode, newStartVnode)) {
  35171. patchVnode(oldEndVnode, newStartVnode);
  35172. insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
  35173. oldEndVnode = oldCh[--oldEndIdx];
  35174. newStartVnode = newCh[++newStartIdx];
  35175. }
  35176. else {
  35177. if (isUndef(oldKeyToIdx)) {
  35178. oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
  35179. }
  35180. idxInOld = oldKeyToIdx[newStartVnode.key];
  35181. if (isUndef(idxInOld)) {
  35182. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35183. }
  35184. else {
  35185. elmToMove = oldCh[idxInOld];
  35186. if (elmToMove.tag !== newStartVnode.tag) {
  35187. insertBefore(parentElm, createElm(newStartVnode), oldStartVnode.elm);
  35188. }
  35189. else {
  35190. patchVnode(elmToMove, newStartVnode);
  35191. oldCh[idxInOld] = undefined;
  35192. insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm);
  35193. }
  35194. }
  35195. newStartVnode = newCh[++newStartIdx];
  35196. }
  35197. }
  35198. if (oldStartIdx <= oldEndIdx || newStartIdx <= newEndIdx) {
  35199. if (oldStartIdx > oldEndIdx) {
  35200. before = newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].elm;
  35201. addVnodes(parentElm, before, newCh, newStartIdx, newEndIdx);
  35202. }
  35203. else {
  35204. removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
  35205. }
  35206. }
  35207. }
  35208. function patchVnode(oldVnode, vnode) {
  35209. var elm = (vnode.elm = oldVnode.elm);
  35210. var oldCh = oldVnode.children;
  35211. var ch = vnode.children;
  35212. if (oldVnode === vnode) {
  35213. return;
  35214. }
  35215. updateAttrs(oldVnode, vnode);
  35216. if (isUndef(vnode.text)) {
  35217. if (isDef(oldCh) && isDef(ch)) {
  35218. if (oldCh !== ch) {
  35219. updateChildren(elm, oldCh, ch);
  35220. }
  35221. }
  35222. else if (isDef(ch)) {
  35223. if (isDef(oldVnode.text)) {
  35224. setTextContent(elm, '');
  35225. }
  35226. addVnodes(elm, null, ch, 0, ch.length - 1);
  35227. }
  35228. else if (isDef(oldCh)) {
  35229. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35230. }
  35231. else if (isDef(oldVnode.text)) {
  35232. setTextContent(elm, '');
  35233. }
  35234. }
  35235. else if (oldVnode.text !== vnode.text) {
  35236. if (isDef(oldCh)) {
  35237. removeVnodes(elm, oldCh, 0, oldCh.length - 1);
  35238. }
  35239. setTextContent(elm, vnode.text);
  35240. }
  35241. }
  35242. function patch(oldVnode, vnode) {
  35243. if (sameVnode(oldVnode, vnode)) {
  35244. patchVnode(oldVnode, vnode);
  35245. }
  35246. else {
  35247. var elm = oldVnode.elm;
  35248. var parent_2 = parentNode(elm);
  35249. createElm(vnode);
  35250. if (parent_2 !== null) {
  35251. insertBefore(parent_2, vnode.elm, nextSibling(elm));
  35252. removeVnodes(parent_2, [oldVnode], 0, 0);
  35253. }
  35254. }
  35255. return vnode;
  35256. }
  35257. var svgId = 0;
  35258. var SVGPainter = (function () {
  35259. function SVGPainter(root, storage, opts) {
  35260. this.type = 'svg';
  35261. this.refreshHover = createMethodNotSupport('refreshHover');
  35262. this.configLayer = createMethodNotSupport('configLayer');
  35263. this.storage = storage;
  35264. this._opts = opts = extend({}, opts);
  35265. this.root = root;
  35266. this._id = 'zr' + svgId++;
  35267. this._oldVNode = createSVGVNode(opts.width, opts.height);
  35268. if (root && !opts.ssr) {
  35269. var viewport = this._viewport = document.createElement('div');
  35270. viewport.style.cssText = 'position:relative;overflow:hidden';
  35271. var svgDom = this._svgDom = this._oldVNode.elm = createElement('svg');
  35272. updateAttrs(null, this._oldVNode);
  35273. viewport.appendChild(svgDom);
  35274. root.appendChild(viewport);
  35275. }
  35276. this.resize(opts.width, opts.height);
  35277. }
  35278. SVGPainter.prototype.getType = function () {
  35279. return this.type;
  35280. };
  35281. SVGPainter.prototype.getViewportRoot = function () {
  35282. return this._viewport;
  35283. };
  35284. SVGPainter.prototype.getViewportRootOffset = function () {
  35285. var viewportRoot = this.getViewportRoot();
  35286. if (viewportRoot) {
  35287. return {
  35288. offsetLeft: viewportRoot.offsetLeft || 0,
  35289. offsetTop: viewportRoot.offsetTop || 0
  35290. };
  35291. }
  35292. };
  35293. SVGPainter.prototype.getSvgDom = function () {
  35294. return this._svgDom;
  35295. };
  35296. SVGPainter.prototype.refresh = function () {
  35297. if (this.root) {
  35298. var vnode = this.renderToVNode({
  35299. willUpdate: true
  35300. });
  35301. vnode.attrs.style = 'position:absolute;left:0;top:0;user-select:none';
  35302. patch(this._oldVNode, vnode);
  35303. this._oldVNode = vnode;
  35304. }
  35305. };
  35306. SVGPainter.prototype.renderOneToVNode = function (el) {
  35307. return brush$1(el, createBrushScope(this._id));
  35308. };
  35309. SVGPainter.prototype.renderToVNode = function (opts) {
  35310. opts = opts || {};
  35311. var list = this.storage.getDisplayList(true);
  35312. var width = this._width;
  35313. var height = this._height;
  35314. var scope = createBrushScope(this._id);
  35315. scope.animation = opts.animation;
  35316. scope.willUpdate = opts.willUpdate;
  35317. scope.compress = opts.compress;
  35318. var children = [];
  35319. var bgVNode = this._bgVNode = createBackgroundVNode(width, height, this._backgroundColor, scope);
  35320. bgVNode && children.push(bgVNode);
  35321. var mainVNode = !opts.compress
  35322. ? (this._mainVNode = createVNode('g', 'main', {}, [])) : null;
  35323. this._paintList(list, scope, mainVNode ? mainVNode.children : children);
  35324. mainVNode && children.push(mainVNode);
  35325. var defs = map(keys(scope.defs), function (id) { return scope.defs[id]; });
  35326. if (defs.length) {
  35327. children.push(createVNode('defs', 'defs', {}, defs));
  35328. }
  35329. if (opts.animation) {
  35330. var animationCssStr = getCssString(scope.cssNodes, scope.cssAnims, { newline: true });
  35331. if (animationCssStr) {
  35332. var styleNode = createVNode('style', 'stl', {}, [], animationCssStr);
  35333. children.push(styleNode);
  35334. }
  35335. }
  35336. return createSVGVNode(width, height, children, opts.useViewBox);
  35337. };
  35338. SVGPainter.prototype.renderToString = function (opts) {
  35339. opts = opts || {};
  35340. return vNodeToString(this.renderToVNode({
  35341. animation: retrieve2(opts.cssAnimation, true),
  35342. willUpdate: false,
  35343. compress: true,
  35344. useViewBox: retrieve2(opts.useViewBox, true)
  35345. }), { newline: true });
  35346. };
  35347. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  35348. this._backgroundColor = backgroundColor;
  35349. };
  35350. SVGPainter.prototype.getSvgRoot = function () {
  35351. return this._mainVNode && this._mainVNode.elm;
  35352. };
  35353. SVGPainter.prototype._paintList = function (list, scope, out) {
  35354. var listLen = list.length;
  35355. var clipPathsGroupsStack = [];
  35356. var clipPathsGroupsStackDepth = 0;
  35357. var currentClipPathGroup;
  35358. var prevClipPaths;
  35359. var clipGroupNodeIdx = 0;
  35360. for (var i = 0; i < listLen; i++) {
  35361. var displayable = list[i];
  35362. if (!displayable.invisible) {
  35363. var clipPaths = displayable.__clipPaths;
  35364. var len = clipPaths && clipPaths.length || 0;
  35365. var prevLen = prevClipPaths && prevClipPaths.length || 0;
  35366. var lca = void 0;
  35367. for (lca = Math.max(len - 1, prevLen - 1); lca >= 0; lca--) {
  35368. if (clipPaths && prevClipPaths
  35369. && clipPaths[lca] === prevClipPaths[lca]) {
  35370. break;
  35371. }
  35372. }
  35373. for (var i_1 = prevLen - 1; i_1 > lca; i_1--) {
  35374. clipPathsGroupsStackDepth--;
  35375. currentClipPathGroup = clipPathsGroupsStack[clipPathsGroupsStackDepth - 1];
  35376. }
  35377. for (var i_2 = lca + 1; i_2 < len; i_2++) {
  35378. var groupAttrs = {};
  35379. setClipPath(clipPaths[i_2], groupAttrs, scope);
  35380. var g = createVNode('g', 'clip-g-' + clipGroupNodeIdx++, groupAttrs, []);
  35381. (currentClipPathGroup ? currentClipPathGroup.children : out).push(g);
  35382. clipPathsGroupsStack[clipPathsGroupsStackDepth++] = g;
  35383. currentClipPathGroup = g;
  35384. }
  35385. prevClipPaths = clipPaths;
  35386. var ret = brush$1(displayable, scope);
  35387. if (ret) {
  35388. (currentClipPathGroup ? currentClipPathGroup.children : out).push(ret);
  35389. }
  35390. }
  35391. }
  35392. };
  35393. SVGPainter.prototype.resize = function (width, height) {
  35394. var opts = this._opts;
  35395. var root = this.root;
  35396. var viewport = this._viewport;
  35397. width != null && (opts.width = width);
  35398. height != null && (opts.height = height);
  35399. if (root && viewport) {
  35400. viewport.style.display = 'none';
  35401. width = getSize(root, 0, opts);
  35402. height = getSize(root, 1, opts);
  35403. viewport.style.display = '';
  35404. }
  35405. if (this._width !== width || this._height !== height) {
  35406. this._width = width;
  35407. this._height = height;
  35408. if (viewport) {
  35409. var viewportStyle = viewport.style;
  35410. viewportStyle.width = width + 'px';
  35411. viewportStyle.height = height + 'px';
  35412. }
  35413. if (!isPattern(this._backgroundColor)) {
  35414. var svgDom = this._svgDom;
  35415. if (svgDom) {
  35416. svgDom.setAttribute('width', width);
  35417. svgDom.setAttribute('height', height);
  35418. }
  35419. var bgEl = this._bgVNode && this._bgVNode.elm;
  35420. if (bgEl) {
  35421. bgEl.setAttribute('width', width);
  35422. bgEl.setAttribute('height', height);
  35423. }
  35424. }
  35425. else {
  35426. this.refresh();
  35427. }
  35428. }
  35429. };
  35430. SVGPainter.prototype.getWidth = function () {
  35431. return this._width;
  35432. };
  35433. SVGPainter.prototype.getHeight = function () {
  35434. return this._height;
  35435. };
  35436. SVGPainter.prototype.dispose = function () {
  35437. if (this.root) {
  35438. this.root.innerHTML = '';
  35439. }
  35440. this._svgDom =
  35441. this._viewport =
  35442. this.storage =
  35443. this._oldVNode =
  35444. this._bgVNode =
  35445. this._mainVNode = null;
  35446. };
  35447. SVGPainter.prototype.clear = function () {
  35448. if (this._svgDom) {
  35449. this._svgDom.innerHTML = null;
  35450. }
  35451. this._oldVNode = null;
  35452. };
  35453. SVGPainter.prototype.toDataURL = function (base64) {
  35454. var str = this.renderToString();
  35455. var prefix = 'data:image/svg+xml;';
  35456. if (base64) {
  35457. str = encodeBase64(str);
  35458. return str && prefix + 'base64,' + str;
  35459. }
  35460. return prefix + 'charset=UTF-8,' + encodeURIComponent(str);
  35461. };
  35462. return SVGPainter;
  35463. }());
  35464. function createMethodNotSupport(method) {
  35465. return function () {
  35466. if ("development" !== 'production') {
  35467. logError('In SVG mode painter not support method "' + method + '"');
  35468. }
  35469. };
  35470. }
  35471. function createBackgroundVNode(width, height, backgroundColor, scope) {
  35472. var bgVNode;
  35473. if (backgroundColor && backgroundColor !== 'none') {
  35474. bgVNode = createVNode('rect', 'bg', {
  35475. width: width,
  35476. height: height,
  35477. x: '0',
  35478. y: '0',
  35479. id: '0'
  35480. });
  35481. if (isGradient(backgroundColor)) {
  35482. setGradient({ fill: backgroundColor }, bgVNode.attrs, 'fill', scope);
  35483. }
  35484. else if (isPattern(backgroundColor)) {
  35485. setPattern({
  35486. style: {
  35487. fill: backgroundColor
  35488. },
  35489. dirty: noop,
  35490. getBoundingRect: function () { return ({ width: width, height: height }); }
  35491. }, bgVNode.attrs, 'fill', scope);
  35492. }
  35493. else {
  35494. var _a = normalizeColor(backgroundColor), color = _a.color, opacity = _a.opacity;
  35495. bgVNode.attrs.fill = color;
  35496. opacity < 1 && (bgVNode.attrs['fill-opacity'] = opacity);
  35497. }
  35498. }
  35499. return bgVNode;
  35500. }
  35501. function install(registers) {
  35502. registers.registerPainter('svg', SVGPainter);
  35503. }
  35504. function createDom(id, painter, dpr) {
  35505. var newDom = platformApi.createCanvas();
  35506. var width = painter.getWidth();
  35507. var height = painter.getHeight();
  35508. var newDomStyle = newDom.style;
  35509. if (newDomStyle) {
  35510. newDomStyle.position = 'absolute';
  35511. newDomStyle.left = '0';
  35512. newDomStyle.top = '0';
  35513. newDomStyle.width = width + 'px';
  35514. newDomStyle.height = height + 'px';
  35515. newDom.setAttribute('data-zr-dom-id', id);
  35516. }
  35517. newDom.width = width * dpr;
  35518. newDom.height = height * dpr;
  35519. return newDom;
  35520. }
  35521. var Layer = (function (_super) {
  35522. __extends(Layer, _super);
  35523. function Layer(id, painter, dpr) {
  35524. var _this = _super.call(this) || this;
  35525. _this.motionBlur = false;
  35526. _this.lastFrameAlpha = 0.7;
  35527. _this.dpr = 1;
  35528. _this.virtual = false;
  35529. _this.config = {};
  35530. _this.incremental = false;
  35531. _this.zlevel = 0;
  35532. _this.maxRepaintRectCount = 5;
  35533. _this.__dirty = true;
  35534. _this.__firstTimePaint = true;
  35535. _this.__used = false;
  35536. _this.__drawIndex = 0;
  35537. _this.__startIndex = 0;
  35538. _this.__endIndex = 0;
  35539. _this.__prevStartIndex = null;
  35540. _this.__prevEndIndex = null;
  35541. var dom;
  35542. dpr = dpr || devicePixelRatio;
  35543. if (typeof id === 'string') {
  35544. dom = createDom(id, painter, dpr);
  35545. }
  35546. else if (isObject(id)) {
  35547. dom = id;
  35548. id = dom.id;
  35549. }
  35550. _this.id = id;
  35551. _this.dom = dom;
  35552. var domStyle = dom.style;
  35553. if (domStyle) {
  35554. disableUserSelect(dom);
  35555. dom.onselectstart = function () { return false; };
  35556. domStyle.padding = '0';
  35557. domStyle.margin = '0';
  35558. domStyle.borderWidth = '0';
  35559. }
  35560. _this.painter = painter;
  35561. _this.dpr = dpr;
  35562. return _this;
  35563. }
  35564. Layer.prototype.getElementCount = function () {
  35565. return this.__endIndex - this.__startIndex;
  35566. };
  35567. Layer.prototype.afterBrush = function () {
  35568. this.__prevStartIndex = this.__startIndex;
  35569. this.__prevEndIndex = this.__endIndex;
  35570. };
  35571. Layer.prototype.initContext = function () {
  35572. this.ctx = this.dom.getContext('2d');
  35573. this.ctx.dpr = this.dpr;
  35574. };
  35575. Layer.prototype.setUnpainted = function () {
  35576. this.__firstTimePaint = true;
  35577. };
  35578. Layer.prototype.createBackBuffer = function () {
  35579. var dpr = this.dpr;
  35580. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  35581. this.ctxBack = this.domBack.getContext('2d');
  35582. if (dpr !== 1) {
  35583. this.ctxBack.scale(dpr, dpr);
  35584. }
  35585. };
  35586. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  35587. if (this.__firstTimePaint) {
  35588. this.__firstTimePaint = false;
  35589. return null;
  35590. }
  35591. var mergedRepaintRects = [];
  35592. var maxRepaintRectCount = this.maxRepaintRectCount;
  35593. var full = false;
  35594. var pendingRect = new BoundingRect(0, 0, 0, 0);
  35595. function addRectToMergePool(rect) {
  35596. if (!rect.isFinite() || rect.isZero()) {
  35597. return;
  35598. }
  35599. if (mergedRepaintRects.length === 0) {
  35600. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35601. boundingRect.copy(rect);
  35602. mergedRepaintRects.push(boundingRect);
  35603. }
  35604. else {
  35605. var isMerged = false;
  35606. var minDeltaArea = Infinity;
  35607. var bestRectToMergeIdx = 0;
  35608. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  35609. var mergedRect = mergedRepaintRects[i];
  35610. if (mergedRect.intersect(rect)) {
  35611. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  35612. pendingRect_1.copy(mergedRect);
  35613. pendingRect_1.union(rect);
  35614. mergedRepaintRects[i] = pendingRect_1;
  35615. isMerged = true;
  35616. break;
  35617. }
  35618. else if (full) {
  35619. pendingRect.copy(rect);
  35620. pendingRect.union(mergedRect);
  35621. var aArea = rect.width * rect.height;
  35622. var bArea = mergedRect.width * mergedRect.height;
  35623. var pendingArea = pendingRect.width * pendingRect.height;
  35624. var deltaArea = pendingArea - aArea - bArea;
  35625. if (deltaArea < minDeltaArea) {
  35626. minDeltaArea = deltaArea;
  35627. bestRectToMergeIdx = i;
  35628. }
  35629. }
  35630. }
  35631. if (full) {
  35632. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  35633. isMerged = true;
  35634. }
  35635. if (!isMerged) {
  35636. var boundingRect = new BoundingRect(0, 0, 0, 0);
  35637. boundingRect.copy(rect);
  35638. mergedRepaintRects.push(boundingRect);
  35639. }
  35640. if (!full) {
  35641. full = mergedRepaintRects.length >= maxRepaintRectCount;
  35642. }
  35643. }
  35644. }
  35645. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  35646. var el = displayList[i];
  35647. if (el) {
  35648. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35649. var prevRect = el.__isRendered && ((el.__dirty & REDRAW_BIT) || !shouldPaint)
  35650. ? el.getPrevPaintRect()
  35651. : null;
  35652. if (prevRect) {
  35653. addRectToMergePool(prevRect);
  35654. }
  35655. var curRect = shouldPaint && ((el.__dirty & REDRAW_BIT) || !el.__isRendered)
  35656. ? el.getPaintRect()
  35657. : null;
  35658. if (curRect) {
  35659. addRectToMergePool(curRect);
  35660. }
  35661. }
  35662. }
  35663. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  35664. var el = prevList[i];
  35665. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  35666. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  35667. var prevRect = el.getPrevPaintRect();
  35668. if (prevRect) {
  35669. addRectToMergePool(prevRect);
  35670. }
  35671. }
  35672. }
  35673. var hasIntersections;
  35674. do {
  35675. hasIntersections = false;
  35676. for (var i = 0; i < mergedRepaintRects.length;) {
  35677. if (mergedRepaintRects[i].isZero()) {
  35678. mergedRepaintRects.splice(i, 1);
  35679. continue;
  35680. }
  35681. for (var j = i + 1; j < mergedRepaintRects.length;) {
  35682. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  35683. hasIntersections = true;
  35684. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  35685. mergedRepaintRects.splice(j, 1);
  35686. }
  35687. else {
  35688. j++;
  35689. }
  35690. }
  35691. i++;
  35692. }
  35693. } while (hasIntersections);
  35694. this._paintRects = mergedRepaintRects;
  35695. return mergedRepaintRects;
  35696. };
  35697. Layer.prototype.debugGetPaintRects = function () {
  35698. return (this._paintRects || []).slice();
  35699. };
  35700. Layer.prototype.resize = function (width, height) {
  35701. var dpr = this.dpr;
  35702. var dom = this.dom;
  35703. var domStyle = dom.style;
  35704. var domBack = this.domBack;
  35705. if (domStyle) {
  35706. domStyle.width = width + 'px';
  35707. domStyle.height = height + 'px';
  35708. }
  35709. dom.width = width * dpr;
  35710. dom.height = height * dpr;
  35711. if (domBack) {
  35712. domBack.width = width * dpr;
  35713. domBack.height = height * dpr;
  35714. if (dpr !== 1) {
  35715. this.ctxBack.scale(dpr, dpr);
  35716. }
  35717. }
  35718. };
  35719. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  35720. var dom = this.dom;
  35721. var ctx = this.ctx;
  35722. var width = dom.width;
  35723. var height = dom.height;
  35724. clearColor = clearColor || this.clearColor;
  35725. var haveMotionBLur = this.motionBlur && !clearAll;
  35726. var lastFrameAlpha = this.lastFrameAlpha;
  35727. var dpr = this.dpr;
  35728. var self = this;
  35729. if (haveMotionBLur) {
  35730. if (!this.domBack) {
  35731. this.createBackBuffer();
  35732. }
  35733. this.ctxBack.globalCompositeOperation = 'copy';
  35734. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  35735. }
  35736. var domBack = this.domBack;
  35737. function doClear(x, y, width, height) {
  35738. ctx.clearRect(x, y, width, height);
  35739. if (clearColor && clearColor !== 'transparent') {
  35740. var clearColorGradientOrPattern = void 0;
  35741. if (isGradientObject(clearColor)) {
  35742. var shouldCache = clearColor.global || (clearColor.__width === width
  35743. && clearColor.__height === height);
  35744. clearColorGradientOrPattern = shouldCache
  35745. && clearColor.__canvasGradient
  35746. || getCanvasGradient(ctx, clearColor, {
  35747. x: 0,
  35748. y: 0,
  35749. width: width,
  35750. height: height
  35751. });
  35752. clearColor.__canvasGradient = clearColorGradientOrPattern;
  35753. clearColor.__width = width;
  35754. clearColor.__height = height;
  35755. }
  35756. else if (isImagePatternObject(clearColor)) {
  35757. clearColor.scaleX = clearColor.scaleX || dpr;
  35758. clearColor.scaleY = clearColor.scaleY || dpr;
  35759. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  35760. dirty: function () {
  35761. self.setUnpainted();
  35762. self.__painter.refresh();
  35763. }
  35764. });
  35765. }
  35766. ctx.save();
  35767. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  35768. ctx.fillRect(x, y, width, height);
  35769. ctx.restore();
  35770. }
  35771. if (haveMotionBLur) {
  35772. ctx.save();
  35773. ctx.globalAlpha = lastFrameAlpha;
  35774. ctx.drawImage(domBack, x, y, width, height);
  35775. ctx.restore();
  35776. }
  35777. }
  35778. if (!repaintRects || haveMotionBLur) {
  35779. doClear(0, 0, width, height);
  35780. }
  35781. else if (repaintRects.length) {
  35782. each(repaintRects, function (rect) {
  35783. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  35784. });
  35785. }
  35786. };
  35787. return Layer;
  35788. }(Eventful));
  35789. var HOVER_LAYER_ZLEVEL = 1e5;
  35790. var CANVAS_ZLEVEL = 314159;
  35791. var EL_AFTER_INCREMENTAL_INC = 0.01;
  35792. var INCREMENTAL_INC = 0.001;
  35793. function isLayerValid(layer) {
  35794. if (!layer) {
  35795. return false;
  35796. }
  35797. if (layer.__builtin__) {
  35798. return true;
  35799. }
  35800. if (typeof (layer.resize) !== 'function'
  35801. || typeof (layer.refresh) !== 'function') {
  35802. return false;
  35803. }
  35804. return true;
  35805. }
  35806. function createRoot(width, height) {
  35807. var domRoot = document.createElement('div');
  35808. domRoot.style.cssText = [
  35809. 'position:relative',
  35810. 'width:' + width + 'px',
  35811. 'height:' + height + 'px',
  35812. 'padding:0',
  35813. 'margin:0',
  35814. 'border-width:0'
  35815. ].join(';') + ';';
  35816. return domRoot;
  35817. }
  35818. var CanvasPainter = (function () {
  35819. function CanvasPainter(root, storage, opts, id) {
  35820. this.type = 'canvas';
  35821. this._zlevelList = [];
  35822. this._prevDisplayList = [];
  35823. this._layers = {};
  35824. this._layerConfig = {};
  35825. this._needsManuallyCompositing = false;
  35826. this.type = 'canvas';
  35827. var singleCanvas = !root.nodeName
  35828. || root.nodeName.toUpperCase() === 'CANVAS';
  35829. this._opts = opts = extend({}, opts || {});
  35830. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  35831. this._singleCanvas = singleCanvas;
  35832. this.root = root;
  35833. var rootStyle = root.style;
  35834. if (rootStyle) {
  35835. disableUserSelect(root);
  35836. root.innerHTML = '';
  35837. }
  35838. this.storage = storage;
  35839. var zlevelList = this._zlevelList;
  35840. this._prevDisplayList = [];
  35841. var layers = this._layers;
  35842. if (!singleCanvas) {
  35843. this._width = getSize(root, 0, opts);
  35844. this._height = getSize(root, 1, opts);
  35845. var domRoot = this._domRoot = createRoot(this._width, this._height);
  35846. root.appendChild(domRoot);
  35847. }
  35848. else {
  35849. var rootCanvas = root;
  35850. var width = rootCanvas.width;
  35851. var height = rootCanvas.height;
  35852. if (opts.width != null) {
  35853. width = opts.width;
  35854. }
  35855. if (opts.height != null) {
  35856. height = opts.height;
  35857. }
  35858. this.dpr = opts.devicePixelRatio || 1;
  35859. rootCanvas.width = width * this.dpr;
  35860. rootCanvas.height = height * this.dpr;
  35861. this._width = width;
  35862. this._height = height;
  35863. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  35864. mainLayer.__builtin__ = true;
  35865. mainLayer.initContext();
  35866. layers[CANVAS_ZLEVEL] = mainLayer;
  35867. mainLayer.zlevel = CANVAS_ZLEVEL;
  35868. zlevelList.push(CANVAS_ZLEVEL);
  35869. this._domRoot = root;
  35870. }
  35871. }
  35872. CanvasPainter.prototype.getType = function () {
  35873. return 'canvas';
  35874. };
  35875. CanvasPainter.prototype.isSingleCanvas = function () {
  35876. return this._singleCanvas;
  35877. };
  35878. CanvasPainter.prototype.getViewportRoot = function () {
  35879. return this._domRoot;
  35880. };
  35881. CanvasPainter.prototype.getViewportRootOffset = function () {
  35882. var viewportRoot = this.getViewportRoot();
  35883. if (viewportRoot) {
  35884. return {
  35885. offsetLeft: viewportRoot.offsetLeft || 0,
  35886. offsetTop: viewportRoot.offsetTop || 0
  35887. };
  35888. }
  35889. };
  35890. CanvasPainter.prototype.refresh = function (paintAll) {
  35891. var list = this.storage.getDisplayList(true);
  35892. var prevList = this._prevDisplayList;
  35893. var zlevelList = this._zlevelList;
  35894. this._redrawId = Math.random();
  35895. this._paintList(list, prevList, paintAll, this._redrawId);
  35896. for (var i = 0; i < zlevelList.length; i++) {
  35897. var z = zlevelList[i];
  35898. var layer = this._layers[z];
  35899. if (!layer.__builtin__ && layer.refresh) {
  35900. var clearColor = i === 0 ? this._backgroundColor : null;
  35901. layer.refresh(clearColor);
  35902. }
  35903. }
  35904. if (this._opts.useDirtyRect) {
  35905. this._prevDisplayList = list.slice();
  35906. }
  35907. return this;
  35908. };
  35909. CanvasPainter.prototype.refreshHover = function () {
  35910. this._paintHoverList(this.storage.getDisplayList(false));
  35911. };
  35912. CanvasPainter.prototype._paintHoverList = function (list) {
  35913. var len = list.length;
  35914. var hoverLayer = this._hoverlayer;
  35915. hoverLayer && hoverLayer.clear();
  35916. if (!len) {
  35917. return;
  35918. }
  35919. var scope = {
  35920. inHover: true,
  35921. viewWidth: this._width,
  35922. viewHeight: this._height
  35923. };
  35924. var ctx;
  35925. for (var i = 0; i < len; i++) {
  35926. var el = list[i];
  35927. if (el.__inHover) {
  35928. if (!hoverLayer) {
  35929. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  35930. }
  35931. if (!ctx) {
  35932. ctx = hoverLayer.ctx;
  35933. ctx.save();
  35934. }
  35935. brush(ctx, el, scope, i === len - 1);
  35936. }
  35937. }
  35938. if (ctx) {
  35939. ctx.restore();
  35940. }
  35941. };
  35942. CanvasPainter.prototype.getHoverLayer = function () {
  35943. return this.getLayer(HOVER_LAYER_ZLEVEL);
  35944. };
  35945. CanvasPainter.prototype.paintOne = function (ctx, el) {
  35946. brushSingle(ctx, el);
  35947. };
  35948. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  35949. if (this._redrawId !== redrawId) {
  35950. return;
  35951. }
  35952. paintAll = paintAll || false;
  35953. this._updateLayerStatus(list);
  35954. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  35955. if (this._needsManuallyCompositing) {
  35956. this._compositeManually();
  35957. }
  35958. if (needsRefreshHover) {
  35959. this._paintHoverList(list);
  35960. }
  35961. if (!finished) {
  35962. var self_1 = this;
  35963. requestAnimationFrame$1(function () {
  35964. self_1._paintList(list, prevList, paintAll, redrawId);
  35965. });
  35966. }
  35967. else {
  35968. this.eachLayer(function (layer) {
  35969. layer.afterBrush && layer.afterBrush();
  35970. });
  35971. }
  35972. };
  35973. CanvasPainter.prototype._compositeManually = function () {
  35974. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  35975. var width = this._domRoot.width;
  35976. var height = this._domRoot.height;
  35977. ctx.clearRect(0, 0, width, height);
  35978. this.eachBuiltinLayer(function (layer) {
  35979. if (layer.virtual) {
  35980. ctx.drawImage(layer.dom, 0, 0, width, height);
  35981. }
  35982. });
  35983. };
  35984. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  35985. var _this = this;
  35986. var layerList = [];
  35987. var useDirtyRect = this._opts.useDirtyRect;
  35988. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  35989. var zlevel = this._zlevelList[zi];
  35990. var layer = this._layers[zlevel];
  35991. if (layer.__builtin__
  35992. && layer !== this._hoverlayer
  35993. && (layer.__dirty || paintAll)) {
  35994. layerList.push(layer);
  35995. }
  35996. }
  35997. var finished = true;
  35998. var needsRefreshHover = false;
  35999. var _loop_1 = function (k) {
  36000. var layer = layerList[k];
  36001. var ctx = layer.ctx;
  36002. var repaintRects = useDirtyRect
  36003. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  36004. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  36005. var useTimer = !paintAll && layer.incremental && Date.now;
  36006. var startTime = useTimer && Date.now();
  36007. var clearColor = layer.zlevel === this_1._zlevelList[0]
  36008. ? this_1._backgroundColor : null;
  36009. if (layer.__startIndex === layer.__endIndex) {
  36010. layer.clear(false, clearColor, repaintRects);
  36011. }
  36012. else if (start === layer.__startIndex) {
  36013. var firstEl = list[start];
  36014. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  36015. layer.clear(false, clearColor, repaintRects);
  36016. }
  36017. }
  36018. if (start === -1) {
  36019. console.error('For some unknown reason. drawIndex is -1');
  36020. start = layer.__startIndex;
  36021. }
  36022. var i;
  36023. var repaint = function (repaintRect) {
  36024. var scope = {
  36025. inHover: false,
  36026. allClipped: false,
  36027. prevEl: null,
  36028. viewWidth: _this._width,
  36029. viewHeight: _this._height
  36030. };
  36031. for (i = start; i < layer.__endIndex; i++) {
  36032. var el = list[i];
  36033. if (el.__inHover) {
  36034. needsRefreshHover = true;
  36035. }
  36036. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  36037. if (useTimer) {
  36038. var dTime = Date.now() - startTime;
  36039. if (dTime > 15) {
  36040. break;
  36041. }
  36042. }
  36043. }
  36044. if (scope.prevElClipPaths) {
  36045. ctx.restore();
  36046. }
  36047. };
  36048. if (repaintRects) {
  36049. if (repaintRects.length === 0) {
  36050. i = layer.__endIndex;
  36051. }
  36052. else {
  36053. var dpr = this_1.dpr;
  36054. for (var r = 0; r < repaintRects.length; ++r) {
  36055. var rect = repaintRects[r];
  36056. ctx.save();
  36057. ctx.beginPath();
  36058. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  36059. ctx.clip();
  36060. repaint(rect);
  36061. ctx.restore();
  36062. }
  36063. }
  36064. }
  36065. else {
  36066. ctx.save();
  36067. repaint();
  36068. ctx.restore();
  36069. }
  36070. layer.__drawIndex = i;
  36071. if (layer.__drawIndex < layer.__endIndex) {
  36072. finished = false;
  36073. }
  36074. };
  36075. var this_1 = this;
  36076. for (var k = 0; k < layerList.length; k++) {
  36077. _loop_1(k);
  36078. }
  36079. if (env.wxa) {
  36080. each(this._layers, function (layer) {
  36081. if (layer && layer.ctx && layer.ctx.draw) {
  36082. layer.ctx.draw();
  36083. }
  36084. });
  36085. }
  36086. return {
  36087. finished: finished,
  36088. needsRefreshHover: needsRefreshHover
  36089. };
  36090. };
  36091. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  36092. var ctx = currentLayer.ctx;
  36093. if (useDirtyRect) {
  36094. var paintRect = el.getPaintRect();
  36095. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  36096. brush(ctx, el, scope, isLast);
  36097. el.setPrevPaintRect(paintRect);
  36098. }
  36099. }
  36100. else {
  36101. brush(ctx, el, scope, isLast);
  36102. }
  36103. };
  36104. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  36105. if (this._singleCanvas && !this._needsManuallyCompositing) {
  36106. zlevel = CANVAS_ZLEVEL;
  36107. }
  36108. var layer = this._layers[zlevel];
  36109. if (!layer) {
  36110. layer = new Layer('zr_' + zlevel, this, this.dpr);
  36111. layer.zlevel = zlevel;
  36112. layer.__builtin__ = true;
  36113. if (this._layerConfig[zlevel]) {
  36114. merge(layer, this._layerConfig[zlevel], true);
  36115. }
  36116. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  36117. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  36118. }
  36119. if (virtual) {
  36120. layer.virtual = virtual;
  36121. }
  36122. this.insertLayer(zlevel, layer);
  36123. layer.initContext();
  36124. }
  36125. return layer;
  36126. };
  36127. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  36128. var layersMap = this._layers;
  36129. var zlevelList = this._zlevelList;
  36130. var len = zlevelList.length;
  36131. var domRoot = this._domRoot;
  36132. var prevLayer = null;
  36133. var i = -1;
  36134. if (layersMap[zlevel]) {
  36135. if ("development" !== 'production') {
  36136. logError('ZLevel ' + zlevel + ' has been used already');
  36137. }
  36138. return;
  36139. }
  36140. if (!isLayerValid(layer)) {
  36141. if ("development" !== 'production') {
  36142. logError('Layer of zlevel ' + zlevel + ' is not valid');
  36143. }
  36144. return;
  36145. }
  36146. if (len > 0 && zlevel > zlevelList[0]) {
  36147. for (i = 0; i < len - 1; i++) {
  36148. if (zlevelList[i] < zlevel
  36149. && zlevelList[i + 1] > zlevel) {
  36150. break;
  36151. }
  36152. }
  36153. prevLayer = layersMap[zlevelList[i]];
  36154. }
  36155. zlevelList.splice(i + 1, 0, zlevel);
  36156. layersMap[zlevel] = layer;
  36157. if (!layer.virtual) {
  36158. if (prevLayer) {
  36159. var prevDom = prevLayer.dom;
  36160. if (prevDom.nextSibling) {
  36161. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  36162. }
  36163. else {
  36164. domRoot.appendChild(layer.dom);
  36165. }
  36166. }
  36167. else {
  36168. if (domRoot.firstChild) {
  36169. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  36170. }
  36171. else {
  36172. domRoot.appendChild(layer.dom);
  36173. }
  36174. }
  36175. }
  36176. layer.__painter = this;
  36177. };
  36178. CanvasPainter.prototype.eachLayer = function (cb, context) {
  36179. var zlevelList = this._zlevelList;
  36180. for (var i = 0; i < zlevelList.length; i++) {
  36181. var z = zlevelList[i];
  36182. cb.call(context, this._layers[z], z);
  36183. }
  36184. };
  36185. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  36186. var zlevelList = this._zlevelList;
  36187. for (var i = 0; i < zlevelList.length; i++) {
  36188. var z = zlevelList[i];
  36189. var layer = this._layers[z];
  36190. if (layer.__builtin__) {
  36191. cb.call(context, layer, z);
  36192. }
  36193. }
  36194. };
  36195. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  36196. var zlevelList = this._zlevelList;
  36197. for (var i = 0; i < zlevelList.length; i++) {
  36198. var z = zlevelList[i];
  36199. var layer = this._layers[z];
  36200. if (!layer.__builtin__) {
  36201. cb.call(context, layer, z);
  36202. }
  36203. }
  36204. };
  36205. CanvasPainter.prototype.getLayers = function () {
  36206. return this._layers;
  36207. };
  36208. CanvasPainter.prototype._updateLayerStatus = function (list) {
  36209. this.eachBuiltinLayer(function (layer, z) {
  36210. layer.__dirty = layer.__used = false;
  36211. });
  36212. function updatePrevLayer(idx) {
  36213. if (prevLayer) {
  36214. if (prevLayer.__endIndex !== idx) {
  36215. prevLayer.__dirty = true;
  36216. }
  36217. prevLayer.__endIndex = idx;
  36218. }
  36219. }
  36220. if (this._singleCanvas) {
  36221. for (var i_1 = 1; i_1 < list.length; i_1++) {
  36222. var el = list[i_1];
  36223. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  36224. this._needsManuallyCompositing = true;
  36225. break;
  36226. }
  36227. }
  36228. }
  36229. var prevLayer = null;
  36230. var incrementalLayerCount = 0;
  36231. var prevZlevel;
  36232. var i;
  36233. for (i = 0; i < list.length; i++) {
  36234. var el = list[i];
  36235. var zlevel = el.zlevel;
  36236. var layer = void 0;
  36237. if (prevZlevel !== zlevel) {
  36238. prevZlevel = zlevel;
  36239. incrementalLayerCount = 0;
  36240. }
  36241. if (el.incremental) {
  36242. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  36243. layer.incremental = true;
  36244. incrementalLayerCount = 1;
  36245. }
  36246. else {
  36247. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  36248. }
  36249. if (!layer.__builtin__) {
  36250. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  36251. }
  36252. if (layer !== prevLayer) {
  36253. layer.__used = true;
  36254. if (layer.__startIndex !== i) {
  36255. layer.__dirty = true;
  36256. }
  36257. layer.__startIndex = i;
  36258. if (!layer.incremental) {
  36259. layer.__drawIndex = i;
  36260. }
  36261. else {
  36262. layer.__drawIndex = -1;
  36263. }
  36264. updatePrevLayer(i);
  36265. prevLayer = layer;
  36266. }
  36267. if ((el.__dirty & REDRAW_BIT) && !el.__inHover) {
  36268. layer.__dirty = true;
  36269. if (layer.incremental && layer.__drawIndex < 0) {
  36270. layer.__drawIndex = i;
  36271. }
  36272. }
  36273. }
  36274. updatePrevLayer(i);
  36275. this.eachBuiltinLayer(function (layer, z) {
  36276. if (!layer.__used && layer.getElementCount() > 0) {
  36277. layer.__dirty = true;
  36278. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  36279. }
  36280. if (layer.__dirty && layer.__drawIndex < 0) {
  36281. layer.__drawIndex = layer.__startIndex;
  36282. }
  36283. });
  36284. };
  36285. CanvasPainter.prototype.clear = function () {
  36286. this.eachBuiltinLayer(this._clearLayer);
  36287. return this;
  36288. };
  36289. CanvasPainter.prototype._clearLayer = function (layer) {
  36290. layer.clear();
  36291. };
  36292. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  36293. this._backgroundColor = backgroundColor;
  36294. each(this._layers, function (layer) {
  36295. layer.setUnpainted();
  36296. });
  36297. };
  36298. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  36299. if (config) {
  36300. var layerConfig = this._layerConfig;
  36301. if (!layerConfig[zlevel]) {
  36302. layerConfig[zlevel] = config;
  36303. }
  36304. else {
  36305. merge(layerConfig[zlevel], config, true);
  36306. }
  36307. for (var i = 0; i < this._zlevelList.length; i++) {
  36308. var _zlevel = this._zlevelList[i];
  36309. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  36310. var layer = this._layers[_zlevel];
  36311. merge(layer, layerConfig[zlevel], true);
  36312. }
  36313. }
  36314. }
  36315. };
  36316. CanvasPainter.prototype.delLayer = function (zlevel) {
  36317. var layers = this._layers;
  36318. var zlevelList = this._zlevelList;
  36319. var layer = layers[zlevel];
  36320. if (!layer) {
  36321. return;
  36322. }
  36323. layer.dom.parentNode.removeChild(layer.dom);
  36324. delete layers[zlevel];
  36325. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  36326. };
  36327. CanvasPainter.prototype.resize = function (width, height) {
  36328. if (!this._domRoot.style) {
  36329. if (width == null || height == null) {
  36330. return;
  36331. }
  36332. this._width = width;
  36333. this._height = height;
  36334. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  36335. }
  36336. else {
  36337. var domRoot = this._domRoot;
  36338. domRoot.style.display = 'none';
  36339. var opts = this._opts;
  36340. var root = this.root;
  36341. width != null && (opts.width = width);
  36342. height != null && (opts.height = height);
  36343. width = getSize(root, 0, opts);
  36344. height = getSize(root, 1, opts);
  36345. domRoot.style.display = '';
  36346. if (this._width !== width || height !== this._height) {
  36347. domRoot.style.width = width + 'px';
  36348. domRoot.style.height = height + 'px';
  36349. for (var id in this._layers) {
  36350. if (this._layers.hasOwnProperty(id)) {
  36351. this._layers[id].resize(width, height);
  36352. }
  36353. }
  36354. this.refresh(true);
  36355. }
  36356. this._width = width;
  36357. this._height = height;
  36358. }
  36359. return this;
  36360. };
  36361. CanvasPainter.prototype.clearLayer = function (zlevel) {
  36362. var layer = this._layers[zlevel];
  36363. if (layer) {
  36364. layer.clear();
  36365. }
  36366. };
  36367. CanvasPainter.prototype.dispose = function () {
  36368. this.root.innerHTML = '';
  36369. this.root =
  36370. this.storage =
  36371. this._domRoot =
  36372. this._layers = null;
  36373. };
  36374. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  36375. opts = opts || {};
  36376. if (this._singleCanvas && !this._compositeManually) {
  36377. return this._layers[CANVAS_ZLEVEL].dom;
  36378. }
  36379. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  36380. imageLayer.initContext();
  36381. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  36382. var ctx = imageLayer.ctx;
  36383. if (opts.pixelRatio <= this.dpr) {
  36384. this.refresh();
  36385. var width_1 = imageLayer.dom.width;
  36386. var height_1 = imageLayer.dom.height;
  36387. this.eachLayer(function (layer) {
  36388. if (layer.__builtin__) {
  36389. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  36390. }
  36391. else if (layer.renderToCanvas) {
  36392. ctx.save();
  36393. layer.renderToCanvas(ctx);
  36394. ctx.restore();
  36395. }
  36396. });
  36397. }
  36398. else {
  36399. var scope = {
  36400. inHover: false,
  36401. viewWidth: this._width,
  36402. viewHeight: this._height
  36403. };
  36404. var displayList = this.storage.getDisplayList(true);
  36405. for (var i = 0, len = displayList.length; i < len; i++) {
  36406. var el = displayList[i];
  36407. brush(ctx, el, scope, i === len - 1);
  36408. }
  36409. }
  36410. return imageLayer.dom;
  36411. };
  36412. CanvasPainter.prototype.getWidth = function () {
  36413. return this._width;
  36414. };
  36415. CanvasPainter.prototype.getHeight = function () {
  36416. return this._height;
  36417. };
  36418. return CanvasPainter;
  36419. }());
  36420. function install$1(registers) {
  36421. registers.registerPainter('canvas', CanvasPainter);
  36422. }
  36423. var LineSeriesModel =
  36424. /** @class */
  36425. function (_super) {
  36426. __extends(LineSeriesModel, _super);
  36427. function LineSeriesModel() {
  36428. var _this = _super !== null && _super.apply(this, arguments) || this;
  36429. _this.type = LineSeriesModel.type;
  36430. _this.hasSymbolVisual = true;
  36431. return _this;
  36432. }
  36433. LineSeriesModel.prototype.getInitialData = function (option) {
  36434. if ("development" !== 'production') {
  36435. var coordSys = option.coordinateSystem;
  36436. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  36437. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  36438. }
  36439. }
  36440. return createSeriesData(null, this, {
  36441. useEncodeDefaulter: true
  36442. });
  36443. };
  36444. LineSeriesModel.prototype.getLegendIcon = function (opt) {
  36445. var group = new Group();
  36446. var line = createSymbol('line', 0, opt.itemHeight / 2, opt.itemWidth, 0, opt.lineStyle.stroke, false);
  36447. group.add(line);
  36448. line.setStyle(opt.lineStyle);
  36449. var visualType = this.getData().getVisual('symbol');
  36450. var visualRotate = this.getData().getVisual('symbolRotate');
  36451. var symbolType = visualType === 'none' ? 'circle' : visualType; // Symbol size is 80% when there is a line
  36452. var size = opt.itemHeight * 0.8;
  36453. var symbol = createSymbol(symbolType, (opt.itemWidth - size) / 2, (opt.itemHeight - size) / 2, size, size, opt.itemStyle.fill);
  36454. group.add(symbol);
  36455. symbol.setStyle(opt.itemStyle);
  36456. var symbolRotate = opt.iconRotate === 'inherit' ? visualRotate : opt.iconRotate || 0;
  36457. symbol.rotation = symbolRotate * Math.PI / 180;
  36458. symbol.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  36459. if (symbolType.indexOf('empty') > -1) {
  36460. symbol.style.stroke = symbol.style.fill;
  36461. symbol.style.fill = '#fff';
  36462. symbol.style.lineWidth = 2;
  36463. }
  36464. return group;
  36465. };
  36466. LineSeriesModel.type = 'series.line';
  36467. LineSeriesModel.dependencies = ['grid', 'polar'];
  36468. LineSeriesModel.defaultOption = {
  36469. // zlevel: 0,
  36470. z: 3,
  36471. coordinateSystem: 'cartesian2d',
  36472. legendHoverLink: true,
  36473. clip: true,
  36474. label: {
  36475. position: 'top'
  36476. },
  36477. // itemStyle: {
  36478. // },
  36479. endLabel: {
  36480. show: false,
  36481. valueAnimation: true,
  36482. distance: 8
  36483. },
  36484. lineStyle: {
  36485. width: 2,
  36486. type: 'solid'
  36487. },
  36488. emphasis: {
  36489. scale: true
  36490. },
  36491. // areaStyle: {
  36492. // origin of areaStyle. Valid values:
  36493. // `'auto'/null/undefined`: from axisLine to data
  36494. // `'start'`: from min to data
  36495. // `'end'`: from data to max
  36496. // origin: 'auto'
  36497. // },
  36498. // false, 'start', 'end', 'middle'
  36499. step: false,
  36500. // Disabled if step is true
  36501. smooth: false,
  36502. smoothMonotone: null,
  36503. symbol: 'emptyCircle',
  36504. symbolSize: 4,
  36505. symbolRotate: null,
  36506. showSymbol: true,
  36507. // `false`: follow the label interval strategy.
  36508. // `true`: show all symbols.
  36509. // `'auto'`: If possible, show all symbols, otherwise
  36510. // follow the label interval strategy.
  36511. showAllSymbol: 'auto',
  36512. // Whether to connect break point.
  36513. connectNulls: false,
  36514. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  36515. sampling: 'none',
  36516. animationEasing: 'linear',
  36517. // Disable progressive
  36518. progressive: 0,
  36519. hoverLayerThreshold: Infinity,
  36520. universalTransition: {
  36521. divideShape: 'clone'
  36522. },
  36523. triggerLineEvent: false
  36524. };
  36525. return LineSeriesModel;
  36526. }(SeriesModel);
  36527. /**
  36528. * @return label string. Not null/undefined
  36529. */
  36530. function getDefaultLabel(data, dataIndex) {
  36531. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36532. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  36533. if (len === 1) {
  36534. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  36535. return rawVal != null ? rawVal + '' : null;
  36536. } else if (len) {
  36537. var vals = [];
  36538. for (var i = 0; i < labelDims.length; i++) {
  36539. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  36540. }
  36541. return vals.join(' ');
  36542. }
  36543. }
  36544. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  36545. var labelDims = data.mapDimensionsAll('defaultedLabel');
  36546. if (!isArray(interpolatedValue)) {
  36547. return interpolatedValue + '';
  36548. }
  36549. var vals = [];
  36550. for (var i = 0; i < labelDims.length; i++) {
  36551. var dimIndex = data.getDimensionIndex(labelDims[i]);
  36552. if (dimIndex >= 0) {
  36553. vals.push(interpolatedValue[dimIndex]);
  36554. }
  36555. }
  36556. return vals.join(' ');
  36557. }
  36558. var Symbol =
  36559. /** @class */
  36560. function (_super) {
  36561. __extends(Symbol, _super);
  36562. function Symbol(data, idx, seriesScope, opts) {
  36563. var _this = _super.call(this) || this;
  36564. _this.updateData(data, idx, seriesScope, opts);
  36565. return _this;
  36566. }
  36567. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  36568. // Remove paths created before
  36569. this.removeAll(); // let symbolPath = createSymbol(
  36570. // symbolType, -0.5, -0.5, 1, 1, color
  36571. // );
  36572. // If width/height are set too small (e.g., set to 1) on ios10
  36573. // and macOS Sierra, a circle stroke become a rect, no matter what
  36574. // the scale is set. So we set width/height as 2. See #4150.
  36575. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  36576. symbolPath.attr({
  36577. z2: 100,
  36578. culling: true,
  36579. scaleX: symbolSize[0] / 2,
  36580. scaleY: symbolSize[1] / 2
  36581. }); // Rewrite drift method
  36582. symbolPath.drift = driftSymbol;
  36583. this._symbolType = symbolType;
  36584. this.add(symbolPath);
  36585. };
  36586. /**
  36587. * Stop animation
  36588. * @param {boolean} toLastFrame
  36589. */
  36590. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  36591. this.childAt(0).stopAnimation(null, toLastFrame);
  36592. };
  36593. Symbol.prototype.getSymbolType = function () {
  36594. return this._symbolType;
  36595. };
  36596. /**
  36597. * FIXME:
  36598. * Caution: This method breaks the encapsulation of this module,
  36599. * but it indeed brings convenience. So do not use the method
  36600. * unless you detailedly know all the implements of `Symbol`,
  36601. * especially animation.
  36602. *
  36603. * Get symbol path element.
  36604. */
  36605. Symbol.prototype.getSymbolPath = function () {
  36606. return this.childAt(0);
  36607. };
  36608. /**
  36609. * Highlight symbol
  36610. */
  36611. Symbol.prototype.highlight = function () {
  36612. enterEmphasis(this.childAt(0));
  36613. };
  36614. /**
  36615. * Downplay symbol
  36616. */
  36617. Symbol.prototype.downplay = function () {
  36618. leaveEmphasis(this.childAt(0));
  36619. };
  36620. /**
  36621. * @param {number} zlevel
  36622. * @param {number} z
  36623. */
  36624. Symbol.prototype.setZ = function (zlevel, z) {
  36625. var symbolPath = this.childAt(0);
  36626. symbolPath.zlevel = zlevel;
  36627. symbolPath.z = z;
  36628. };
  36629. Symbol.prototype.setDraggable = function (draggable, hasCursorOption) {
  36630. var symbolPath = this.childAt(0);
  36631. symbolPath.draggable = draggable;
  36632. symbolPath.cursor = !hasCursorOption && draggable ? 'move' : symbolPath.cursor;
  36633. };
  36634. /**
  36635. * Update symbol properties
  36636. */
  36637. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  36638. this.silent = false;
  36639. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36640. var seriesModel = data.hostModel;
  36641. var symbolSize = Symbol.getSymbolSize(data, idx);
  36642. var isInit = symbolType !== this._symbolType;
  36643. var disableAnimation = opts && opts.disableAnimation;
  36644. if (isInit) {
  36645. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  36646. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  36647. } else {
  36648. var symbolPath = this.childAt(0);
  36649. symbolPath.silent = false;
  36650. var target = {
  36651. scaleX: symbolSize[0] / 2,
  36652. scaleY: symbolSize[1] / 2
  36653. };
  36654. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  36655. saveOldStyle(symbolPath);
  36656. }
  36657. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  36658. if (isInit) {
  36659. var symbolPath = this.childAt(0);
  36660. if (!disableAnimation) {
  36661. var target = {
  36662. scaleX: this._sizeX,
  36663. scaleY: this._sizeY,
  36664. style: {
  36665. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  36666. opacity: symbolPath.style.opacity
  36667. }
  36668. };
  36669. symbolPath.scaleX = symbolPath.scaleY = 0;
  36670. symbolPath.style.opacity = 0;
  36671. initProps(symbolPath, target, seriesModel, idx);
  36672. }
  36673. }
  36674. if (disableAnimation) {
  36675. // Must stop leave transition manually if don't call initProps or updateProps.
  36676. this.childAt(0).stopAnimation('leave');
  36677. }
  36678. };
  36679. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  36680. var symbolPath = this.childAt(0);
  36681. var seriesModel = data.hostModel;
  36682. var emphasisItemStyle;
  36683. var blurItemStyle;
  36684. var selectItemStyle;
  36685. var focus;
  36686. var blurScope;
  36687. var emphasisDisabled;
  36688. var labelStatesModels;
  36689. var hoverScale;
  36690. var cursorStyle;
  36691. if (seriesScope) {
  36692. emphasisItemStyle = seriesScope.emphasisItemStyle;
  36693. blurItemStyle = seriesScope.blurItemStyle;
  36694. selectItemStyle = seriesScope.selectItemStyle;
  36695. focus = seriesScope.focus;
  36696. blurScope = seriesScope.blurScope;
  36697. labelStatesModels = seriesScope.labelStatesModels;
  36698. hoverScale = seriesScope.hoverScale;
  36699. cursorStyle = seriesScope.cursorStyle;
  36700. emphasisDisabled = seriesScope.emphasisDisabled;
  36701. }
  36702. if (!seriesScope || data.hasItemOption) {
  36703. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  36704. var emphasisModel = itemModel.getModel('emphasis');
  36705. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  36706. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  36707. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  36708. focus = emphasisModel.get('focus');
  36709. blurScope = emphasisModel.get('blurScope');
  36710. emphasisDisabled = emphasisModel.get('disabled');
  36711. labelStatesModels = getLabelStatesModels(itemModel);
  36712. hoverScale = emphasisModel.getShallow('scale');
  36713. cursorStyle = itemModel.getShallow('cursor');
  36714. }
  36715. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  36716. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  36717. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  36718. if (symbolOffset) {
  36719. symbolPath.x = symbolOffset[0];
  36720. symbolPath.y = symbolOffset[1];
  36721. }
  36722. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  36723. var symbolStyle = data.getItemVisual(idx, 'style');
  36724. var visualColor = symbolStyle.fill;
  36725. if (symbolPath instanceof ZRImage) {
  36726. var pathStyle = symbolPath.style;
  36727. symbolPath.useStyle(extend({
  36728. // TODO other properties like x, y ?
  36729. image: pathStyle.image,
  36730. x: pathStyle.x,
  36731. y: pathStyle.y,
  36732. width: pathStyle.width,
  36733. height: pathStyle.height
  36734. }, symbolStyle));
  36735. } else {
  36736. if (symbolPath.__isEmptyBrush) {
  36737. // fill and stroke will be swapped if it's empty.
  36738. // So we cloned a new style to avoid it affecting the original style in visual storage.
  36739. // TODO Better implementation. No empty logic!
  36740. symbolPath.useStyle(extend({}, symbolStyle));
  36741. } else {
  36742. symbolPath.useStyle(symbolStyle);
  36743. } // Disable decal because symbol scale will been applied on the decal.
  36744. symbolPath.style.decal = null;
  36745. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  36746. symbolPath.style.strokeNoScale = true;
  36747. }
  36748. var liftZ = data.getItemVisual(idx, 'liftZ');
  36749. var z2Origin = this._z2;
  36750. if (liftZ != null) {
  36751. if (z2Origin == null) {
  36752. this._z2 = symbolPath.z2;
  36753. symbolPath.z2 += liftZ;
  36754. }
  36755. } else if (z2Origin != null) {
  36756. symbolPath.z2 = z2Origin;
  36757. this._z2 = null;
  36758. }
  36759. var useNameLabel = opts && opts.useNameLabel;
  36760. setLabelStyle(symbolPath, labelStatesModels, {
  36761. labelFetcher: seriesModel,
  36762. labelDataIndex: idx,
  36763. defaultText: getLabelDefaultText,
  36764. inheritColor: visualColor,
  36765. defaultOpacity: symbolStyle.opacity
  36766. }); // Do not execute util needed.
  36767. function getLabelDefaultText(idx) {
  36768. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  36769. }
  36770. this._sizeX = symbolSize[0] / 2;
  36771. this._sizeY = symbolSize[1] / 2;
  36772. var emphasisState = symbolPath.ensureState('emphasis');
  36773. emphasisState.style = emphasisItemStyle;
  36774. symbolPath.ensureState('select').style = selectItemStyle;
  36775. symbolPath.ensureState('blur').style = blurItemStyle; // null / undefined / true means to use default strategy.
  36776. // 0 / false / negative number / NaN / Infinity means no scale.
  36777. var scaleRatio = hoverScale == null || hoverScale === true ? Math.max(1.1, 3 / this._sizeY) // PENDING: restrict hoverScale > 1? It seems unreasonable to scale down
  36778. : isFinite(hoverScale) && hoverScale > 0 ? +hoverScale : 1; // always set scale to allow resetting
  36779. emphasisState.scaleX = this._sizeX * scaleRatio;
  36780. emphasisState.scaleY = this._sizeY * scaleRatio;
  36781. this.setSymbolScale(1);
  36782. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  36783. };
  36784. Symbol.prototype.setSymbolScale = function (scale) {
  36785. this.scaleX = this.scaleY = scale;
  36786. };
  36787. Symbol.prototype.fadeOut = function (cb, seriesModel, opt) {
  36788. var symbolPath = this.childAt(0);
  36789. var dataIndex = getECData(this).dataIndex;
  36790. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  36791. this.silent = symbolPath.silent = true; // Not show text when animating
  36792. if (opt && opt.fadeLabel) {
  36793. var textContent = symbolPath.getTextContent();
  36794. if (textContent) {
  36795. removeElement(textContent, {
  36796. style: {
  36797. opacity: 0
  36798. }
  36799. }, seriesModel, {
  36800. dataIndex: dataIndex,
  36801. removeOpt: animationOpt,
  36802. cb: function () {
  36803. symbolPath.removeTextContent();
  36804. }
  36805. });
  36806. }
  36807. } else {
  36808. symbolPath.removeTextContent();
  36809. }
  36810. removeElement(symbolPath, {
  36811. style: {
  36812. opacity: 0
  36813. },
  36814. scaleX: 0,
  36815. scaleY: 0
  36816. }, seriesModel, {
  36817. dataIndex: dataIndex,
  36818. cb: cb,
  36819. removeOpt: animationOpt
  36820. });
  36821. };
  36822. Symbol.getSymbolSize = function (data, idx) {
  36823. return normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  36824. };
  36825. return Symbol;
  36826. }(Group);
  36827. function driftSymbol(dx, dy) {
  36828. this.parent.drift(dx, dy);
  36829. }
  36830. function symbolNeedsDraw(data, point, idx, opt) {
  36831. 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
  36832. // the symbol element shape. We use the same clip shape here as
  36833. // the line clip.
  36834. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  36835. }
  36836. function normalizeUpdateOpt(opt) {
  36837. if (opt != null && !isObject(opt)) {
  36838. opt = {
  36839. isIgnore: opt
  36840. };
  36841. }
  36842. return opt || {};
  36843. }
  36844. function makeSeriesScope(data) {
  36845. var seriesModel = data.hostModel;
  36846. var emphasisModel = seriesModel.getModel('emphasis');
  36847. return {
  36848. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  36849. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  36850. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  36851. focus: emphasisModel.get('focus'),
  36852. blurScope: emphasisModel.get('blurScope'),
  36853. emphasisDisabled: emphasisModel.get('disabled'),
  36854. hoverScale: emphasisModel.get('scale'),
  36855. labelStatesModels: getLabelStatesModels(seriesModel),
  36856. cursorStyle: seriesModel.get('cursor')
  36857. };
  36858. }
  36859. var SymbolDraw =
  36860. /** @class */
  36861. function () {
  36862. function SymbolDraw(SymbolCtor) {
  36863. this.group = new Group();
  36864. this._SymbolCtor = SymbolCtor || Symbol;
  36865. }
  36866. /**
  36867. * Update symbols draw by new data
  36868. */
  36869. SymbolDraw.prototype.updateData = function (data, opt) {
  36870. // Remove progressive els.
  36871. this._progressiveEls = null;
  36872. opt = normalizeUpdateOpt(opt);
  36873. var group = this.group;
  36874. var seriesModel = data.hostModel;
  36875. var oldData = this._data;
  36876. var SymbolCtor = this._SymbolCtor;
  36877. var disableAnimation = opt.disableAnimation;
  36878. var seriesScope = makeSeriesScope(data);
  36879. var symbolUpdateOpt = {
  36880. disableAnimation: disableAnimation
  36881. };
  36882. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  36883. return data.getItemLayout(idx);
  36884. }; // There is no oldLineData only when first rendering or switching from
  36885. // stream mode to normal mode, where previous elements should be removed.
  36886. if (!oldData) {
  36887. group.removeAll();
  36888. }
  36889. data.diff(oldData).add(function (newIdx) {
  36890. var point = getSymbolPoint(newIdx);
  36891. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  36892. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36893. symbolEl.setPosition(point);
  36894. data.setItemGraphicEl(newIdx, symbolEl);
  36895. group.add(symbolEl);
  36896. }
  36897. }).update(function (newIdx, oldIdx) {
  36898. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  36899. var point = getSymbolPoint(newIdx);
  36900. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  36901. group.remove(symbolEl);
  36902. return;
  36903. }
  36904. var newSymbolType = data.getItemVisual(newIdx, 'symbol') || 'circle';
  36905. var oldSymbolType = symbolEl && symbolEl.getSymbolType && symbolEl.getSymbolType();
  36906. if (!symbolEl // Create a new if symbol type changed.
  36907. || oldSymbolType && oldSymbolType !== newSymbolType) {
  36908. group.remove(symbolEl);
  36909. symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  36910. symbolEl.setPosition(point);
  36911. } else {
  36912. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  36913. var target = {
  36914. x: point[0],
  36915. y: point[1]
  36916. };
  36917. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  36918. } // Add back
  36919. group.add(symbolEl);
  36920. data.setItemGraphicEl(newIdx, symbolEl);
  36921. }).remove(function (oldIdx) {
  36922. var el = oldData.getItemGraphicEl(oldIdx);
  36923. el && el.fadeOut(function () {
  36924. group.remove(el);
  36925. }, seriesModel);
  36926. }).execute();
  36927. this._getSymbolPoint = getSymbolPoint;
  36928. this._data = data;
  36929. };
  36930. SymbolDraw.prototype.updateLayout = function () {
  36931. var _this = this;
  36932. var data = this._data;
  36933. if (data) {
  36934. // Not use animation
  36935. data.eachItemGraphicEl(function (el, idx) {
  36936. var point = _this._getSymbolPoint(idx);
  36937. el.setPosition(point);
  36938. el.markRedraw();
  36939. });
  36940. }
  36941. };
  36942. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  36943. this._seriesScope = makeSeriesScope(data);
  36944. this._data = null;
  36945. this.group.removeAll();
  36946. };
  36947. /**
  36948. * Update symbols draw by new data
  36949. */
  36950. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  36951. // Clear
  36952. this._progressiveEls = [];
  36953. opt = normalizeUpdateOpt(opt);
  36954. function updateIncrementalAndHover(el) {
  36955. if (!el.isGroup) {
  36956. el.incremental = true;
  36957. el.ensureState('emphasis').hoverLayer = true;
  36958. }
  36959. }
  36960. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  36961. var point = data.getItemLayout(idx);
  36962. if (symbolNeedsDraw(data, point, idx, opt)) {
  36963. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  36964. el.traverse(updateIncrementalAndHover);
  36965. el.setPosition(point);
  36966. this.group.add(el);
  36967. data.setItemGraphicEl(idx, el);
  36968. this._progressiveEls.push(el);
  36969. }
  36970. }
  36971. };
  36972. SymbolDraw.prototype.eachRendered = function (cb) {
  36973. traverseElements(this._progressiveEls || this.group, cb);
  36974. };
  36975. SymbolDraw.prototype.remove = function (enableAnimation) {
  36976. var group = this.group;
  36977. var data = this._data; // Incremental model do not have this._data.
  36978. if (data && enableAnimation) {
  36979. data.eachItemGraphicEl(function (el) {
  36980. el.fadeOut(function () {
  36981. group.remove(el);
  36982. }, data.hostModel);
  36983. });
  36984. } else {
  36985. group.removeAll();
  36986. }
  36987. };
  36988. return SymbolDraw;
  36989. }();
  36990. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  36991. var baseAxis = coordSys.getBaseAxis();
  36992. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36993. var valueStart = getValueStart(valueAxis, valueOrigin);
  36994. var baseAxisDim = baseAxis.dim;
  36995. var valueAxisDim = valueAxis.dim;
  36996. var valueDim = data.mapDimension(valueAxisDim);
  36997. var baseDim = data.mapDimension(baseAxisDim);
  36998. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  36999. var dims = map(coordSys.dimensions, function (coordDim) {
  37000. return data.mapDimension(coordDim);
  37001. });
  37002. var stacked = false;
  37003. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  37004. if (isDimensionStacked(data, dims[0]
  37005. /* , dims[1] */
  37006. )) {
  37007. // jshint ignore:line
  37008. stacked = true;
  37009. dims[0] = stackResultDim;
  37010. }
  37011. if (isDimensionStacked(data, dims[1]
  37012. /* , dims[0] */
  37013. )) {
  37014. // jshint ignore:line
  37015. stacked = true;
  37016. dims[1] = stackResultDim;
  37017. }
  37018. return {
  37019. dataDimsForPoint: dims,
  37020. valueStart: valueStart,
  37021. valueAxisDim: valueAxisDim,
  37022. baseAxisDim: baseAxisDim,
  37023. stacked: !!stacked,
  37024. valueDim: valueDim,
  37025. baseDim: baseDim,
  37026. baseDataOffset: baseDataOffset,
  37027. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  37028. };
  37029. }
  37030. function getValueStart(valueAxis, valueOrigin) {
  37031. var valueStart = 0;
  37032. var extent = valueAxis.scale.getExtent();
  37033. if (valueOrigin === 'start') {
  37034. valueStart = extent[0];
  37035. } else if (valueOrigin === 'end') {
  37036. valueStart = extent[1];
  37037. } // If origin is specified as a number, use it as
  37038. // valueStart directly
  37039. else if (isNumber(valueOrigin) && !isNaN(valueOrigin)) {
  37040. valueStart = valueOrigin;
  37041. } // auto
  37042. else {
  37043. // Both positive
  37044. if (extent[0] > 0) {
  37045. valueStart = extent[0];
  37046. } // Both negative
  37047. else if (extent[1] < 0) {
  37048. valueStart = extent[1];
  37049. } // If is one positive, and one negative, onZero shall be true
  37050. }
  37051. return valueStart;
  37052. }
  37053. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  37054. var value = NaN;
  37055. if (dataCoordInfo.stacked) {
  37056. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  37057. }
  37058. if (isNaN(value)) {
  37059. value = dataCoordInfo.valueStart;
  37060. }
  37061. var baseDataOffset = dataCoordInfo.baseDataOffset;
  37062. var stackedData = [];
  37063. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  37064. stackedData[1 - baseDataOffset] = value;
  37065. return coordSys.dataToPoint(stackedData);
  37066. }
  37067. function diffData(oldData, newData) {
  37068. var diffResult = [];
  37069. newData.diff(oldData).add(function (idx) {
  37070. diffResult.push({
  37071. cmd: '+',
  37072. idx: idx
  37073. });
  37074. }).update(function (newIdx, oldIdx) {
  37075. diffResult.push({
  37076. cmd: '=',
  37077. idx: oldIdx,
  37078. idx1: newIdx
  37079. });
  37080. }).remove(function (idx) {
  37081. diffResult.push({
  37082. cmd: '-',
  37083. idx: idx
  37084. });
  37085. }).execute();
  37086. return diffResult;
  37087. }
  37088. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  37089. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  37090. // let oldIdList = oldData.mapArray(oldData.getId);
  37091. // convertToIntId(newIdList, oldIdList);
  37092. // // FIXME One data ?
  37093. // diff = arrayDiff(oldIdList, newIdList);
  37094. var currPoints = [];
  37095. var nextPoints = []; // Points for stacking base line
  37096. var currStackedPoints = [];
  37097. var nextStackedPoints = [];
  37098. var status = [];
  37099. var sortedIndices = [];
  37100. var rawIndices = [];
  37101. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin); // const oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  37102. var oldPoints = oldData.getLayout('points') || [];
  37103. var newPoints = newData.getLayout('points') || [];
  37104. for (var i = 0; i < diff.length; i++) {
  37105. var diffItem = diff[i];
  37106. var pointAdded = true;
  37107. var oldIdx2 = void 0;
  37108. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  37109. // Which is in case remvoing or add more than one data in the tail or head
  37110. switch (diffItem.cmd) {
  37111. case '=':
  37112. oldIdx2 = diffItem.idx * 2;
  37113. newIdx2 = diffItem.idx1 * 2;
  37114. var currentX = oldPoints[oldIdx2];
  37115. var currentY = oldPoints[oldIdx2 + 1];
  37116. var nextX = newPoints[newIdx2];
  37117. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  37118. if (isNaN(currentX) || isNaN(currentY)) {
  37119. currentX = nextX;
  37120. currentY = nextY;
  37121. }
  37122. currPoints.push(currentX, currentY);
  37123. nextPoints.push(nextX, nextY);
  37124. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  37125. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37126. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  37127. break;
  37128. case '+':
  37129. var newIdx = diffItem.idx;
  37130. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  37131. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  37132. newIdx2 = newIdx * 2;
  37133. currPoints.push(oldPt[0], oldPt[1]);
  37134. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  37135. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  37136. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  37137. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  37138. rawIndices.push(newData.getRawIndex(newIdx));
  37139. break;
  37140. case '-':
  37141. pointAdded = false;
  37142. } // Original indices
  37143. if (pointAdded) {
  37144. status.push(diffItem);
  37145. sortedIndices.push(sortedIndices.length);
  37146. }
  37147. } // Diff result may be crossed if all items are changed
  37148. // Sort by data index
  37149. sortedIndices.sort(function (a, b) {
  37150. return rawIndices[a] - rawIndices[b];
  37151. });
  37152. var len = currPoints.length;
  37153. var sortedCurrPoints = createFloat32Array(len);
  37154. var sortedNextPoints = createFloat32Array(len);
  37155. var sortedCurrStackedPoints = createFloat32Array(len);
  37156. var sortedNextStackedPoints = createFloat32Array(len);
  37157. var sortedStatus = [];
  37158. for (var i = 0; i < sortedIndices.length; i++) {
  37159. var idx = sortedIndices[i];
  37160. var i2 = i * 2;
  37161. var idx2 = idx * 2;
  37162. sortedCurrPoints[i2] = currPoints[idx2];
  37163. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  37164. sortedNextPoints[i2] = nextPoints[idx2];
  37165. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  37166. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  37167. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  37168. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  37169. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  37170. sortedStatus[i] = status[idx];
  37171. }
  37172. return {
  37173. current: sortedCurrPoints,
  37174. next: sortedNextPoints,
  37175. stackedOnCurrent: sortedCurrStackedPoints,
  37176. stackedOnNext: sortedNextStackedPoints,
  37177. status: sortedStatus
  37178. };
  37179. }
  37180. var mathMin$5 = Math.min;
  37181. var mathMax$5 = Math.max;
  37182. function isPointNull(x, y) {
  37183. return isNaN(x) || isNaN(y);
  37184. }
  37185. /**
  37186. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  37187. * situations. This should be used when points are non-monotone neither in x or
  37188. * y dimension.
  37189. */
  37190. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  37191. var prevX;
  37192. var prevY;
  37193. var cpx0;
  37194. var cpy0;
  37195. var cpx1;
  37196. var cpy1;
  37197. var idx = start;
  37198. var k = 0;
  37199. for (; k < segLen; k++) {
  37200. var x = points[idx * 2];
  37201. var y = points[idx * 2 + 1];
  37202. if (idx >= allLen || idx < 0) {
  37203. break;
  37204. }
  37205. if (isPointNull(x, y)) {
  37206. if (connectNulls) {
  37207. idx += dir;
  37208. continue;
  37209. }
  37210. break;
  37211. }
  37212. if (idx === start) {
  37213. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  37214. cpx0 = x;
  37215. cpy0 = y;
  37216. } else {
  37217. var dx = x - prevX;
  37218. var dy = y - prevY; // Ignore tiny segment.
  37219. if (dx * dx + dy * dy < 0.5) {
  37220. idx += dir;
  37221. continue;
  37222. }
  37223. if (smooth > 0) {
  37224. var nextIdx = idx + dir;
  37225. var nextX = points[nextIdx * 2];
  37226. var nextY = points[nextIdx * 2 + 1]; // Ignore duplicate point
  37227. while (nextX === x && nextY === y && k < segLen) {
  37228. k++;
  37229. nextIdx += dir;
  37230. idx += dir;
  37231. nextX = points[nextIdx * 2];
  37232. nextY = points[nextIdx * 2 + 1];
  37233. x = points[idx * 2];
  37234. y = points[idx * 2 + 1];
  37235. dx = x - prevX;
  37236. dy = y - prevY;
  37237. }
  37238. var tmpK = k + 1;
  37239. if (connectNulls) {
  37240. // Find next point not null
  37241. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  37242. tmpK++;
  37243. nextIdx += dir;
  37244. nextX = points[nextIdx * 2];
  37245. nextY = points[nextIdx * 2 + 1];
  37246. }
  37247. }
  37248. var ratioNextSeg = 0.5;
  37249. var vx = 0;
  37250. var vy = 0;
  37251. var nextCpx0 = void 0;
  37252. var nextCpy0 = void 0; // Is last point
  37253. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  37254. cpx1 = x;
  37255. cpy1 = y;
  37256. } else {
  37257. vx = nextX - prevX;
  37258. vy = nextY - prevY;
  37259. var dx0 = x - prevX;
  37260. var dx1 = nextX - x;
  37261. var dy0 = y - prevY;
  37262. var dy1 = nextY - y;
  37263. var lenPrevSeg = void 0;
  37264. var lenNextSeg = void 0;
  37265. if (smoothMonotone === 'x') {
  37266. lenPrevSeg = Math.abs(dx0);
  37267. lenNextSeg = Math.abs(dx1);
  37268. var dir_1 = vx > 0 ? 1 : -1;
  37269. cpx1 = x - dir_1 * lenPrevSeg * smooth;
  37270. cpy1 = y;
  37271. nextCpx0 = x + dir_1 * lenNextSeg * smooth;
  37272. nextCpy0 = y;
  37273. } else if (smoothMonotone === 'y') {
  37274. lenPrevSeg = Math.abs(dy0);
  37275. lenNextSeg = Math.abs(dy1);
  37276. var dir_2 = vy > 0 ? 1 : -1;
  37277. cpx1 = x;
  37278. cpy1 = y - dir_2 * lenPrevSeg * smooth;
  37279. nextCpx0 = x;
  37280. nextCpy0 = y + dir_2 * lenNextSeg * smooth;
  37281. } else {
  37282. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  37283. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  37284. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  37285. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  37286. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  37287. nextCpx0 = x + vx * smooth * ratioNextSeg;
  37288. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  37289. // Avoid exceeding extreme after smoothing.
  37290. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  37291. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  37292. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  37293. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  37294. vx = nextCpx0 - x;
  37295. vy = nextCpy0 - y;
  37296. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  37297. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  37298. // Avoid exceeding extreme after smoothing.
  37299. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  37300. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  37301. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  37302. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  37303. vx = x - cpx1;
  37304. vy = y - cpy1;
  37305. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  37306. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  37307. }
  37308. }
  37309. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  37310. cpx0 = nextCpx0;
  37311. cpy0 = nextCpy0;
  37312. } else {
  37313. ctx.lineTo(x, y);
  37314. }
  37315. }
  37316. prevX = x;
  37317. prevY = y;
  37318. idx += dir;
  37319. }
  37320. return k;
  37321. }
  37322. var ECPolylineShape =
  37323. /** @class */
  37324. function () {
  37325. function ECPolylineShape() {
  37326. this.smooth = 0;
  37327. this.smoothConstraint = true;
  37328. }
  37329. return ECPolylineShape;
  37330. }();
  37331. var ECPolyline =
  37332. /** @class */
  37333. function (_super) {
  37334. __extends(ECPolyline, _super);
  37335. function ECPolyline(opts) {
  37336. var _this = _super.call(this, opts) || this;
  37337. _this.type = 'ec-polyline';
  37338. return _this;
  37339. }
  37340. ECPolyline.prototype.getDefaultStyle = function () {
  37341. return {
  37342. stroke: '#000',
  37343. fill: null
  37344. };
  37345. };
  37346. ECPolyline.prototype.getDefaultShape = function () {
  37347. return new ECPolylineShape();
  37348. };
  37349. ECPolyline.prototype.buildPath = function (ctx, shape) {
  37350. var points = shape.points;
  37351. var i = 0;
  37352. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  37353. if (shape.connectNulls) {
  37354. // Must remove first and last null values avoid draw error in polygon
  37355. for (; len > 0; len--) {
  37356. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37357. break;
  37358. }
  37359. }
  37360. for (; i < len; i++) {
  37361. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37362. break;
  37363. }
  37364. }
  37365. }
  37366. while (i < len) {
  37367. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  37368. }
  37369. };
  37370. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  37371. if (!this.path) {
  37372. this.createPathProxy();
  37373. this.buildPath(this.path, this.shape);
  37374. }
  37375. var path = this.path;
  37376. var data = path.data;
  37377. var CMD = PathProxy.CMD;
  37378. var x0;
  37379. var y0;
  37380. var isDimX = dim === 'x';
  37381. var roots = [];
  37382. for (var i = 0; i < data.length;) {
  37383. var cmd = data[i++];
  37384. var x = void 0;
  37385. var y = void 0;
  37386. var x2 = void 0;
  37387. var y2 = void 0;
  37388. var x3 = void 0;
  37389. var y3 = void 0;
  37390. var t = void 0;
  37391. switch (cmd) {
  37392. case CMD.M:
  37393. x0 = data[i++];
  37394. y0 = data[i++];
  37395. break;
  37396. case CMD.L:
  37397. x = data[i++];
  37398. y = data[i++];
  37399. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  37400. if (t <= 1 && t >= 0) {
  37401. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  37402. return isDimX ? [xOrY, val] : [val, xOrY];
  37403. }
  37404. x0 = x;
  37405. y0 = y;
  37406. break;
  37407. case CMD.C:
  37408. x = data[i++];
  37409. y = data[i++];
  37410. x2 = data[i++];
  37411. y2 = data[i++];
  37412. x3 = data[i++];
  37413. y3 = data[i++];
  37414. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  37415. if (nRoot > 0) {
  37416. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  37417. var t_1 = roots[i_1];
  37418. if (t_1 <= 1 && t_1 >= 0) {
  37419. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  37420. return isDimX ? [xOrY, val] : [val, xOrY];
  37421. }
  37422. }
  37423. }
  37424. x0 = x3;
  37425. y0 = y3;
  37426. break;
  37427. }
  37428. }
  37429. };
  37430. return ECPolyline;
  37431. }(Path);
  37432. var ECPolygonShape =
  37433. /** @class */
  37434. function (_super) {
  37435. __extends(ECPolygonShape, _super);
  37436. function ECPolygonShape() {
  37437. return _super !== null && _super.apply(this, arguments) || this;
  37438. }
  37439. return ECPolygonShape;
  37440. }(ECPolylineShape);
  37441. var ECPolygon =
  37442. /** @class */
  37443. function (_super) {
  37444. __extends(ECPolygon, _super);
  37445. function ECPolygon(opts) {
  37446. var _this = _super.call(this, opts) || this;
  37447. _this.type = 'ec-polygon';
  37448. return _this;
  37449. }
  37450. ECPolygon.prototype.getDefaultShape = function () {
  37451. return new ECPolygonShape();
  37452. };
  37453. ECPolygon.prototype.buildPath = function (ctx, shape) {
  37454. var points = shape.points;
  37455. var stackedOnPoints = shape.stackedOnPoints;
  37456. var i = 0;
  37457. var len = points.length / 2;
  37458. var smoothMonotone = shape.smoothMonotone;
  37459. if (shape.connectNulls) {
  37460. // Must remove first and last null values avoid draw error in polygon
  37461. for (; len > 0; len--) {
  37462. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  37463. break;
  37464. }
  37465. }
  37466. for (; i < len; i++) {
  37467. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  37468. break;
  37469. }
  37470. }
  37471. }
  37472. while (i < len) {
  37473. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  37474. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  37475. i += k + 1;
  37476. ctx.closePath();
  37477. }
  37478. };
  37479. return ECPolygon;
  37480. }(Path);
  37481. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  37482. var rect = cartesian.getArea();
  37483. var x = rect.x;
  37484. var y = rect.y;
  37485. var width = rect.width;
  37486. var height = rect.height;
  37487. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  37488. x -= lineWidth / 2;
  37489. y -= lineWidth / 2;
  37490. width += lineWidth;
  37491. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  37492. x = Math.floor(x);
  37493. width = Math.round(width);
  37494. var clipPath = new Rect({
  37495. shape: {
  37496. x: x,
  37497. y: y,
  37498. width: width,
  37499. height: height
  37500. }
  37501. });
  37502. if (hasAnimation) {
  37503. var baseAxis = cartesian.getBaseAxis();
  37504. var isHorizontal = baseAxis.isHorizontal();
  37505. var isAxisInversed = baseAxis.inverse;
  37506. if (isHorizontal) {
  37507. if (isAxisInversed) {
  37508. clipPath.shape.x += width;
  37509. }
  37510. clipPath.shape.width = 0;
  37511. } else {
  37512. if (!isAxisInversed) {
  37513. clipPath.shape.y += height;
  37514. }
  37515. clipPath.shape.height = 0;
  37516. }
  37517. var duringCb = isFunction(during) ? function (percent) {
  37518. during(percent, clipPath);
  37519. } : null;
  37520. initProps(clipPath, {
  37521. shape: {
  37522. width: width,
  37523. height: height,
  37524. x: x,
  37525. y: y
  37526. }
  37527. }, seriesModel, null, done, duringCb);
  37528. }
  37529. return clipPath;
  37530. }
  37531. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  37532. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  37533. var r0 = round(sectorArea.r0, 1);
  37534. var r = round(sectorArea.r, 1);
  37535. var clipPath = new Sector({
  37536. shape: {
  37537. cx: round(polar.cx, 1),
  37538. cy: round(polar.cy, 1),
  37539. r0: r0,
  37540. r: r,
  37541. startAngle: sectorArea.startAngle,
  37542. endAngle: sectorArea.endAngle,
  37543. clockwise: sectorArea.clockwise
  37544. }
  37545. });
  37546. if (hasAnimation) {
  37547. var isRadial = polar.getBaseAxis().dim === 'angle';
  37548. if (isRadial) {
  37549. clipPath.shape.endAngle = sectorArea.startAngle;
  37550. } else {
  37551. clipPath.shape.r = r0;
  37552. }
  37553. initProps(clipPath, {
  37554. shape: {
  37555. endAngle: sectorArea.endAngle,
  37556. r: r
  37557. }
  37558. }, seriesModel);
  37559. }
  37560. return clipPath;
  37561. }
  37562. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  37563. if (!coordSys) {
  37564. return null;
  37565. } else if (coordSys.type === 'polar') {
  37566. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37567. } else if (coordSys.type === 'cartesian2d') {
  37568. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  37569. }
  37570. return null;
  37571. }
  37572. /*
  37573. * Licensed to the Apache Software Foundation (ASF) under one
  37574. * or more contributor license agreements. See the NOTICE file
  37575. * distributed with this work for additional information
  37576. * regarding copyright ownership. The ASF licenses this file
  37577. * to you under the Apache License, Version 2.0 (the
  37578. * "License"); you may not use this file except in compliance
  37579. * with the License. You may obtain a copy of the License at
  37580. *
  37581. * http://www.apache.org/licenses/LICENSE-2.0
  37582. *
  37583. * Unless required by applicable law or agreed to in writing,
  37584. * software distributed under the License is distributed on an
  37585. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37586. * KIND, either express or implied. See the License for the
  37587. * specific language governing permissions and limitations
  37588. * under the License.
  37589. */
  37590. /**
  37591. * AUTO-GENERATED FILE. DO NOT MODIFY.
  37592. */
  37593. /*
  37594. * Licensed to the Apache Software Foundation (ASF) under one
  37595. * or more contributor license agreements. See the NOTICE file
  37596. * distributed with this work for additional information
  37597. * regarding copyright ownership. The ASF licenses this file
  37598. * to you under the Apache License, Version 2.0 (the
  37599. * "License"); you may not use this file except in compliance
  37600. * with the License. You may obtain a copy of the License at
  37601. *
  37602. * http://www.apache.org/licenses/LICENSE-2.0
  37603. *
  37604. * Unless required by applicable law or agreed to in writing,
  37605. * software distributed under the License is distributed on an
  37606. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37607. * KIND, either express or implied. See the License for the
  37608. * specific language governing permissions and limitations
  37609. * under the License.
  37610. */
  37611. function isCoordinateSystemType(coordSys, type) {
  37612. return coordSys.type === type;
  37613. }
  37614. function isPointsSame(points1, points2) {
  37615. if (points1.length !== points2.length) {
  37616. return;
  37617. }
  37618. for (var i = 0; i < points1.length; i++) {
  37619. if (points1[i] !== points2[i]) {
  37620. return;
  37621. }
  37622. }
  37623. return true;
  37624. }
  37625. function bboxFromPoints(points) {
  37626. var minX = Infinity;
  37627. var minY = Infinity;
  37628. var maxX = -Infinity;
  37629. var maxY = -Infinity;
  37630. for (var i = 0; i < points.length;) {
  37631. var x = points[i++];
  37632. var y = points[i++];
  37633. if (!isNaN(x)) {
  37634. minX = Math.min(x, minX);
  37635. maxX = Math.max(x, maxX);
  37636. }
  37637. if (!isNaN(y)) {
  37638. minY = Math.min(y, minY);
  37639. maxY = Math.max(y, maxY);
  37640. }
  37641. }
  37642. return [[minX, minY], [maxX, maxY]];
  37643. }
  37644. function getBoundingDiff(points1, points2) {
  37645. var _a = bboxFromPoints(points1),
  37646. min1 = _a[0],
  37647. max1 = _a[1];
  37648. var _b = bboxFromPoints(points2),
  37649. min2 = _b[0],
  37650. max2 = _b[1]; // Get a max value from each corner of two boundings.
  37651. 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]));
  37652. }
  37653. function getSmooth(smooth) {
  37654. return isNumber(smooth) ? smooth : smooth ? 0.5 : 0;
  37655. }
  37656. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  37657. if (!dataCoordInfo.valueDim) {
  37658. return [];
  37659. }
  37660. var len = data.count();
  37661. var points = createFloat32Array(len * 2);
  37662. for (var idx = 0; idx < len; idx++) {
  37663. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  37664. points[idx * 2] = pt[0];
  37665. points[idx * 2 + 1] = pt[1];
  37666. }
  37667. return points;
  37668. }
  37669. function turnPointsIntoStep(points, coordSys, stepTurnAt, connectNulls) {
  37670. var baseAxis = coordSys.getBaseAxis();
  37671. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  37672. var stepPoints = [];
  37673. var i = 0;
  37674. var stepPt = [];
  37675. var pt = [];
  37676. var nextPt = [];
  37677. var filteredPoints = [];
  37678. if (connectNulls) {
  37679. for (i = 0; i < points.length; i += 2) {
  37680. if (!isNaN(points[i]) && !isNaN(points[i + 1])) {
  37681. filteredPoints.push(points[i], points[i + 1]);
  37682. }
  37683. }
  37684. points = filteredPoints;
  37685. }
  37686. for (i = 0; i < points.length - 2; i += 2) {
  37687. nextPt[0] = points[i + 2];
  37688. nextPt[1] = points[i + 3];
  37689. pt[0] = points[i];
  37690. pt[1] = points[i + 1];
  37691. stepPoints.push(pt[0], pt[1]);
  37692. switch (stepTurnAt) {
  37693. case 'end':
  37694. stepPt[baseIndex] = nextPt[baseIndex];
  37695. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37696. stepPoints.push(stepPt[0], stepPt[1]);
  37697. break;
  37698. case 'middle':
  37699. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  37700. var stepPt2 = [];
  37701. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  37702. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  37703. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  37704. stepPoints.push(stepPt[0], stepPt[1]);
  37705. stepPoints.push(stepPt2[0], stepPt2[1]);
  37706. break;
  37707. default:
  37708. // default is start
  37709. stepPt[baseIndex] = pt[baseIndex];
  37710. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  37711. stepPoints.push(stepPt[0], stepPt[1]);
  37712. }
  37713. } // Last points
  37714. stepPoints.push(points[i++], points[i++]);
  37715. return stepPoints;
  37716. }
  37717. /**
  37718. * Clip color stops to edge. Avoid creating too large gradients.
  37719. * Which may lead to blurry when GPU acceleration is enabled. See #15680
  37720. *
  37721. * The stops has been sorted from small to large.
  37722. */
  37723. function clipColorStops(colorStops, maxSize) {
  37724. var newColorStops = [];
  37725. var len = colorStops.length; // coord will always < 0 in prevOutOfRangeColorStop.
  37726. var prevOutOfRangeColorStop;
  37727. var prevInRangeColorStop;
  37728. function lerpStop(stop0, stop1, clippedCoord) {
  37729. var coord0 = stop0.coord;
  37730. var p = (clippedCoord - coord0) / (stop1.coord - coord0);
  37731. var color = lerp$1(p, [stop0.color, stop1.color]);
  37732. return {
  37733. coord: clippedCoord,
  37734. color: color
  37735. };
  37736. }
  37737. for (var i = 0; i < len; i++) {
  37738. var stop_1 = colorStops[i];
  37739. var coord = stop_1.coord;
  37740. if (coord < 0) {
  37741. prevOutOfRangeColorStop = stop_1;
  37742. } else if (coord > maxSize) {
  37743. if (prevInRangeColorStop) {
  37744. newColorStops.push(lerpStop(prevInRangeColorStop, stop_1, maxSize));
  37745. } else if (prevOutOfRangeColorStop) {
  37746. // If there are two stops and coord range is between these two stops
  37747. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0), lerpStop(prevOutOfRangeColorStop, stop_1, maxSize));
  37748. } // All following stop will be out of range. So just ignore them.
  37749. break;
  37750. } else {
  37751. if (prevOutOfRangeColorStop) {
  37752. newColorStops.push(lerpStop(prevOutOfRangeColorStop, stop_1, 0)); // Reset
  37753. prevOutOfRangeColorStop = null;
  37754. }
  37755. newColorStops.push(stop_1);
  37756. prevInRangeColorStop = stop_1;
  37757. }
  37758. }
  37759. return newColorStops;
  37760. }
  37761. function getVisualGradient(data, coordSys, api) {
  37762. var visualMetaList = data.getVisual('visualMeta');
  37763. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  37764. // When data.count() is 0, gradient range can not be calculated.
  37765. return;
  37766. }
  37767. if (coordSys.type !== 'cartesian2d') {
  37768. if ("development" !== 'production') {
  37769. console.warn('Visual map on line style is only supported on cartesian2d.');
  37770. }
  37771. return;
  37772. }
  37773. var coordDim;
  37774. var visualMeta;
  37775. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  37776. var dimInfo = data.getDimensionInfo(visualMetaList[i].dimension);
  37777. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  37778. if (coordDim === 'x' || coordDim === 'y') {
  37779. visualMeta = visualMetaList[i];
  37780. break;
  37781. }
  37782. }
  37783. if (!visualMeta) {
  37784. if ("development" !== 'production') {
  37785. console.warn('Visual map on line style only support x or y dimension.');
  37786. }
  37787. return;
  37788. } // If the area to be rendered is bigger than area defined by LinearGradient,
  37789. // the canvas spec prescribes that the color of the first stop and the last
  37790. // stop should be used. But if two stops are added at offset 0, in effect
  37791. // browsers use the color of the second stop to render area outside
  37792. // LinearGradient. So we can only infinitesimally extend area defined in
  37793. // LinearGradient to render `outerColors`.
  37794. var axis = coordSys.getAxis(coordDim); // dataToCoord mapping may not be linear, but must be monotonic.
  37795. var colorStops = map(visualMeta.stops, function (stop) {
  37796. // offset will be calculated later.
  37797. return {
  37798. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  37799. color: stop.color
  37800. };
  37801. });
  37802. var stopLen = colorStops.length;
  37803. var outerColors = visualMeta.outerColors.slice();
  37804. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  37805. colorStops.reverse();
  37806. outerColors.reverse();
  37807. }
  37808. var colorStopsInRange = clipColorStops(colorStops, coordDim === 'x' ? api.getWidth() : api.getHeight());
  37809. var inRangeStopLen = colorStopsInRange.length;
  37810. if (!inRangeStopLen && stopLen) {
  37811. // All stops are out of range. All will be the same color.
  37812. return colorStops[0].coord < 0 ? outerColors[1] ? outerColors[1] : colorStops[stopLen - 1].color : outerColors[0] ? outerColors[0] : colorStops[0].color;
  37813. }
  37814. var tinyExtent = 10; // Arbitrary value: 10px
  37815. var minCoord = colorStopsInRange[0].coord - tinyExtent;
  37816. var maxCoord = colorStopsInRange[inRangeStopLen - 1].coord + tinyExtent;
  37817. var coordSpan = maxCoord - minCoord;
  37818. if (coordSpan < 1e-3) {
  37819. return 'transparent';
  37820. }
  37821. each(colorStopsInRange, function (stop) {
  37822. stop.offset = (stop.coord - minCoord) / coordSpan;
  37823. });
  37824. colorStopsInRange.push({
  37825. // NOTE: inRangeStopLen may still be 0 if stoplen is zero.
  37826. offset: inRangeStopLen ? colorStopsInRange[inRangeStopLen - 1].offset : 0.5,
  37827. color: outerColors[1] || 'transparent'
  37828. });
  37829. colorStopsInRange.unshift({
  37830. offset: inRangeStopLen ? colorStopsInRange[0].offset : 0.5,
  37831. color: outerColors[0] || 'transparent'
  37832. });
  37833. var gradient = new LinearGradient(0, 0, 0, 0, colorStopsInRange, true);
  37834. gradient[coordDim] = minCoord;
  37835. gradient[coordDim + '2'] = maxCoord;
  37836. return gradient;
  37837. }
  37838. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  37839. var showAllSymbol = seriesModel.get('showAllSymbol');
  37840. var isAuto = showAllSymbol === 'auto';
  37841. if (showAllSymbol && !isAuto) {
  37842. return;
  37843. }
  37844. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  37845. if (!categoryAxis) {
  37846. return;
  37847. } // Note that category label interval strategy might bring some weird effect
  37848. // in some scenario: users may wonder why some of the symbols are not
  37849. // displayed. So we show all symbols as possible as we can.
  37850. if (isAuto // Simplify the logic, do not determine label overlap here.
  37851. && canShowAllSymbolForCategory(categoryAxis, data)) {
  37852. return;
  37853. } // Otherwise follow the label interval strategy on category axis.
  37854. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  37855. var labelMap = {};
  37856. each(categoryAxis.getViewLabels(), function (labelItem) {
  37857. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  37858. labelMap[ordinalNumber] = 1;
  37859. });
  37860. return function (dataIndex) {
  37861. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  37862. };
  37863. }
  37864. function canShowAllSymbolForCategory(categoryAxis, data) {
  37865. // In most cases, line is monotonous on category axis, and the label size
  37866. // is close with each other. So we check the symbol size and some of the
  37867. // label size alone with the category axis to estimate whether all symbol
  37868. // can be shown without overlap.
  37869. var axisExtent = categoryAxis.getExtent();
  37870. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  37871. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  37872. // Sampling some points, max 5.
  37873. var dataLen = data.count();
  37874. var step = Math.max(1, Math.round(dataLen / 5));
  37875. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  37876. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  37877. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  37878. * 1.5 > availSize) {
  37879. return false;
  37880. }
  37881. }
  37882. return true;
  37883. }
  37884. function isPointNull$1(x, y) {
  37885. return isNaN(x) || isNaN(y);
  37886. }
  37887. function getLastIndexNotNull(points) {
  37888. var len = points.length / 2;
  37889. for (; len > 0; len--) {
  37890. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  37891. break;
  37892. }
  37893. }
  37894. return len - 1;
  37895. }
  37896. function getPointAtIndex(points, idx) {
  37897. return [points[idx * 2], points[idx * 2 + 1]];
  37898. }
  37899. function getIndexRange(points, xOrY, dim) {
  37900. var len = points.length / 2;
  37901. var dimIdx = dim === 'x' ? 0 : 1;
  37902. var a;
  37903. var b;
  37904. var prevIndex = 0;
  37905. var nextIndex = -1;
  37906. for (var i = 0; i < len; i++) {
  37907. b = points[i * 2 + dimIdx];
  37908. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  37909. continue;
  37910. }
  37911. if (i === 0) {
  37912. a = b;
  37913. continue;
  37914. }
  37915. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  37916. nextIndex = i;
  37917. break;
  37918. }
  37919. prevIndex = i;
  37920. a = b;
  37921. }
  37922. return {
  37923. range: [prevIndex, nextIndex],
  37924. t: (xOrY - a) / (b - a)
  37925. };
  37926. }
  37927. function anyStateShowEndLabel(seriesModel) {
  37928. if (seriesModel.get(['endLabel', 'show'])) {
  37929. return true;
  37930. }
  37931. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  37932. if (seriesModel.get([SPECIAL_STATES[i], 'endLabel', 'show'])) {
  37933. return true;
  37934. }
  37935. }
  37936. return false;
  37937. }
  37938. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  37939. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  37940. var endLabelModel_1 = seriesModel.getModel('endLabel');
  37941. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  37942. var data_1 = seriesModel.getData();
  37943. var labelAnimationRecord_1 = {
  37944. lastFrameIndex: 0
  37945. };
  37946. var during = anyStateShowEndLabel(seriesModel) ? function (percent, clipRect) {
  37947. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  37948. } : null;
  37949. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  37950. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  37951. var endLabel = lineView._endLabel;
  37952. if (endLabel && hasAnimation) {
  37953. if (labelAnimationRecord_1.originalX != null) {
  37954. endLabel.attr({
  37955. x: labelAnimationRecord_1.originalX,
  37956. y: labelAnimationRecord_1.originalY
  37957. });
  37958. }
  37959. }
  37960. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  37961. if (!seriesModel.get('clip', true)) {
  37962. var rectShape = clipPath.shape;
  37963. var expandSize = Math.max(rectShape.width, rectShape.height);
  37964. if (isHorizontal) {
  37965. rectShape.y -= expandSize;
  37966. rectShape.height += expandSize * 2;
  37967. } else {
  37968. rectShape.x -= expandSize;
  37969. rectShape.width += expandSize * 2;
  37970. }
  37971. } // Set to the final frame. To make sure label layout is right.
  37972. if (during) {
  37973. during(1, clipPath);
  37974. }
  37975. return clipPath;
  37976. } else {
  37977. if ("development" !== 'production') {
  37978. if (seriesModel.get(['endLabel', 'show'])) {
  37979. console.warn('endLabel is not supported for lines in polar systems.');
  37980. }
  37981. }
  37982. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  37983. }
  37984. }
  37985. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  37986. var baseAxis = coordSys.getBaseAxis();
  37987. var isHorizontal = baseAxis.isHorizontal();
  37988. var isBaseInversed = baseAxis.inverse;
  37989. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  37990. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  37991. return {
  37992. normal: {
  37993. align: endLabelModel.get('align') || align,
  37994. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  37995. }
  37996. };
  37997. }
  37998. var LineView =
  37999. /** @class */
  38000. function (_super) {
  38001. __extends(LineView, _super);
  38002. function LineView() {
  38003. return _super !== null && _super.apply(this, arguments) || this;
  38004. }
  38005. LineView.prototype.init = function () {
  38006. var lineGroup = new Group();
  38007. var symbolDraw = new SymbolDraw();
  38008. this.group.add(symbolDraw.group);
  38009. this._symbolDraw = symbolDraw;
  38010. this._lineGroup = lineGroup;
  38011. };
  38012. LineView.prototype.render = function (seriesModel, ecModel, api) {
  38013. var _this = this;
  38014. var coordSys = seriesModel.coordinateSystem;
  38015. var group = this.group;
  38016. var data = seriesModel.getData();
  38017. var lineStyleModel = seriesModel.getModel('lineStyle');
  38018. var areaStyleModel = seriesModel.getModel('areaStyle');
  38019. var points = data.getLayout('points') || [];
  38020. var isCoordSysPolar = coordSys.type === 'polar';
  38021. var prevCoordSys = this._coordSys;
  38022. var symbolDraw = this._symbolDraw;
  38023. var polyline = this._polyline;
  38024. var polygon = this._polygon;
  38025. var lineGroup = this._lineGroup;
  38026. var hasAnimation = !ecModel.ssr && seriesModel.isAnimationEnabled();
  38027. var isAreaChart = !areaStyleModel.isEmpty();
  38028. var valueOrigin = areaStyleModel.get('origin');
  38029. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  38030. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  38031. var showSymbol = seriesModel.get('showSymbol');
  38032. var connectNulls = seriesModel.get('connectNulls');
  38033. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  38034. var oldData = this._data;
  38035. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38036. if (el.__temp) {
  38037. group.remove(el);
  38038. oldData.setItemGraphicEl(idx, null);
  38039. }
  38040. }); // Remove previous created symbols if showSymbol changed to false
  38041. if (!showSymbol) {
  38042. symbolDraw.remove();
  38043. }
  38044. group.add(lineGroup); // FIXME step not support polar
  38045. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  38046. var clipShapeForSymbol;
  38047. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  38048. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  38049. // See #7913 and `test/dataZoom-clip.html`.
  38050. if (clipShapeForSymbol.width != null) {
  38051. clipShapeForSymbol.x -= 0.1;
  38052. clipShapeForSymbol.y -= 0.1;
  38053. clipShapeForSymbol.width += 0.2;
  38054. clipShapeForSymbol.height += 0.2;
  38055. } else if (clipShapeForSymbol.r0) {
  38056. clipShapeForSymbol.r0 -= 0.5;
  38057. clipShapeForSymbol.r += 0.5;
  38058. }
  38059. }
  38060. this._clipShapeForSymbol = clipShapeForSymbol;
  38061. var visualColor = getVisualGradient(data, coordSys, api) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  38062. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  38063. showSymbol && symbolDraw.updateData(data, {
  38064. isIgnore: isIgnoreFunc,
  38065. clipShape: clipShapeForSymbol,
  38066. disableAnimation: true,
  38067. getSymbolPoint: function (idx) {
  38068. return [points[idx * 2], points[idx * 2 + 1]];
  38069. }
  38070. });
  38071. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  38072. if (step) {
  38073. // TODO If stacked series is not step
  38074. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38075. if (stackedOnPoints) {
  38076. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38077. }
  38078. }
  38079. polyline = this._newPolyline(points);
  38080. if (isAreaChart) {
  38081. polygon = this._newPolygon(points, stackedOnPoints);
  38082. } // If areaStyle is removed
  38083. else if (polygon) {
  38084. lineGroup.remove(polygon);
  38085. polygon = this._polygon = null;
  38086. } // NOTE: Must update _endLabel before setClipPath.
  38087. if (!isCoordSysPolar) {
  38088. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38089. }
  38090. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38091. } else {
  38092. if (isAreaChart && !polygon) {
  38093. // If areaStyle is added
  38094. polygon = this._newPolygon(points, stackedOnPoints);
  38095. } else if (polygon && !isAreaChart) {
  38096. // If areaStyle is removed
  38097. lineGroup.remove(polygon);
  38098. polygon = this._polygon = null;
  38099. } // NOTE: Must update _endLabel before setClipPath.
  38100. if (!isCoordSysPolar) {
  38101. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  38102. } // Update clipPath
  38103. var oldClipPath = lineGroup.getClipPath();
  38104. if (oldClipPath) {
  38105. var newClipPath = createLineClipPath(this, coordSys, false, seriesModel);
  38106. initProps(oldClipPath, {
  38107. shape: newClipPath.shape
  38108. }, seriesModel);
  38109. } else {
  38110. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  38111. } // Always update, or it is wrong in the case turning on legend
  38112. // because points are not changed.
  38113. showSymbol && symbolDraw.updateData(data, {
  38114. isIgnore: isIgnoreFunc,
  38115. clipShape: clipShapeForSymbol,
  38116. disableAnimation: true,
  38117. getSymbolPoint: function (idx) {
  38118. return [points[idx * 2], points[idx * 2 + 1]];
  38119. }
  38120. }); // In the case data zoom triggered refreshing frequently
  38121. // Data may not change if line has a category axis. So it should animate nothing.
  38122. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  38123. if (hasAnimation) {
  38124. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls);
  38125. } else {
  38126. // Not do it in update with animation
  38127. if (step) {
  38128. // TODO If stacked series is not step
  38129. points = turnPointsIntoStep(points, coordSys, step, connectNulls);
  38130. if (stackedOnPoints) {
  38131. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step, connectNulls);
  38132. }
  38133. }
  38134. polyline.setShape({
  38135. points: points
  38136. });
  38137. polygon && polygon.setShape({
  38138. points: points,
  38139. stackedOnPoints: stackedOnPoints
  38140. });
  38141. }
  38142. }
  38143. }
  38144. var emphasisModel = seriesModel.getModel('emphasis');
  38145. var focus = emphasisModel.get('focus');
  38146. var blurScope = emphasisModel.get('blurScope');
  38147. var emphasisDisabled = emphasisModel.get('disabled');
  38148. polyline.useStyle(defaults( // Use color in lineStyle first
  38149. lineStyleModel.getLineStyle(), {
  38150. fill: 'none',
  38151. stroke: visualColor,
  38152. lineJoin: 'bevel'
  38153. }));
  38154. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  38155. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  38156. var emphasisLineStyle = polyline.getState('emphasis').style;
  38157. emphasisLineStyle.lineWidth = +polyline.style.lineWidth + 1;
  38158. } // Needs seriesIndex for focus
  38159. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  38160. toggleHoverEmphasis(polyline, focus, blurScope, emphasisDisabled);
  38161. var smooth = getSmooth(seriesModel.get('smooth'));
  38162. var smoothMonotone = seriesModel.get('smoothMonotone');
  38163. polyline.setShape({
  38164. smooth: smooth,
  38165. smoothMonotone: smoothMonotone,
  38166. connectNulls: connectNulls
  38167. });
  38168. if (polygon) {
  38169. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  38170. var stackedOnSmooth = 0;
  38171. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38172. fill: visualColor,
  38173. opacity: 0.7,
  38174. lineJoin: 'bevel',
  38175. decal: data.getVisual('style').decal
  38176. }));
  38177. if (stackedOnSeries) {
  38178. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  38179. }
  38180. polygon.setShape({
  38181. smooth: smooth,
  38182. stackedOnSmooth: stackedOnSmooth,
  38183. smoothMonotone: smoothMonotone,
  38184. connectNulls: connectNulls
  38185. });
  38186. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  38187. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  38188. toggleHoverEmphasis(polygon, focus, blurScope, emphasisDisabled);
  38189. }
  38190. var changePolyState = function (toState) {
  38191. _this._changePolyState(toState);
  38192. };
  38193. data.eachItemGraphicEl(function (el) {
  38194. // Switch polyline / polygon state if element changed its state.
  38195. el && (el.onHoverStateChange = changePolyState);
  38196. });
  38197. this._polyline.onHoverStateChange = changePolyState;
  38198. this._data = data; // Save the coordinate system for transition animation when data changed
  38199. this._coordSys = coordSys;
  38200. this._stackedOnPoints = stackedOnPoints;
  38201. this._points = points;
  38202. this._step = step;
  38203. this._valueOrigin = valueOrigin;
  38204. if (seriesModel.get('triggerLineEvent')) {
  38205. this.packEventData(seriesModel, polyline);
  38206. polygon && this.packEventData(seriesModel, polygon);
  38207. }
  38208. };
  38209. LineView.prototype.packEventData = function (seriesModel, el) {
  38210. getECData(el).eventData = {
  38211. componentType: 'series',
  38212. componentSubType: 'line',
  38213. componentIndex: seriesModel.componentIndex,
  38214. seriesIndex: seriesModel.seriesIndex,
  38215. seriesName: seriesModel.name,
  38216. seriesType: 'line'
  38217. };
  38218. };
  38219. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  38220. var data = seriesModel.getData();
  38221. var dataIndex = queryDataIndex(data, payload);
  38222. this._changePolyState('emphasis');
  38223. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  38224. var points = data.getLayout('points');
  38225. var symbol = data.getItemGraphicEl(dataIndex);
  38226. if (!symbol) {
  38227. // Create a temporary symbol if it is not exists
  38228. var x = points[dataIndex * 2];
  38229. var y = points[dataIndex * 2 + 1];
  38230. if (isNaN(x) || isNaN(y)) {
  38231. // Null data
  38232. return;
  38233. } // fix #11360: shouldn't draw symbol outside clipShapeForSymbol
  38234. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  38235. return;
  38236. }
  38237. var zlevel = seriesModel.get('zlevel') || 0;
  38238. var z = seriesModel.get('z') || 0;
  38239. symbol = new Symbol(data, dataIndex);
  38240. symbol.x = x;
  38241. symbol.y = y;
  38242. symbol.setZ(zlevel, z); // ensure label text of the temporary symbol is in front of line and area polygon
  38243. var symbolLabel = symbol.getSymbolPath().getTextContent();
  38244. if (symbolLabel) {
  38245. symbolLabel.zlevel = zlevel;
  38246. symbolLabel.z = z;
  38247. symbolLabel.z2 = this._polyline.z2 + 1;
  38248. }
  38249. symbol.__temp = true;
  38250. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  38251. symbol.stopSymbolAnimation(true);
  38252. this.group.add(symbol);
  38253. }
  38254. symbol.highlight();
  38255. } else {
  38256. // Highlight whole series
  38257. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  38258. }
  38259. };
  38260. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  38261. var data = seriesModel.getData();
  38262. var dataIndex = queryDataIndex(data, payload);
  38263. this._changePolyState('normal');
  38264. if (dataIndex != null && dataIndex >= 0) {
  38265. var symbol = data.getItemGraphicEl(dataIndex);
  38266. if (symbol) {
  38267. if (symbol.__temp) {
  38268. data.setItemGraphicEl(dataIndex, null);
  38269. this.group.remove(symbol);
  38270. } else {
  38271. symbol.downplay();
  38272. }
  38273. }
  38274. } else {
  38275. // FIXME
  38276. // can not downplay completely.
  38277. // Downplay whole series
  38278. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  38279. }
  38280. };
  38281. LineView.prototype._changePolyState = function (toState) {
  38282. var polygon = this._polygon;
  38283. setStatesFlag(this._polyline, toState);
  38284. polygon && setStatesFlag(polygon, toState);
  38285. };
  38286. LineView.prototype._newPolyline = function (points) {
  38287. var polyline = this._polyline; // Remove previous created polyline
  38288. if (polyline) {
  38289. this._lineGroup.remove(polyline);
  38290. }
  38291. polyline = new ECPolyline({
  38292. shape: {
  38293. points: points
  38294. },
  38295. segmentIgnoreThreshold: 2,
  38296. z2: 10
  38297. });
  38298. this._lineGroup.add(polyline);
  38299. this._polyline = polyline;
  38300. return polyline;
  38301. };
  38302. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  38303. var polygon = this._polygon; // Remove previous created polygon
  38304. if (polygon) {
  38305. this._lineGroup.remove(polygon);
  38306. }
  38307. polygon = new ECPolygon({
  38308. shape: {
  38309. points: points,
  38310. stackedOnPoints: stackedOnPoints
  38311. },
  38312. segmentIgnoreThreshold: 2
  38313. });
  38314. this._lineGroup.add(polygon);
  38315. this._polygon = polygon;
  38316. return polygon;
  38317. };
  38318. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  38319. var isHorizontalOrRadial;
  38320. var isCoordSysPolar;
  38321. var baseAxis = coordSys.getBaseAxis();
  38322. var isAxisInverse = baseAxis.inverse;
  38323. if (coordSys.type === 'cartesian2d') {
  38324. isHorizontalOrRadial = baseAxis.isHorizontal();
  38325. isCoordSysPolar = false;
  38326. } else if (coordSys.type === 'polar') {
  38327. isHorizontalOrRadial = baseAxis.dim === 'angle';
  38328. isCoordSysPolar = true;
  38329. }
  38330. var seriesModel = data.hostModel;
  38331. var seriesDuration = seriesModel.get('animationDuration');
  38332. if (isFunction(seriesDuration)) {
  38333. seriesDuration = seriesDuration(null);
  38334. }
  38335. var seriesDelay = seriesModel.get('animationDelay') || 0;
  38336. var seriesDelayValue = isFunction(seriesDelay) ? seriesDelay(null) : seriesDelay;
  38337. data.eachItemGraphicEl(function (symbol, idx) {
  38338. var el = symbol;
  38339. if (el) {
  38340. var point = [symbol.x, symbol.y];
  38341. var start = void 0;
  38342. var end = void 0;
  38343. var current = void 0;
  38344. if (clipShape) {
  38345. if (isCoordSysPolar) {
  38346. var polarClip = clipShape;
  38347. var coord = coordSys.pointToCoord(point);
  38348. if (isHorizontalOrRadial) {
  38349. start = polarClip.startAngle;
  38350. end = polarClip.endAngle;
  38351. current = -coord[1] / 180 * Math.PI;
  38352. } else {
  38353. start = polarClip.r0;
  38354. end = polarClip.r;
  38355. current = coord[0];
  38356. }
  38357. } else {
  38358. var gridClip = clipShape;
  38359. if (isHorizontalOrRadial) {
  38360. start = gridClip.x;
  38361. end = gridClip.x + gridClip.width;
  38362. current = symbol.x;
  38363. } else {
  38364. start = gridClip.y + gridClip.height;
  38365. end = gridClip.y;
  38366. current = symbol.y;
  38367. }
  38368. }
  38369. }
  38370. var ratio = end === start ? 0 : (current - start) / (end - start);
  38371. if (isAxisInverse) {
  38372. ratio = 1 - ratio;
  38373. }
  38374. var delay = isFunction(seriesDelay) ? seriesDelay(idx) : seriesDuration * ratio + seriesDelayValue;
  38375. var symbolPath = el.getSymbolPath();
  38376. var text = symbolPath.getTextContent();
  38377. el.attr({
  38378. scaleX: 0,
  38379. scaleY: 0
  38380. });
  38381. el.animateTo({
  38382. scaleX: 1,
  38383. scaleY: 1
  38384. }, {
  38385. duration: 200,
  38386. setToFinal: true,
  38387. delay: delay
  38388. });
  38389. if (text) {
  38390. text.animateFrom({
  38391. style: {
  38392. opacity: 0
  38393. }
  38394. }, {
  38395. duration: 300,
  38396. delay: delay
  38397. });
  38398. }
  38399. symbolPath.disableLabelAnimation = true;
  38400. }
  38401. });
  38402. };
  38403. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  38404. var endLabelModel = seriesModel.getModel('endLabel');
  38405. if (anyStateShowEndLabel(seriesModel)) {
  38406. var data_2 = seriesModel.getData();
  38407. var polyline = this._polyline; // series may be filtered.
  38408. var points = data_2.getLayout('points');
  38409. if (!points) {
  38410. polyline.removeTextContent();
  38411. this._endLabel = null;
  38412. return;
  38413. }
  38414. var endLabel = this._endLabel;
  38415. if (!endLabel) {
  38416. endLabel = this._endLabel = new ZRText({
  38417. z2: 200 // should be higher than item symbol
  38418. });
  38419. endLabel.ignoreClip = true;
  38420. polyline.setTextContent(this._endLabel);
  38421. polyline.disableLabelAnimation = true;
  38422. } // Find last non-NaN data to display data
  38423. var dataIndex = getLastIndexNotNull(points);
  38424. if (dataIndex >= 0) {
  38425. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  38426. inheritColor: inheritColor,
  38427. labelFetcher: seriesModel,
  38428. labelDataIndex: dataIndex,
  38429. defaultText: function (dataIndex, opt, interpolatedValue) {
  38430. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  38431. },
  38432. enableTextSetter: true
  38433. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  38434. polyline.textConfig.position = null;
  38435. }
  38436. } else if (this._endLabel) {
  38437. this._polyline.removeTextContent();
  38438. this._endLabel = null;
  38439. }
  38440. };
  38441. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  38442. var endLabel = this._endLabel;
  38443. var polyline = this._polyline;
  38444. if (endLabel) {
  38445. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  38446. // The label is not prepared at this time.
  38447. if (percent < 1 && animationRecord.originalX == null) {
  38448. animationRecord.originalX = endLabel.x;
  38449. animationRecord.originalY = endLabel.y;
  38450. }
  38451. var points = data.getLayout('points');
  38452. var seriesModel = data.hostModel;
  38453. var connectNulls = seriesModel.get('connectNulls');
  38454. var precision = endLabelModel.get('precision');
  38455. var distance = endLabelModel.get('distance') || 0;
  38456. var baseAxis = coordSys.getBaseAxis();
  38457. var isHorizontal = baseAxis.isHorizontal();
  38458. var isBaseInversed = baseAxis.inverse;
  38459. var clipShape = clipRect.shape;
  38460. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  38461. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  38462. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  38463. var dim = isHorizontal ? 'x' : 'y';
  38464. var dataIndexRange = getIndexRange(points, xOrY, dim);
  38465. var indices = dataIndexRange.range;
  38466. var diff = indices[1] - indices[0];
  38467. var value = void 0;
  38468. if (diff >= 1) {
  38469. // diff > 1 && connectNulls, which is on the null data.
  38470. if (diff > 1 && !connectNulls) {
  38471. var pt = getPointAtIndex(points, indices[0]);
  38472. endLabel.attr({
  38473. x: pt[0] + distanceX,
  38474. y: pt[1] + distanceY
  38475. });
  38476. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  38477. } else {
  38478. var pt = polyline.getPointOn(xOrY, dim);
  38479. pt && endLabel.attr({
  38480. x: pt[0] + distanceX,
  38481. y: pt[1] + distanceY
  38482. });
  38483. var startValue = seriesModel.getRawValue(indices[0]);
  38484. var endValue = seriesModel.getRawValue(indices[1]);
  38485. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  38486. }
  38487. animationRecord.lastFrameIndex = indices[0];
  38488. } else {
  38489. // If diff <= 0, which is the range is not found(Include NaN)
  38490. // Choose the first point or last point.
  38491. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  38492. var pt = getPointAtIndex(points, idx);
  38493. valueAnimation && (value = seriesModel.getRawValue(idx));
  38494. endLabel.attr({
  38495. x: pt[0] + distanceX,
  38496. y: pt[1] + distanceY
  38497. });
  38498. }
  38499. if (valueAnimation) {
  38500. var inner = labelInner(endLabel);
  38501. if (typeof inner.setLabelText === 'function') {
  38502. inner.setLabelText(value);
  38503. }
  38504. }
  38505. }
  38506. };
  38507. /**
  38508. * @private
  38509. */
  38510. // FIXME Two value axis
  38511. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin, connectNulls) {
  38512. var polyline = this._polyline;
  38513. var polygon = this._polygon;
  38514. var seriesModel = data.hostModel;
  38515. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin);
  38516. var current = diff.current;
  38517. var stackedOnCurrent = diff.stackedOnCurrent;
  38518. var next = diff.next;
  38519. var stackedOnNext = diff.stackedOnNext;
  38520. if (step) {
  38521. // TODO If stacked series is not step
  38522. current = turnPointsIntoStep(diff.current, coordSys, step, connectNulls);
  38523. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step, connectNulls);
  38524. next = turnPointsIntoStep(diff.next, coordSys, step, connectNulls);
  38525. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step, connectNulls);
  38526. } // Don't apply animation if diff is large.
  38527. // For better result and avoid memory explosion problems like
  38528. // https://github.com/apache/incubator-echarts/issues/12229
  38529. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  38530. polyline.stopAnimation();
  38531. polyline.setShape({
  38532. points: next
  38533. });
  38534. if (polygon) {
  38535. polygon.stopAnimation();
  38536. polygon.setShape({
  38537. points: next,
  38538. stackedOnPoints: stackedOnNext
  38539. });
  38540. }
  38541. return;
  38542. }
  38543. polyline.shape.__points = diff.current;
  38544. polyline.shape.points = current;
  38545. var target = {
  38546. shape: {
  38547. points: next
  38548. }
  38549. }; // Also animate the original points.
  38550. // If points reference is changed when turning into step line.
  38551. if (diff.current !== current) {
  38552. target.shape.__points = diff.next;
  38553. } // Stop previous animation.
  38554. polyline.stopAnimation();
  38555. updateProps(polyline, target, seriesModel);
  38556. if (polygon) {
  38557. polygon.setShape({
  38558. // Reuse the points with polyline.
  38559. points: current,
  38560. stackedOnPoints: stackedOnCurrent
  38561. });
  38562. polygon.stopAnimation();
  38563. updateProps(polygon, {
  38564. shape: {
  38565. stackedOnPoints: stackedOnNext
  38566. }
  38567. }, seriesModel); // If use attr directly in updateProps.
  38568. if (polyline.shape.points !== polygon.shape.points) {
  38569. polygon.shape.points = polyline.shape.points;
  38570. }
  38571. }
  38572. var updatedDataInfo = [];
  38573. var diffStatus = diff.status;
  38574. for (var i = 0; i < diffStatus.length; i++) {
  38575. var cmd = diffStatus[i].cmd;
  38576. if (cmd === '=') {
  38577. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  38578. if (el) {
  38579. updatedDataInfo.push({
  38580. el: el,
  38581. ptIdx: i // Index of points
  38582. });
  38583. }
  38584. }
  38585. }
  38586. if (polyline.animators && polyline.animators.length) {
  38587. polyline.animators[0].during(function () {
  38588. polygon && polygon.dirtyShape();
  38589. var points = polyline.shape.__points;
  38590. for (var i = 0; i < updatedDataInfo.length; i++) {
  38591. var el = updatedDataInfo[i].el;
  38592. var offset = updatedDataInfo[i].ptIdx * 2;
  38593. el.x = points[offset];
  38594. el.y = points[offset + 1];
  38595. el.markRedraw();
  38596. }
  38597. });
  38598. }
  38599. };
  38600. LineView.prototype.remove = function (ecModel) {
  38601. var group = this.group;
  38602. var oldData = this._data;
  38603. this._lineGroup.removeAll();
  38604. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  38605. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  38606. if (el.__temp) {
  38607. group.remove(el);
  38608. oldData.setItemGraphicEl(idx, null);
  38609. }
  38610. });
  38611. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  38612. };
  38613. LineView.type = 'line';
  38614. return LineView;
  38615. }(ChartView);
  38616. function pointsLayout(seriesType, forceStoreInTypedArray) {
  38617. return {
  38618. seriesType: seriesType,
  38619. plan: createRenderPlanner(),
  38620. reset: function (seriesModel) {
  38621. var data = seriesModel.getData();
  38622. var coordSys = seriesModel.coordinateSystem;
  38623. var pipelineContext = seriesModel.pipelineContext;
  38624. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  38625. if (!coordSys) {
  38626. return;
  38627. }
  38628. var dims = map(coordSys.dimensions, function (dim) {
  38629. return data.mapDimension(dim);
  38630. }).slice(0, 2);
  38631. var dimLen = dims.length;
  38632. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  38633. if (isDimensionStacked(data, dims[0])) {
  38634. dims[0] = stackResultDim;
  38635. }
  38636. if (isDimensionStacked(data, dims[1])) {
  38637. dims[1] = stackResultDim;
  38638. }
  38639. var store = data.getStore();
  38640. var dimIdx0 = data.getDimensionIndex(dims[0]);
  38641. var dimIdx1 = data.getDimensionIndex(dims[1]);
  38642. return dimLen && {
  38643. progress: function (params, data) {
  38644. var segCount = params.end - params.start;
  38645. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  38646. var tmpIn = [];
  38647. var tmpOut = [];
  38648. for (var i = params.start, offset = 0; i < params.end; i++) {
  38649. var point = void 0;
  38650. if (dimLen === 1) {
  38651. var x = store.get(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  38652. point = coordSys.dataToPoint(x, null, tmpOut);
  38653. } else {
  38654. tmpIn[0] = store.get(dimIdx0, i);
  38655. tmpIn[1] = store.get(dimIdx1, i); // Let coordinate system to handle the NaN data.
  38656. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  38657. }
  38658. if (useTypedArray) {
  38659. points[offset++] = point[0];
  38660. points[offset++] = point[1];
  38661. } else {
  38662. data.setItemLayout(i, point.slice());
  38663. }
  38664. }
  38665. useTypedArray && data.setLayout('points', points);
  38666. }
  38667. };
  38668. }
  38669. };
  38670. }
  38671. var samplers = {
  38672. average: function (frame) {
  38673. var sum = 0;
  38674. var count = 0;
  38675. for (var i = 0; i < frame.length; i++) {
  38676. if (!isNaN(frame[i])) {
  38677. sum += frame[i];
  38678. count++;
  38679. }
  38680. } // Return NaN if count is 0
  38681. return count === 0 ? NaN : sum / count;
  38682. },
  38683. sum: function (frame) {
  38684. var sum = 0;
  38685. for (var i = 0; i < frame.length; i++) {
  38686. // Ignore NaN
  38687. sum += frame[i] || 0;
  38688. }
  38689. return sum;
  38690. },
  38691. max: function (frame) {
  38692. var max = -Infinity;
  38693. for (var i = 0; i < frame.length; i++) {
  38694. frame[i] > max && (max = frame[i]);
  38695. } // NaN will cause illegal axis extent.
  38696. return isFinite(max) ? max : NaN;
  38697. },
  38698. min: function (frame) {
  38699. var min = Infinity;
  38700. for (var i = 0; i < frame.length; i++) {
  38701. frame[i] < min && (min = frame[i]);
  38702. } // NaN will cause illegal axis extent.
  38703. return isFinite(min) ? min : NaN;
  38704. },
  38705. // TODO
  38706. // Median
  38707. nearest: function (frame) {
  38708. return frame[0];
  38709. }
  38710. };
  38711. var indexSampler = function (frame) {
  38712. return Math.round(frame.length / 2);
  38713. };
  38714. function dataSample(seriesType) {
  38715. return {
  38716. seriesType: seriesType,
  38717. // FIXME:TS never used, so comment it
  38718. // modifyOutputEnd: true,
  38719. reset: function (seriesModel, ecModel, api) {
  38720. var data = seriesModel.getData();
  38721. var sampling = seriesModel.get('sampling');
  38722. var coordSys = seriesModel.coordinateSystem;
  38723. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  38724. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  38725. var baseAxis = coordSys.getBaseAxis();
  38726. var valueAxis = coordSys.getOtherAxis(baseAxis);
  38727. var extent = baseAxis.getExtent();
  38728. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  38729. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  38730. var rate = Math.round(count / size);
  38731. if (isFinite(rate) && rate > 1) {
  38732. if (sampling === 'lttb') {
  38733. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  38734. }
  38735. var sampler = void 0;
  38736. if (isString(sampling)) {
  38737. sampler = samplers[sampling];
  38738. } else if (isFunction(sampling)) {
  38739. sampler = sampling;
  38740. }
  38741. if (sampler) {
  38742. // Only support sample the first dim mapped from value axis.
  38743. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  38744. }
  38745. }
  38746. }
  38747. }
  38748. };
  38749. }
  38750. function install$2(registers) {
  38751. registers.registerChartView(LineView);
  38752. registers.registerSeriesModel(LineSeriesModel);
  38753. registers.registerLayout(pointsLayout('line', true));
  38754. registers.registerVisual({
  38755. seriesType: 'line',
  38756. reset: function (seriesModel) {
  38757. var data = seriesModel.getData(); // Visual coding for legend
  38758. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  38759. if (lineStyle && !lineStyle.stroke) {
  38760. // Fill in visual should be palette color if
  38761. // has color callback
  38762. lineStyle.stroke = data.getVisual('style').fill;
  38763. }
  38764. data.setVisual('legendLineStyle', lineStyle);
  38765. }
  38766. }); // Down sample after filter
  38767. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  38768. }
  38769. var BaseBarSeriesModel =
  38770. /** @class */
  38771. function (_super) {
  38772. __extends(BaseBarSeriesModel, _super);
  38773. function BaseBarSeriesModel() {
  38774. var _this = _super !== null && _super.apply(this, arguments) || this;
  38775. _this.type = BaseBarSeriesModel.type;
  38776. return _this;
  38777. }
  38778. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38779. return createSeriesData(null, this, {
  38780. useEncodeDefaulter: true
  38781. });
  38782. };
  38783. BaseBarSeriesModel.prototype.getMarkerPosition = function (value, dims, startingAtTick) {
  38784. var coordSys = this.coordinateSystem;
  38785. if (coordSys && coordSys.clampData) {
  38786. // PENDING if clamp ?
  38787. var clampData_1 = coordSys.clampData(value);
  38788. var pt_1 = coordSys.dataToPoint(clampData_1);
  38789. if (startingAtTick) {
  38790. each(coordSys.getAxes(), function (axis, idx) {
  38791. // If axis type is category, use tick coords instead
  38792. if (axis.type === 'category' && dims != null) {
  38793. var tickCoords = axis.getTicksCoords();
  38794. var targetTickId = clampData_1[idx]; // The index of rightmost tick of markArea is 1 larger than x1/y1 index
  38795. var isEnd = dims[idx] === 'x1' || dims[idx] === 'y1';
  38796. if (isEnd) {
  38797. targetTickId += 1;
  38798. } // The only contains one tick, tickCoords is
  38799. // like [{coord: 0, tickValue: 0}, {coord: 0}]
  38800. // to the length should always be larger than 1
  38801. if (tickCoords.length < 2) {
  38802. return;
  38803. } else if (tickCoords.length === 2) {
  38804. // The left value and right value of the axis are
  38805. // the same. coord is 0 in both items. Use the max
  38806. // value of the axis as the coord
  38807. pt_1[idx] = axis.toGlobalCoord(axis.getExtent()[isEnd ? 1 : 0]);
  38808. return;
  38809. }
  38810. var leftCoord = void 0;
  38811. var coord = void 0;
  38812. var stepTickValue = 1;
  38813. for (var i = 0; i < tickCoords.length; i++) {
  38814. var tickCoord = tickCoords[i].coord; // The last item of tickCoords doesn't contain
  38815. // tickValue
  38816. var tickValue = i === tickCoords.length - 1 ? tickCoords[i - 1].tickValue + stepTickValue : tickCoords[i].tickValue;
  38817. if (tickValue === targetTickId) {
  38818. coord = tickCoord;
  38819. break;
  38820. } else if (tickValue < targetTickId) {
  38821. leftCoord = tickCoord;
  38822. } else if (leftCoord != null && tickValue > targetTickId) {
  38823. coord = (tickCoord + leftCoord) / 2;
  38824. break;
  38825. }
  38826. if (i === 1) {
  38827. // Here we assume the step of category axes is
  38828. // the same
  38829. stepTickValue = tickValue - tickCoords[0].tickValue;
  38830. }
  38831. }
  38832. if (coord == null) {
  38833. if (!leftCoord) {
  38834. // targetTickId is smaller than all tick ids in the
  38835. // visible area, use the leftmost tick coord
  38836. coord = tickCoords[0].coord;
  38837. } else if (leftCoord) {
  38838. // targetTickId is larger than all tick ids in the
  38839. // visible area, use the rightmost tick coord
  38840. coord = tickCoords[tickCoords.length - 1].coord;
  38841. }
  38842. }
  38843. pt_1[idx] = axis.toGlobalCoord(coord);
  38844. }
  38845. });
  38846. } else {
  38847. var data = this.getData();
  38848. var offset = data.getLayout('offset');
  38849. var size = data.getLayout('size');
  38850. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  38851. pt_1[offsetIndex] += offset + size / 2;
  38852. }
  38853. return pt_1;
  38854. }
  38855. return [NaN, NaN];
  38856. };
  38857. BaseBarSeriesModel.type = 'series.__base_bar__';
  38858. BaseBarSeriesModel.defaultOption = {
  38859. // zlevel: 0,
  38860. z: 2,
  38861. coordinateSystem: 'cartesian2d',
  38862. legendHoverLink: true,
  38863. // stack: null
  38864. // Cartesian coordinate system
  38865. // xAxisIndex: 0,
  38866. // yAxisIndex: 0,
  38867. barMinHeight: 0,
  38868. barMinAngle: 0,
  38869. // cursor: null,
  38870. large: false,
  38871. largeThreshold: 400,
  38872. progressive: 3e3,
  38873. progressiveChunkMode: 'mod'
  38874. };
  38875. return BaseBarSeriesModel;
  38876. }(SeriesModel);
  38877. SeriesModel.registerClass(BaseBarSeriesModel);
  38878. var BarSeriesModel =
  38879. /** @class */
  38880. function (_super) {
  38881. __extends(BarSeriesModel, _super);
  38882. function BarSeriesModel() {
  38883. var _this = _super !== null && _super.apply(this, arguments) || this;
  38884. _this.type = BarSeriesModel.type;
  38885. return _this;
  38886. }
  38887. BarSeriesModel.prototype.getInitialData = function () {
  38888. return createSeriesData(null, this, {
  38889. useEncodeDefaulter: true,
  38890. createInvertedIndices: !!this.get('realtimeSort', true) || null
  38891. });
  38892. };
  38893. /**
  38894. * @override
  38895. */
  38896. BarSeriesModel.prototype.getProgressive = function () {
  38897. // Do not support progressive in normal mode.
  38898. return this.get('large') ? this.get('progressive') : false;
  38899. };
  38900. /**
  38901. * @override
  38902. */
  38903. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  38904. // Do not support progressive in normal mode.
  38905. var progressiveThreshold = this.get('progressiveThreshold');
  38906. var largeThreshold = this.get('largeThreshold');
  38907. if (largeThreshold > progressiveThreshold) {
  38908. progressiveThreshold = largeThreshold;
  38909. }
  38910. return progressiveThreshold;
  38911. };
  38912. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38913. return selectors.rect(data.getItemLayout(dataIndex));
  38914. };
  38915. BarSeriesModel.type = 'series.bar';
  38916. BarSeriesModel.dependencies = ['grid', 'polar'];
  38917. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  38918. // If clipped
  38919. // Only available on cartesian2d
  38920. clip: true,
  38921. roundCap: false,
  38922. showBackground: false,
  38923. backgroundStyle: {
  38924. color: 'rgba(180, 180, 180, 0.2)',
  38925. borderColor: null,
  38926. borderWidth: 0,
  38927. borderType: 'solid',
  38928. borderRadius: 0,
  38929. shadowBlur: 0,
  38930. shadowColor: null,
  38931. shadowOffsetX: 0,
  38932. shadowOffsetY: 0,
  38933. opacity: 1
  38934. },
  38935. select: {
  38936. itemStyle: {
  38937. borderColor: '#212121'
  38938. }
  38939. },
  38940. realtimeSort: false
  38941. });
  38942. return BarSeriesModel;
  38943. }(BaseBarSeriesModel);
  38944. /**
  38945. * Sausage: similar to sector, but have half circle on both sides
  38946. */
  38947. var SausageShape =
  38948. /** @class */
  38949. function () {
  38950. function SausageShape() {
  38951. this.cx = 0;
  38952. this.cy = 0;
  38953. this.r0 = 0;
  38954. this.r = 0;
  38955. this.startAngle = 0;
  38956. this.endAngle = Math.PI * 2;
  38957. this.clockwise = true;
  38958. }
  38959. return SausageShape;
  38960. }();
  38961. var SausagePath =
  38962. /** @class */
  38963. function (_super) {
  38964. __extends(SausagePath, _super);
  38965. function SausagePath(opts) {
  38966. var _this = _super.call(this, opts) || this;
  38967. _this.type = 'sausage';
  38968. return _this;
  38969. }
  38970. SausagePath.prototype.getDefaultShape = function () {
  38971. return new SausageShape();
  38972. };
  38973. SausagePath.prototype.buildPath = function (ctx, shape) {
  38974. var cx = shape.cx;
  38975. var cy = shape.cy;
  38976. var r0 = Math.max(shape.r0 || 0, 0);
  38977. var r = Math.max(shape.r, 0);
  38978. var dr = (r - r0) * 0.5;
  38979. var rCenter = r0 + dr;
  38980. var startAngle = shape.startAngle;
  38981. var endAngle = shape.endAngle;
  38982. var clockwise = shape.clockwise;
  38983. var PI2 = Math.PI * 2;
  38984. var lessThanCircle = clockwise ? endAngle - startAngle < PI2 : startAngle - endAngle < PI2;
  38985. if (!lessThanCircle) {
  38986. // Normalize angles
  38987. startAngle = endAngle - (clockwise ? PI2 : -PI2);
  38988. }
  38989. var unitStartX = Math.cos(startAngle);
  38990. var unitStartY = Math.sin(startAngle);
  38991. var unitEndX = Math.cos(endAngle);
  38992. var unitEndY = Math.sin(endAngle);
  38993. if (lessThanCircle) {
  38994. ctx.moveTo(unitStartX * r0 + cx, unitStartY * r0 + cy);
  38995. ctx.arc(unitStartX * rCenter + cx, unitStartY * rCenter + cy, dr, -Math.PI + startAngle, startAngle, !clockwise);
  38996. } else {
  38997. ctx.moveTo(unitStartX * r + cx, unitStartY * r + cy);
  38998. }
  38999. ctx.arc(cx, cy, r, startAngle, endAngle, !clockwise);
  39000. ctx.arc(unitEndX * rCenter + cx, unitEndY * rCenter + cy, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  39001. if (r0 !== 0) {
  39002. ctx.arc(cx, cy, r0, endAngle, startAngle, clockwise);
  39003. } // ctx.closePath();
  39004. };
  39005. return SausagePath;
  39006. }(Path);
  39007. function createSectorCalculateTextPosition(positionMapping, opts) {
  39008. opts = opts || {};
  39009. var isRoundCap = opts.isRoundCap;
  39010. return function (out, opts, boundingRect) {
  39011. var textPosition = opts.position;
  39012. if (!textPosition || textPosition instanceof Array) {
  39013. return calculateTextPosition(out, opts, boundingRect);
  39014. }
  39015. var mappedSectorPosition = positionMapping(textPosition);
  39016. var distance = opts.distance != null ? opts.distance : 5;
  39017. var sector = this.shape;
  39018. var cx = sector.cx;
  39019. var cy = sector.cy;
  39020. var r = sector.r;
  39021. var r0 = sector.r0;
  39022. var middleR = (r + r0) / 2;
  39023. var startAngle = sector.startAngle;
  39024. var endAngle = sector.endAngle;
  39025. var middleAngle = (startAngle + endAngle) / 2;
  39026. var extraDist = isRoundCap ? Math.abs(r - r0) / 2 : 0;
  39027. var mathCos = Math.cos;
  39028. var mathSin = Math.sin; // base position: top-left
  39029. var x = cx + r * mathCos(startAngle);
  39030. var y = cy + r * mathSin(startAngle);
  39031. var textAlign = 'left';
  39032. var textVerticalAlign = 'top';
  39033. switch (mappedSectorPosition) {
  39034. case 'startArc':
  39035. x = cx + (r0 - distance) * mathCos(middleAngle);
  39036. y = cy + (r0 - distance) * mathSin(middleAngle);
  39037. textAlign = 'center';
  39038. textVerticalAlign = 'top';
  39039. break;
  39040. case 'insideStartArc':
  39041. x = cx + (r0 + distance) * mathCos(middleAngle);
  39042. y = cy + (r0 + distance) * mathSin(middleAngle);
  39043. textAlign = 'center';
  39044. textVerticalAlign = 'bottom';
  39045. break;
  39046. case 'startAngle':
  39047. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, distance + extraDist, false);
  39048. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, distance + extraDist, false);
  39049. textAlign = 'right';
  39050. textVerticalAlign = 'middle';
  39051. break;
  39052. case 'insideStartAngle':
  39053. x = cx + middleR * mathCos(startAngle) + adjustAngleDistanceX(startAngle, -distance + extraDist, false);
  39054. y = cy + middleR * mathSin(startAngle) + adjustAngleDistanceY(startAngle, -distance + extraDist, false);
  39055. textAlign = 'left';
  39056. textVerticalAlign = 'middle';
  39057. break;
  39058. case 'middle':
  39059. x = cx + middleR * mathCos(middleAngle);
  39060. y = cy + middleR * mathSin(middleAngle);
  39061. textAlign = 'center';
  39062. textVerticalAlign = 'middle';
  39063. break;
  39064. case 'endArc':
  39065. x = cx + (r + distance) * mathCos(middleAngle);
  39066. y = cy + (r + distance) * mathSin(middleAngle);
  39067. textAlign = 'center';
  39068. textVerticalAlign = 'bottom';
  39069. break;
  39070. case 'insideEndArc':
  39071. x = cx + (r - distance) * mathCos(middleAngle);
  39072. y = cy + (r - distance) * mathSin(middleAngle);
  39073. textAlign = 'center';
  39074. textVerticalAlign = 'top';
  39075. break;
  39076. case 'endAngle':
  39077. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, distance + extraDist, true);
  39078. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, distance + extraDist, true);
  39079. textAlign = 'left';
  39080. textVerticalAlign = 'middle';
  39081. break;
  39082. case 'insideEndAngle':
  39083. x = cx + middleR * mathCos(endAngle) + adjustAngleDistanceX(endAngle, -distance + extraDist, true);
  39084. y = cy + middleR * mathSin(endAngle) + adjustAngleDistanceY(endAngle, -distance + extraDist, true);
  39085. textAlign = 'right';
  39086. textVerticalAlign = 'middle';
  39087. break;
  39088. default:
  39089. return calculateTextPosition(out, opts, boundingRect);
  39090. }
  39091. out = out || {};
  39092. out.x = x;
  39093. out.y = y;
  39094. out.align = textAlign;
  39095. out.verticalAlign = textVerticalAlign;
  39096. return out;
  39097. };
  39098. }
  39099. function setSectorTextRotation(sector, textPosition, positionMapping, rotateType) {
  39100. if (isNumber(rotateType)) {
  39101. // user-set rotation
  39102. sector.setTextConfig({
  39103. rotation: rotateType
  39104. });
  39105. return;
  39106. } else if (isArray(textPosition)) {
  39107. // user-set position, use 0 as auto rotation
  39108. sector.setTextConfig({
  39109. rotation: 0
  39110. });
  39111. return;
  39112. }
  39113. var shape = sector.shape;
  39114. var startAngle = shape.clockwise ? shape.startAngle : shape.endAngle;
  39115. var endAngle = shape.clockwise ? shape.endAngle : shape.startAngle;
  39116. var middleAngle = (startAngle + endAngle) / 2;
  39117. var anchorAngle;
  39118. var mappedSectorPosition = positionMapping(textPosition);
  39119. switch (mappedSectorPosition) {
  39120. case 'startArc':
  39121. case 'insideStartArc':
  39122. case 'middle':
  39123. case 'insideEndArc':
  39124. case 'endArc':
  39125. anchorAngle = middleAngle;
  39126. break;
  39127. case 'startAngle':
  39128. case 'insideStartAngle':
  39129. anchorAngle = startAngle;
  39130. break;
  39131. case 'endAngle':
  39132. case 'insideEndAngle':
  39133. anchorAngle = endAngle;
  39134. break;
  39135. default:
  39136. sector.setTextConfig({
  39137. rotation: 0
  39138. });
  39139. return;
  39140. }
  39141. var rotate = Math.PI * 1.5 - anchorAngle;
  39142. /**
  39143. * TODO: labels with rotate > Math.PI / 2 should be rotate another
  39144. * half round flipped to increase readability. However, only middle
  39145. * position supports this for now, because in other positions, the
  39146. * anchor point is not at the center of the text, so the positions
  39147. * after rotating is not as expected.
  39148. */
  39149. if (mappedSectorPosition === 'middle' && rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  39150. rotate -= Math.PI;
  39151. }
  39152. sector.setTextConfig({
  39153. rotation: rotate
  39154. });
  39155. }
  39156. function adjustAngleDistanceX(angle, distance, isEnd) {
  39157. return distance * Math.sin(angle) * (isEnd ? -1 : 1);
  39158. }
  39159. function adjustAngleDistanceY(angle, distance, isEnd) {
  39160. return distance * Math.cos(angle) * (isEnd ? 1 : -1);
  39161. }
  39162. function getSectorCornerRadius(model, shape, zeroIfNull) {
  39163. var cornerRadius = model.get('borderRadius');
  39164. if (cornerRadius == null) {
  39165. return zeroIfNull ? {
  39166. cornerRadius: 0
  39167. } : null;
  39168. }
  39169. if (!isArray(cornerRadius)) {
  39170. cornerRadius = [cornerRadius, cornerRadius, cornerRadius, cornerRadius];
  39171. }
  39172. var dr = Math.abs(shape.r || 0 - shape.r0 || 0);
  39173. return {
  39174. cornerRadius: map(cornerRadius, function (cr) {
  39175. return parsePercent(cr, dr);
  39176. })
  39177. };
  39178. }
  39179. var mathMax$6 = Math.max;
  39180. var mathMin$6 = Math.min;
  39181. function getClipArea(coord, data) {
  39182. var coordSysClipArea = coord.getArea && coord.getArea();
  39183. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39184. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  39185. // We should not clip this part.
  39186. // See test/bar2.html
  39187. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  39188. var expandWidth = data.getLayout('bandWidth');
  39189. if (baseAxis.isHorizontal()) {
  39190. coordSysClipArea.x -= expandWidth;
  39191. coordSysClipArea.width += expandWidth * 2;
  39192. } else {
  39193. coordSysClipArea.y -= expandWidth;
  39194. coordSysClipArea.height += expandWidth * 2;
  39195. }
  39196. }
  39197. }
  39198. return coordSysClipArea;
  39199. }
  39200. var BarView =
  39201. /** @class */
  39202. function (_super) {
  39203. __extends(BarView, _super);
  39204. function BarView() {
  39205. var _this = _super.call(this) || this;
  39206. _this.type = BarView.type;
  39207. _this._isFirstFrame = true;
  39208. return _this;
  39209. }
  39210. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  39211. this._model = seriesModel;
  39212. this._removeOnRenderedListener(api);
  39213. this._updateDrawMode(seriesModel);
  39214. var coordinateSystemType = seriesModel.get('coordinateSystem');
  39215. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  39216. // Clear previously rendered progressive elements.
  39217. this._progressiveEls = null;
  39218. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  39219. } else if ("development" !== 'production') {
  39220. warn('Only cartesian2d and polar supported for bar.');
  39221. }
  39222. };
  39223. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  39224. this._clear();
  39225. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  39226. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  39227. this._updateLargeClip(seriesModel);
  39228. };
  39229. BarView.prototype.incrementalRender = function (params, seriesModel) {
  39230. // Reset
  39231. this._progressiveEls = []; // Do not support progressive in normal mode.
  39232. this._incrementalRenderLarge(params, seriesModel);
  39233. };
  39234. BarView.prototype.eachRendered = function (cb) {
  39235. traverseElements(this._progressiveEls || this.group, cb);
  39236. };
  39237. BarView.prototype._updateDrawMode = function (seriesModel) {
  39238. var isLargeDraw = seriesModel.pipelineContext.large;
  39239. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  39240. this._isLargeDraw = isLargeDraw;
  39241. this._clear();
  39242. }
  39243. };
  39244. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  39245. var group = this.group;
  39246. var data = seriesModel.getData();
  39247. var oldData = this._data;
  39248. var coord = seriesModel.coordinateSystem;
  39249. var baseAxis = coord.getBaseAxis();
  39250. var isHorizontalOrRadial;
  39251. if (coord.type === 'cartesian2d') {
  39252. isHorizontalOrRadial = baseAxis.isHorizontal();
  39253. } else if (coord.type === 'polar') {
  39254. isHorizontalOrRadial = baseAxis.dim === 'angle';
  39255. }
  39256. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  39257. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  39258. if (realtimeSortCfg) {
  39259. this._enableRealtimeSort(realtimeSortCfg, data, api);
  39260. }
  39261. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  39262. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  39263. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  39264. // And don't want the label are clipped.
  39265. var roundCap = seriesModel.get('roundCap', true);
  39266. var drawBackground = seriesModel.get('showBackground', true);
  39267. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39268. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  39269. var bgEls = [];
  39270. var oldBgEls = this._backgroundEls;
  39271. var isInitSort = payload && payload.isInitSort;
  39272. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  39273. function createBackground(dataIndex) {
  39274. var bgLayout = getLayout[coord.type](data, dataIndex);
  39275. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  39276. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39277. if (coord.type === 'cartesian2d') {
  39278. bgEl.setShape('r', barBorderRadius);
  39279. } else {
  39280. bgEl.setShape('cornerRadius', barBorderRadius);
  39281. }
  39282. bgEls[dataIndex] = bgEl;
  39283. return bgEl;
  39284. }
  39285. data.diff(oldData).add(function (dataIndex) {
  39286. var itemModel = data.getItemModel(dataIndex);
  39287. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  39288. if (drawBackground) {
  39289. createBackground(dataIndex);
  39290. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  39291. if (!data.hasValue(dataIndex) || !isValidLayout[coord.type](layout)) {
  39292. return;
  39293. }
  39294. var isClipped = false;
  39295. if (needsClip) {
  39296. // Clip will modify the layout params.
  39297. // And return a boolean to determine if the shape are fully clipped.
  39298. isClipped = clip[coord.type](coordSysClipArea, layout);
  39299. }
  39300. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  39301. if (realtimeSortCfg) {
  39302. /**
  39303. * Force label animation because even if the element is
  39304. * ignored because it's clipped, it may not be clipped after
  39305. * changing order. Then, if not using forceLabelAnimation,
  39306. * the label animation was never started, in which case,
  39307. * the label will be the final value and doesn't have label
  39308. * animation.
  39309. */
  39310. el.forceLabelAnimation = true;
  39311. }
  39312. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39313. if (isInitSort) {
  39314. el.attr({
  39315. shape: layout
  39316. });
  39317. } else if (realtimeSortCfg) {
  39318. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  39319. } else {
  39320. initProps(el, {
  39321. shape: layout
  39322. }, seriesModel, dataIndex);
  39323. }
  39324. data.setItemGraphicEl(dataIndex, el);
  39325. group.add(el);
  39326. el.ignore = isClipped;
  39327. }).update(function (newIndex, oldIndex) {
  39328. var itemModel = data.getItemModel(newIndex);
  39329. var layout = getLayout[coord.type](data, newIndex, itemModel);
  39330. if (drawBackground) {
  39331. var bgEl = void 0;
  39332. if (oldBgEls.length === 0) {
  39333. bgEl = createBackground(oldIndex);
  39334. } else {
  39335. bgEl = oldBgEls[oldIndex];
  39336. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  39337. if (coord.type === 'cartesian2d') {
  39338. bgEl.setShape('r', barBorderRadius);
  39339. } else {
  39340. bgEl.setShape('cornerRadius', barBorderRadius);
  39341. }
  39342. bgEls[newIndex] = bgEl;
  39343. }
  39344. var bgLayout = getLayout[coord.type](data, newIndex);
  39345. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  39346. updateProps(bgEl, {
  39347. shape: shape
  39348. }, animationModel, newIndex);
  39349. }
  39350. var el = oldData.getItemGraphicEl(oldIndex);
  39351. if (!data.hasValue(newIndex) || !isValidLayout[coord.type](layout)) {
  39352. group.remove(el);
  39353. return;
  39354. }
  39355. var isClipped = false;
  39356. if (needsClip) {
  39357. isClipped = clip[coord.type](coordSysClipArea, layout);
  39358. if (isClipped) {
  39359. group.remove(el);
  39360. }
  39361. }
  39362. if (!el) {
  39363. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  39364. } else {
  39365. saveOldStyle(el);
  39366. }
  39367. if (realtimeSortCfg) {
  39368. el.forceLabelAnimation = true;
  39369. }
  39370. if (isChangeOrder) {
  39371. var textEl = el.getTextContent();
  39372. if (textEl) {
  39373. var labelInnerStore = labelInner(textEl);
  39374. if (labelInnerStore.prevValue != null) {
  39375. /**
  39376. * Set preValue to be value so that no new label
  39377. * should be started, otherwise, it will take a full
  39378. * `animationDurationUpdate` time to finish the
  39379. * animation, which is not expected.
  39380. */
  39381. labelInnerStore.prevValue = labelInnerStore.value;
  39382. }
  39383. }
  39384. } // Not change anything if only order changed.
  39385. // Especially not change label.
  39386. else {
  39387. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  39388. }
  39389. if (isInitSort) {
  39390. el.attr({
  39391. shape: layout
  39392. });
  39393. } else if (realtimeSortCfg) {
  39394. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  39395. } else {
  39396. updateProps(el, {
  39397. shape: layout
  39398. }, seriesModel, newIndex, null);
  39399. }
  39400. data.setItemGraphicEl(newIndex, el);
  39401. el.ignore = isClipped;
  39402. group.add(el);
  39403. }).remove(function (dataIndex) {
  39404. var el = oldData.getItemGraphicEl(dataIndex);
  39405. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  39406. }).execute();
  39407. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  39408. bgGroup.removeAll();
  39409. for (var i = 0; i < bgEls.length; ++i) {
  39410. bgGroup.add(bgEls[i]);
  39411. }
  39412. group.add(bgGroup);
  39413. this._backgroundEls = bgEls;
  39414. this._data = data;
  39415. };
  39416. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  39417. this._clear();
  39418. createLarge(seriesModel, this.group);
  39419. this._updateLargeClip(seriesModel);
  39420. };
  39421. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  39422. this._removeBackground();
  39423. createLarge(seriesModel, this.group, this._progressiveEls, true);
  39424. };
  39425. BarView.prototype._updateLargeClip = function (seriesModel) {
  39426. // Use clipPath in large mode.
  39427. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  39428. var group = this.group;
  39429. if (clipPath) {
  39430. group.setClipPath(clipPath);
  39431. } else {
  39432. group.removeClipPath();
  39433. }
  39434. };
  39435. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  39436. var _this = this; // If no data in the first frame, wait for data to initSort
  39437. if (!data.count()) {
  39438. return;
  39439. }
  39440. var baseAxis = realtimeSortCfg.baseAxis;
  39441. if (this._isFirstFrame) {
  39442. this._dispatchInitSort(data, realtimeSortCfg, api);
  39443. this._isFirstFrame = false;
  39444. } else {
  39445. var orderMapping_1 = function (idx) {
  39446. var el = data.getItemGraphicEl(idx);
  39447. var shape = el && el.shape;
  39448. return shape && // The result should be consistent with the initial sort by data value.
  39449. // Do not support the case that both positive and negative exist.
  39450. Math.abs(baseAxis.isHorizontal() ? shape.height : shape.width) // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  39451. || 0;
  39452. };
  39453. this._onRendered = function () {
  39454. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  39455. };
  39456. api.getZr().on('rendered', this._onRendered);
  39457. }
  39458. };
  39459. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  39460. var info = [];
  39461. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  39462. var mappedValue = orderMapping(dataIdx);
  39463. mappedValue = mappedValue == null ? NaN : mappedValue;
  39464. info.push({
  39465. dataIndex: dataIdx,
  39466. mappedValue: mappedValue,
  39467. ordinalNumber: ordinalNumber
  39468. });
  39469. });
  39470. info.sort(function (a, b) {
  39471. // If NaN, it will be treated as min val.
  39472. return b.mappedValue - a.mappedValue;
  39473. });
  39474. return {
  39475. ordinalNumbers: map(info, function (item) {
  39476. return item.ordinalNumber;
  39477. })
  39478. };
  39479. };
  39480. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  39481. var scale = baseAxis.scale;
  39482. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  39483. var lastValue = Number.MAX_VALUE;
  39484. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  39485. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  39486. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  39487. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  39488. : orderMapping(data.indexOfRawIndex(rawIdx));
  39489. if (value > lastValue) {
  39490. return true;
  39491. }
  39492. lastValue = value;
  39493. }
  39494. return false;
  39495. };
  39496. /*
  39497. * Consider the case when A and B changed order, whose representing
  39498. * bars are both out of sight, we don't wish to trigger reorder action
  39499. * as long as the order in the view doesn't change.
  39500. */
  39501. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  39502. var scale = baseAxis.scale;
  39503. var extent = scale.getExtent();
  39504. var tickNum = Math.max(0, extent[0]);
  39505. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  39506. for (; tickNum <= tickMax; ++tickNum) {
  39507. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  39508. return true;
  39509. }
  39510. }
  39511. };
  39512. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  39513. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  39514. return;
  39515. }
  39516. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  39517. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  39518. this._removeOnRenderedListener(api);
  39519. api.dispatchAction({
  39520. type: 'changeAxisOrder',
  39521. componentType: baseAxis.dim + 'Axis',
  39522. axisId: baseAxis.index,
  39523. sortInfo: sortInfo
  39524. });
  39525. }
  39526. };
  39527. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  39528. var baseAxis = realtimeSortCfg.baseAxis;
  39529. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  39530. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  39531. });
  39532. api.dispatchAction({
  39533. type: 'changeAxisOrder',
  39534. componentType: baseAxis.dim + 'Axis',
  39535. isInitSort: true,
  39536. axisId: baseAxis.index,
  39537. sortInfo: sortResult
  39538. });
  39539. };
  39540. BarView.prototype.remove = function (ecModel, api) {
  39541. this._clear(this._model);
  39542. this._removeOnRenderedListener(api);
  39543. };
  39544. BarView.prototype.dispose = function (ecModel, api) {
  39545. this._removeOnRenderedListener(api);
  39546. };
  39547. BarView.prototype._removeOnRenderedListener = function (api) {
  39548. if (this._onRendered) {
  39549. api.getZr().off('rendered', this._onRendered);
  39550. this._onRendered = null;
  39551. }
  39552. };
  39553. BarView.prototype._clear = function (model) {
  39554. var group = this.group;
  39555. var data = this._data;
  39556. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  39557. this._removeBackground();
  39558. this._backgroundEls = [];
  39559. data.eachItemGraphicEl(function (el) {
  39560. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  39561. });
  39562. } else {
  39563. group.removeAll();
  39564. }
  39565. this._data = null;
  39566. this._isFirstFrame = true;
  39567. };
  39568. BarView.prototype._removeBackground = function () {
  39569. this.group.remove(this._backgroundGroup);
  39570. this._backgroundGroup = null;
  39571. };
  39572. BarView.type = 'bar';
  39573. return BarView;
  39574. }(ChartView);
  39575. var clip = {
  39576. cartesian2d: function (coordSysBoundingRect, layout) {
  39577. var signWidth = layout.width < 0 ? -1 : 1;
  39578. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  39579. if (signWidth < 0) {
  39580. layout.x += layout.width;
  39581. layout.width = -layout.width;
  39582. }
  39583. if (signHeight < 0) {
  39584. layout.y += layout.height;
  39585. layout.height = -layout.height;
  39586. }
  39587. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  39588. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  39589. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  39590. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  39591. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  39592. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  39593. var xClipped = x2 < x;
  39594. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  39595. // But we should also place the element at the edge of the coord sys bounding rect.
  39596. // Because if data changed and the bar shows again, its transition animation
  39597. // will begin at this place.
  39598. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  39599. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  39600. layout.width = xClipped ? 0 : x2 - x;
  39601. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  39602. if (signWidth < 0) {
  39603. layout.x += layout.width;
  39604. layout.width = -layout.width;
  39605. }
  39606. if (signHeight < 0) {
  39607. layout.y += layout.height;
  39608. layout.height = -layout.height;
  39609. }
  39610. return xClipped || yClipped;
  39611. },
  39612. polar: function (coordSysClipArea, layout) {
  39613. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  39614. if (signR < 0) {
  39615. var tmp = layout.r;
  39616. layout.r = layout.r0;
  39617. layout.r0 = tmp;
  39618. }
  39619. var r = mathMin$6(layout.r, coordSysClipArea.r);
  39620. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  39621. layout.r = r;
  39622. layout.r0 = r0;
  39623. var clipped = r - r0 < 0; // Reverse back
  39624. if (signR < 0) {
  39625. var tmp = layout.r;
  39626. layout.r = layout.r0;
  39627. layout.r0 = tmp;
  39628. }
  39629. return clipped;
  39630. }
  39631. };
  39632. var elementCreator = {
  39633. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  39634. var rect = new Rect({
  39635. shape: extend({}, layout),
  39636. z2: 1
  39637. });
  39638. rect.__dataIndex = newIndex;
  39639. rect.name = 'item';
  39640. if (animationModel) {
  39641. var rectShape = rect.shape;
  39642. var animateProperty = isHorizontal ? 'height' : 'width';
  39643. rectShape[animateProperty] = 0;
  39644. }
  39645. return rect;
  39646. },
  39647. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  39648. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  39649. var sector = new ShapeClass({
  39650. shape: layout,
  39651. z2: 1
  39652. });
  39653. sector.name = 'item';
  39654. var positionMap = createPolarPositionMapping(isRadial);
  39655. sector.calculateTextPosition = createSectorCalculateTextPosition(positionMap, {
  39656. isRoundCap: ShapeClass === SausagePath
  39657. }); // Animation
  39658. if (animationModel) {
  39659. var sectorShape = sector.shape;
  39660. var animateProperty = isRadial ? 'r' : 'endAngle';
  39661. var animateTarget = {};
  39662. sectorShape[animateProperty] = isRadial ? layout.r0 : layout.startAngle;
  39663. animateTarget[animateProperty] = layout[animateProperty];
  39664. (isUpdate ? updateProps : initProps)(sector, {
  39665. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  39666. }, animationModel);
  39667. }
  39668. return sector;
  39669. }
  39670. };
  39671. function shouldRealtimeSort(seriesModel, coordSys) {
  39672. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  39673. var baseAxis = coordSys.getBaseAxis();
  39674. if ("development" !== 'production') {
  39675. if (realtimeSortOption) {
  39676. if (baseAxis.type !== 'category') {
  39677. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  39678. }
  39679. if (coordSys.type !== 'cartesian2d') {
  39680. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  39681. }
  39682. }
  39683. }
  39684. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  39685. return {
  39686. baseAxis: baseAxis,
  39687. otherAxis: coordSys.getOtherAxis(baseAxis)
  39688. };
  39689. }
  39690. }
  39691. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  39692. var seriesTarget;
  39693. var axisTarget;
  39694. if (isHorizontal) {
  39695. axisTarget = {
  39696. x: layout.x,
  39697. width: layout.width
  39698. };
  39699. seriesTarget = {
  39700. y: layout.y,
  39701. height: layout.height
  39702. };
  39703. } else {
  39704. axisTarget = {
  39705. y: layout.y,
  39706. height: layout.height
  39707. };
  39708. seriesTarget = {
  39709. x: layout.x,
  39710. width: layout.width
  39711. };
  39712. }
  39713. if (!isChangeOrder) {
  39714. // Keep the original growth animation if only axis order changed.
  39715. // Not start a new animation.
  39716. (isUpdate ? updateProps : initProps)(el, {
  39717. shape: seriesTarget
  39718. }, seriesAnimationModel, newIndex, null);
  39719. }
  39720. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  39721. (isUpdate ? updateProps : initProps)(el, {
  39722. shape: axisTarget
  39723. }, axisAnimationModel, newIndex);
  39724. }
  39725. function checkPropertiesNotValid(obj, props) {
  39726. for (var i = 0; i < props.length; i++) {
  39727. if (!isFinite(obj[props[i]])) {
  39728. return true;
  39729. }
  39730. }
  39731. return false;
  39732. }
  39733. var rectPropties = ['x', 'y', 'width', 'height'];
  39734. var polarPropties = ['cx', 'cy', 'r', 'startAngle', 'endAngle'];
  39735. var isValidLayout = {
  39736. cartesian2d: function (layout) {
  39737. return !checkPropertiesNotValid(layout, rectPropties);
  39738. },
  39739. polar: function (layout) {
  39740. return !checkPropertiesNotValid(layout, polarPropties);
  39741. }
  39742. };
  39743. var getLayout = {
  39744. // itemModel is only used to get borderWidth, which is not needed
  39745. // when calculating bar background layout.
  39746. cartesian2d: function (data, dataIndex, itemModel) {
  39747. var layout = data.getItemLayout(dataIndex);
  39748. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  39749. var signX = layout.width > 0 ? 1 : -1;
  39750. var signY = layout.height > 0 ? 1 : -1;
  39751. return {
  39752. x: layout.x + signX * fixedLineWidth / 2,
  39753. y: layout.y + signY * fixedLineWidth / 2,
  39754. width: layout.width - signX * fixedLineWidth,
  39755. height: layout.height - signY * fixedLineWidth
  39756. };
  39757. },
  39758. polar: function (data, dataIndex, itemModel) {
  39759. var layout = data.getItemLayout(dataIndex);
  39760. return {
  39761. cx: layout.cx,
  39762. cy: layout.cy,
  39763. r0: layout.r0,
  39764. r: layout.r,
  39765. startAngle: layout.startAngle,
  39766. endAngle: layout.endAngle,
  39767. clockwise: layout.clockwise
  39768. };
  39769. }
  39770. };
  39771. function isZeroOnPolar(layout) {
  39772. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  39773. }
  39774. function createPolarPositionMapping(isRadial) {
  39775. return function (isRadial) {
  39776. var arcOrAngle = isRadial ? 'Arc' : 'Angle';
  39777. return function (position) {
  39778. switch (position) {
  39779. case 'start':
  39780. case 'insideStart':
  39781. case 'end':
  39782. case 'insideEnd':
  39783. return position + arcOrAngle;
  39784. default:
  39785. return position;
  39786. }
  39787. };
  39788. }(isRadial);
  39789. }
  39790. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, isPolar) {
  39791. var style = data.getItemVisual(dataIndex, 'style');
  39792. if (!isPolar) {
  39793. var borderRadius = itemModel.get(['itemStyle', 'borderRadius']) || 0;
  39794. el.setShape('r', borderRadius);
  39795. } else if (!seriesModel.get('roundCap')) {
  39796. var sectorShape = el.shape;
  39797. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  39798. extend(sectorShape, cornerRadius);
  39799. el.setShape(sectorShape);
  39800. }
  39801. el.useStyle(style);
  39802. var cursorStyle = itemModel.getShallow('cursor');
  39803. cursorStyle && el.attr('cursor', cursorStyle);
  39804. 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';
  39805. var labelStatesModels = getLabelStatesModels(itemModel);
  39806. setLabelStyle(el, labelStatesModels, {
  39807. labelFetcher: seriesModel,
  39808. labelDataIndex: dataIndex,
  39809. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  39810. inheritColor: style.fill,
  39811. defaultOpacity: style.opacity,
  39812. defaultOutsidePosition: labelPositionOutside
  39813. });
  39814. var label = el.getTextContent();
  39815. if (isPolar && label) {
  39816. var position = itemModel.get(['label', 'position']);
  39817. el.textConfig.inside = position === 'middle' ? true : null;
  39818. setSectorTextRotation(el, position === 'outside' ? labelPositionOutside : position, createPolarPositionMapping(isHorizontalOrRadial), itemModel.get(['label', 'rotate']));
  39819. }
  39820. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  39821. return getDefaultInterpolatedLabel(data, value);
  39822. });
  39823. var emphasisModel = itemModel.getModel(['emphasis']);
  39824. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  39825. setStatesStylesFromModel(el, itemModel);
  39826. if (isZeroOnPolar(layout)) {
  39827. el.style.fill = 'none';
  39828. el.style.stroke = 'none';
  39829. each(el.states, function (state) {
  39830. if (state.style) {
  39831. state.style.fill = state.style.stroke = 'none';
  39832. }
  39833. });
  39834. }
  39835. } // In case width or height are too small.
  39836. function getLineWidth(itemModel, rawLayout) {
  39837. // Has no border.
  39838. var borderColor = itemModel.get(['itemStyle', 'borderColor']);
  39839. if (!borderColor || borderColor === 'none') {
  39840. return 0;
  39841. }
  39842. var lineWidth = itemModel.get(['itemStyle', 'borderWidth']) || 0; // width or height may be NaN for empty data
  39843. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  39844. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  39845. return Math.min(lineWidth, width, height);
  39846. }
  39847. var LagePathShape =
  39848. /** @class */
  39849. function () {
  39850. function LagePathShape() {}
  39851. return LagePathShape;
  39852. }();
  39853. var LargePath =
  39854. /** @class */
  39855. function (_super) {
  39856. __extends(LargePath, _super);
  39857. function LargePath(opts) {
  39858. var _this = _super.call(this, opts) || this;
  39859. _this.type = 'largeBar';
  39860. return _this;
  39861. }
  39862. LargePath.prototype.getDefaultShape = function () {
  39863. return new LagePathShape();
  39864. };
  39865. LargePath.prototype.buildPath = function (ctx, shape) {
  39866. // Drawing lines is more efficient than drawing
  39867. // a whole line or drawing rects.
  39868. var points = shape.points;
  39869. var baseDimIdx = this.baseDimIdx;
  39870. var valueDimIdx = 1 - this.baseDimIdx;
  39871. var startPoint = [];
  39872. var size = [];
  39873. var barWidth = this.barWidth;
  39874. for (var i = 0; i < points.length; i += 3) {
  39875. size[baseDimIdx] = barWidth;
  39876. size[valueDimIdx] = points[i + 2];
  39877. startPoint[baseDimIdx] = points[i + baseDimIdx];
  39878. startPoint[valueDimIdx] = points[i + valueDimIdx];
  39879. ctx.rect(startPoint[0], startPoint[1], size[0], size[1]);
  39880. }
  39881. };
  39882. return LargePath;
  39883. }(Path);
  39884. function createLarge(seriesModel, group, progressiveEls, incremental) {
  39885. // TODO support polar
  39886. var data = seriesModel.getData();
  39887. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  39888. var largeDataIndices = data.getLayout('largeDataIndices');
  39889. var barWidth = data.getLayout('size');
  39890. var backgroundModel = seriesModel.getModel('backgroundStyle');
  39891. var bgPoints = data.getLayout('largeBackgroundPoints');
  39892. if (bgPoints) {
  39893. var bgEl = new LargePath({
  39894. shape: {
  39895. points: bgPoints
  39896. },
  39897. incremental: !!incremental,
  39898. silent: true,
  39899. z2: 0
  39900. });
  39901. bgEl.baseDimIdx = baseDimIdx;
  39902. bgEl.largeDataIndices = largeDataIndices;
  39903. bgEl.barWidth = barWidth;
  39904. bgEl.useStyle(backgroundModel.getItemStyle());
  39905. group.add(bgEl);
  39906. progressiveEls && progressiveEls.push(bgEl);
  39907. }
  39908. var el = new LargePath({
  39909. shape: {
  39910. points: data.getLayout('largePoints')
  39911. },
  39912. incremental: !!incremental,
  39913. ignoreCoarsePointer: true,
  39914. z2: 1
  39915. });
  39916. el.baseDimIdx = baseDimIdx;
  39917. el.largeDataIndices = largeDataIndices;
  39918. el.barWidth = barWidth;
  39919. group.add(el);
  39920. el.useStyle(data.getVisual('style')); // Enable tooltip and user mouse/touch event handlers.
  39921. getECData(el).seriesIndex = seriesModel.seriesIndex;
  39922. if (!seriesModel.get('silent')) {
  39923. el.on('mousedown', largePathUpdateDataIndex);
  39924. el.on('mousemove', largePathUpdateDataIndex);
  39925. }
  39926. progressiveEls && progressiveEls.push(el);
  39927. } // Use throttle to avoid frequently traverse to find dataIndex.
  39928. var largePathUpdateDataIndex = throttle(function (event) {
  39929. var largePath = this;
  39930. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  39931. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  39932. }, 30, false);
  39933. function largePathFindDataIndex(largePath, x, y) {
  39934. var baseDimIdx = largePath.baseDimIdx;
  39935. var valueDimIdx = 1 - baseDimIdx;
  39936. var points = largePath.shape.points;
  39937. var largeDataIndices = largePath.largeDataIndices;
  39938. var startPoint = [];
  39939. var size = [];
  39940. var barWidth = largePath.barWidth;
  39941. for (var i = 0, len = points.length / 3; i < len; i++) {
  39942. var ii = i * 3;
  39943. size[baseDimIdx] = barWidth;
  39944. size[valueDimIdx] = points[ii + 2];
  39945. startPoint[baseDimIdx] = points[ii + baseDimIdx];
  39946. startPoint[valueDimIdx] = points[ii + valueDimIdx];
  39947. if (size[valueDimIdx] < 0) {
  39948. startPoint[valueDimIdx] += size[valueDimIdx];
  39949. size[valueDimIdx] = -size[valueDimIdx];
  39950. }
  39951. if (x >= startPoint[0] && x <= startPoint[0] + size[0] && y >= startPoint[1] && y <= startPoint[1] + size[1]) {
  39952. return largeDataIndices[i];
  39953. }
  39954. }
  39955. return -1;
  39956. }
  39957. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  39958. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  39959. var rectShape = layout;
  39960. var coordLayout = coord.getArea();
  39961. return {
  39962. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  39963. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  39964. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  39965. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  39966. };
  39967. } else {
  39968. var coordLayout = coord.getArea();
  39969. var sectorShape = layout;
  39970. return {
  39971. cx: coordLayout.cx,
  39972. cy: coordLayout.cy,
  39973. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  39974. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  39975. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  39976. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  39977. };
  39978. }
  39979. }
  39980. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  39981. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  39982. return new ElementClz({
  39983. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  39984. silent: true,
  39985. z2: 0
  39986. });
  39987. }
  39988. function install$3(registers) {
  39989. registers.registerChartView(BarView);
  39990. registers.registerSeriesModel(BarSeriesModel);
  39991. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Do layout after other overall layout, which can prepare some information.
  39992. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('bar')); // Down sample after filter
  39993. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  39994. /**
  39995. * @payload
  39996. * @property {string} [componentType=series]
  39997. * @property {number} [dx]
  39998. * @property {number} [dy]
  39999. * @property {number} [zoom]
  40000. * @property {number} [originX]
  40001. * @property {number} [originY]
  40002. */
  40003. registers.registerAction({
  40004. type: 'changeAxisOrder',
  40005. event: 'changeAxisOrder',
  40006. update: 'update'
  40007. }, function (payload, ecModel) {
  40008. var componentType = payload.componentType || 'series';
  40009. ecModel.eachComponent({
  40010. mainType: componentType,
  40011. query: payload
  40012. }, function (componentModel) {
  40013. if (payload.sortInfo) {
  40014. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  40015. }
  40016. });
  40017. });
  40018. }
  40019. var PI2$8 = Math.PI * 2;
  40020. var RADIAN = Math.PI / 180;
  40021. function getViewRect(seriesModel, api) {
  40022. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40023. width: api.getWidth(),
  40024. height: api.getHeight()
  40025. });
  40026. }
  40027. function getBasicPieLayout(seriesModel, api) {
  40028. var viewRect = getViewRect(seriesModel, api); // center can be string or number when coordinateSystem is specified
  40029. var center = seriesModel.get('center');
  40030. var radius = seriesModel.get('radius');
  40031. if (!isArray(radius)) {
  40032. radius = [0, radius];
  40033. }
  40034. var width = parsePercent$1(viewRect.width, api.getWidth());
  40035. var height = parsePercent$1(viewRect.height, api.getHeight());
  40036. var size = Math.min(width, height);
  40037. var r0 = parsePercent$1(radius[0], size / 2);
  40038. var r = parsePercent$1(radius[1], size / 2);
  40039. var cx;
  40040. var cy;
  40041. var coordSys = seriesModel.coordinateSystem;
  40042. if (coordSys) {
  40043. // percentage is not allowed when coordinate system is specified
  40044. var point = coordSys.dataToPoint(center);
  40045. cx = point[0] || 0;
  40046. cy = point[1] || 0;
  40047. } else {
  40048. if (!isArray(center)) {
  40049. center = [center, center];
  40050. }
  40051. cx = parsePercent$1(center[0], width) + viewRect.x;
  40052. cy = parsePercent$1(center[1], height) + viewRect.y;
  40053. }
  40054. return {
  40055. cx: cx,
  40056. cy: cy,
  40057. r0: r0,
  40058. r: r
  40059. };
  40060. }
  40061. function pieLayout(seriesType, ecModel, api) {
  40062. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  40063. var data = seriesModel.getData();
  40064. var valueDim = data.mapDimension('value');
  40065. var viewRect = getViewRect(seriesModel, api);
  40066. var _a = getBasicPieLayout(seriesModel, api),
  40067. cx = _a.cx,
  40068. cy = _a.cy,
  40069. r = _a.r,
  40070. r0 = _a.r0;
  40071. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  40072. var minAngle = seriesModel.get('minAngle') * RADIAN;
  40073. var validDataCount = 0;
  40074. data.each(valueDim, function (value) {
  40075. !isNaN(value) && validDataCount++;
  40076. });
  40077. var sum = data.getSum(valueDim); // Sum may be 0
  40078. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  40079. var clockwise = seriesModel.get('clockwise');
  40080. var roseType = seriesModel.get('roseType');
  40081. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  40082. var extent = data.getDataExtent(valueDim);
  40083. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  40084. var restAngle = PI2$8;
  40085. var valueSumLargerThanMinAngle = 0;
  40086. var currentAngle = startAngle;
  40087. var dir = clockwise ? 1 : -1;
  40088. data.setLayout({
  40089. viewRect: viewRect,
  40090. r: r
  40091. });
  40092. data.each(valueDim, function (value, idx) {
  40093. var angle;
  40094. if (isNaN(value)) {
  40095. data.setItemLayout(idx, {
  40096. angle: NaN,
  40097. startAngle: NaN,
  40098. endAngle: NaN,
  40099. clockwise: clockwise,
  40100. cx: cx,
  40101. cy: cy,
  40102. r0: r0,
  40103. r: roseType ? NaN : r
  40104. });
  40105. return;
  40106. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  40107. if (roseType !== 'area') {
  40108. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  40109. } else {
  40110. angle = PI2$8 / validDataCount;
  40111. }
  40112. if (angle < minAngle) {
  40113. angle = minAngle;
  40114. restAngle -= minAngle;
  40115. } else {
  40116. valueSumLargerThanMinAngle += value;
  40117. }
  40118. var endAngle = currentAngle + dir * angle;
  40119. data.setItemLayout(idx, {
  40120. angle: angle,
  40121. startAngle: currentAngle,
  40122. endAngle: endAngle,
  40123. clockwise: clockwise,
  40124. cx: cx,
  40125. cy: cy,
  40126. r0: r0,
  40127. r: roseType ? linearMap(value, extent, [r0, r]) : r
  40128. });
  40129. currentAngle = endAngle;
  40130. }); // Some sector is constrained by minAngle
  40131. // Rest sectors needs recalculate angle
  40132. if (restAngle < PI2$8 && validDataCount) {
  40133. // Average the angle if rest angle is not enough after all angles is
  40134. // Constrained by minAngle
  40135. if (restAngle <= 1e-3) {
  40136. var angle_1 = PI2$8 / validDataCount;
  40137. data.each(valueDim, function (value, idx) {
  40138. if (!isNaN(value)) {
  40139. var layout_1 = data.getItemLayout(idx);
  40140. layout_1.angle = angle_1;
  40141. layout_1.startAngle = startAngle + dir * idx * angle_1;
  40142. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  40143. }
  40144. });
  40145. } else {
  40146. unitRadian = restAngle / valueSumLargerThanMinAngle;
  40147. currentAngle = startAngle;
  40148. data.each(valueDim, function (value, idx) {
  40149. if (!isNaN(value)) {
  40150. var layout_2 = data.getItemLayout(idx);
  40151. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  40152. layout_2.startAngle = currentAngle;
  40153. layout_2.endAngle = currentAngle + dir * angle;
  40154. currentAngle += dir * angle;
  40155. }
  40156. });
  40157. }
  40158. }
  40159. });
  40160. }
  40161. /*
  40162. * Licensed to the Apache Software Foundation (ASF) under one
  40163. * or more contributor license agreements. See the NOTICE file
  40164. * distributed with this work for additional information
  40165. * regarding copyright ownership. The ASF licenses this file
  40166. * to you under the Apache License, Version 2.0 (the
  40167. * "License"); you may not use this file except in compliance
  40168. * with the License. You may obtain a copy of the License at
  40169. *
  40170. * http://www.apache.org/licenses/LICENSE-2.0
  40171. *
  40172. * Unless required by applicable law or agreed to in writing,
  40173. * software distributed under the License is distributed on an
  40174. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40175. * KIND, either express or implied. See the License for the
  40176. * specific language governing permissions and limitations
  40177. * under the License.
  40178. */
  40179. /**
  40180. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40181. */
  40182. /*
  40183. * Licensed to the Apache Software Foundation (ASF) under one
  40184. * or more contributor license agreements. See the NOTICE file
  40185. * distributed with this work for additional information
  40186. * regarding copyright ownership. The ASF licenses this file
  40187. * to you under the Apache License, Version 2.0 (the
  40188. * "License"); you may not use this file except in compliance
  40189. * with the License. You may obtain a copy of the License at
  40190. *
  40191. * http://www.apache.org/licenses/LICENSE-2.0
  40192. *
  40193. * Unless required by applicable law or agreed to in writing,
  40194. * software distributed under the License is distributed on an
  40195. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40196. * KIND, either express or implied. See the License for the
  40197. * specific language governing permissions and limitations
  40198. * under the License.
  40199. */
  40200. function dataFilter(seriesType) {
  40201. return {
  40202. seriesType: seriesType,
  40203. reset: function (seriesModel, ecModel) {
  40204. var legendModels = ecModel.findComponents({
  40205. mainType: 'legend'
  40206. });
  40207. if (!legendModels || !legendModels.length) {
  40208. return;
  40209. }
  40210. var data = seriesModel.getData();
  40211. data.filterSelf(function (idx) {
  40212. var name = data.getName(idx); // If in any legend component the status is not selected.
  40213. for (var i = 0; i < legendModels.length; i++) {
  40214. // @ts-ignore FIXME: LegendModel
  40215. if (!legendModels[i].isSelected(name)) {
  40216. return false;
  40217. }
  40218. }
  40219. return true;
  40220. });
  40221. }
  40222. };
  40223. }
  40224. var RADIAN$1 = Math.PI / 180;
  40225. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  40226. if (list.length < 2) {
  40227. return;
  40228. }
  40229. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  40230. var rB = semi.rB;
  40231. var rB2 = rB * rB;
  40232. for (var i = 0; i < semi.list.length; i++) {
  40233. var item = semi.list[i];
  40234. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  40235. var rA = r + item.len;
  40236. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  40237. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  40238. var newX = cx + (dx + item.len2) * dir;
  40239. var deltaX = newX - item.label.x;
  40240. var newTargetWidth = item.targetTextWidth - deltaX * dir; // text x is changed, so need to recalculate width.
  40241. constrainTextWidth(item, newTargetWidth, true);
  40242. item.label.x = newX;
  40243. }
  40244. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  40245. function recalculateX(items) {
  40246. // Extremes of
  40247. var topSemi = {
  40248. list: [],
  40249. maxY: 0
  40250. };
  40251. var bottomSemi = {
  40252. list: [],
  40253. maxY: 0
  40254. };
  40255. for (var i = 0; i < items.length; i++) {
  40256. if (items[i].labelAlignTo !== 'none') {
  40257. continue;
  40258. }
  40259. var item = items[i];
  40260. var semi = item.label.y > cy ? bottomSemi : topSemi;
  40261. var dy = Math.abs(item.label.y - cy);
  40262. if (dy >= semi.maxY) {
  40263. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  40264. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  40265. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  40266. semi.rB = rB;
  40267. semi.maxY = dy;
  40268. }
  40269. semi.list.push(item);
  40270. }
  40271. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  40272. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  40273. }
  40274. var len = list.length;
  40275. for (var i = 0; i < len; i++) {
  40276. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  40277. var dx = list[i].label.x - farthestX;
  40278. list[i].linePoints[1][0] += dx;
  40279. list[i].label.x = farthestX;
  40280. }
  40281. }
  40282. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  40283. recalculateX(list);
  40284. }
  40285. }
  40286. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  40287. var leftList = [];
  40288. var rightList = [];
  40289. var leftmostX = Number.MAX_VALUE;
  40290. var rightmostX = -Number.MAX_VALUE;
  40291. for (var i = 0; i < labelLayoutList.length; i++) {
  40292. var label = labelLayoutList[i].label;
  40293. if (isPositionCenter(labelLayoutList[i])) {
  40294. continue;
  40295. }
  40296. if (label.x < cx) {
  40297. leftmostX = Math.min(leftmostX, label.x);
  40298. leftList.push(labelLayoutList[i]);
  40299. } else {
  40300. rightmostX = Math.max(rightmostX, label.x);
  40301. rightList.push(labelLayoutList[i]);
  40302. }
  40303. }
  40304. for (var i = 0; i < labelLayoutList.length; i++) {
  40305. var layout = labelLayoutList[i];
  40306. if (!isPositionCenter(layout) && layout.linePoints) {
  40307. if (layout.labelStyleWidth != null) {
  40308. continue;
  40309. }
  40310. var label = layout.label;
  40311. var linePoints = layout.linePoints;
  40312. var targetTextWidth = void 0;
  40313. if (layout.labelAlignTo === 'edge') {
  40314. if (label.x < cx) {
  40315. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  40316. } else {
  40317. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  40318. }
  40319. } else if (layout.labelAlignTo === 'labelLine') {
  40320. if (label.x < cx) {
  40321. targetTextWidth = leftmostX - viewLeft - layout.bleedMargin;
  40322. } else {
  40323. targetTextWidth = viewLeft + viewWidth - rightmostX - layout.bleedMargin;
  40324. }
  40325. } else {
  40326. if (label.x < cx) {
  40327. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  40328. } else {
  40329. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  40330. }
  40331. }
  40332. layout.targetTextWidth = targetTextWidth;
  40333. constrainTextWidth(layout, targetTextWidth);
  40334. }
  40335. }
  40336. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  40337. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  40338. for (var i = 0; i < labelLayoutList.length; i++) {
  40339. var layout = labelLayoutList[i];
  40340. if (!isPositionCenter(layout) && layout.linePoints) {
  40341. var label = layout.label;
  40342. var linePoints = layout.linePoints;
  40343. var isAlignToEdge = layout.labelAlignTo === 'edge';
  40344. var padding = label.style.padding;
  40345. var paddingH = padding ? padding[1] + padding[3] : 0; // textRect.width already contains paddingH if bgColor is set
  40346. var extraPaddingH = label.style.backgroundColor ? 0 : paddingH;
  40347. var realTextWidth = layout.rect.width + extraPaddingH;
  40348. var dist = linePoints[1][0] - linePoints[2][0];
  40349. if (isAlignToEdge) {
  40350. if (label.x < cx) {
  40351. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  40352. } else {
  40353. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  40354. }
  40355. } else {
  40356. if (label.x < cx) {
  40357. linePoints[2][0] = label.x + layout.labelDistance;
  40358. } else {
  40359. linePoints[2][0] = label.x - layout.labelDistance;
  40360. }
  40361. linePoints[1][0] = linePoints[2][0] + dist;
  40362. }
  40363. linePoints[1][1] = linePoints[2][1] = label.y;
  40364. }
  40365. }
  40366. }
  40367. /**
  40368. * Set max width of each label, and then wrap each label to the max width.
  40369. *
  40370. * @param layout label layout
  40371. * @param availableWidth max width for the label to display
  40372. * @param forceRecalculate recaculate the text layout even if the current width
  40373. * is smaller than `availableWidth`. This is useful when the text was previously
  40374. * wrapped by calling `constrainTextWidth` but now `availableWidth` changed, in
  40375. * which case, previous wrapping should be redo.
  40376. */
  40377. function constrainTextWidth(layout, availableWidth, forceRecalculate) {
  40378. if (forceRecalculate === void 0) {
  40379. forceRecalculate = false;
  40380. }
  40381. if (layout.labelStyleWidth != null) {
  40382. // User-defined style.width has the highest priority.
  40383. return;
  40384. }
  40385. var label = layout.label;
  40386. var style = label.style;
  40387. var textRect = layout.rect;
  40388. var bgColor = style.backgroundColor;
  40389. var padding = style.padding;
  40390. var paddingH = padding ? padding[1] + padding[3] : 0;
  40391. var overflow = style.overflow; // textRect.width already contains paddingH if bgColor is set
  40392. var oldOuterWidth = textRect.width + (bgColor ? 0 : paddingH);
  40393. if (availableWidth < oldOuterWidth || forceRecalculate) {
  40394. var oldHeight = textRect.height;
  40395. if (overflow && overflow.match('break')) {
  40396. // Temporarily set background to be null to calculate
  40397. // the bounding box without background.
  40398. label.setStyle('backgroundColor', null); // Set constraining width
  40399. label.setStyle('width', availableWidth - paddingH); // This is the real bounding box of the text without padding.
  40400. var innerRect = label.getBoundingRect();
  40401. label.setStyle('width', Math.ceil(innerRect.width));
  40402. label.setStyle('backgroundColor', bgColor);
  40403. } else {
  40404. var availableInnerWidth = availableWidth - paddingH;
  40405. var newWidth = availableWidth < oldOuterWidth // Current text is too wide, use `availableWidth` as max width.
  40406. ? availableInnerWidth : // Current available width is enough, but the text may have
  40407. // already been wrapped with a smaller available width.
  40408. forceRecalculate ? availableInnerWidth > layout.unconstrainedWidth // Current available is larger than text width,
  40409. // so don't constrain width (otherwise it may have
  40410. // empty space in the background).
  40411. ? null // Current available is smaller than text width, so
  40412. // use the current available width as constraining
  40413. // width.
  40414. : availableInnerWidth : // Current available width is enough, so no need to
  40415. // constrain.
  40416. null;
  40417. label.setStyle('width', newWidth);
  40418. }
  40419. var newRect = label.getBoundingRect();
  40420. textRect.width = newRect.width;
  40421. var margin = (label.style.margin || 0) + 2.1;
  40422. textRect.height = newRect.height + margin;
  40423. textRect.y -= (textRect.height - oldHeight) / 2;
  40424. }
  40425. }
  40426. function isPositionCenter(sectorShape) {
  40427. // Not change x for center label
  40428. return sectorShape.position === 'center';
  40429. }
  40430. function pieLabelLayout(seriesModel) {
  40431. var data = seriesModel.getData();
  40432. var labelLayoutList = [];
  40433. var cx;
  40434. var cy;
  40435. var hasLabelRotate = false;
  40436. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  40437. var viewRect = data.getLayout('viewRect');
  40438. var r = data.getLayout('r');
  40439. var viewWidth = viewRect.width;
  40440. var viewLeft = viewRect.x;
  40441. var viewTop = viewRect.y;
  40442. var viewHeight = viewRect.height;
  40443. function setNotShow(el) {
  40444. el.ignore = true;
  40445. }
  40446. function isLabelShown(label) {
  40447. if (!label.ignore) {
  40448. return true;
  40449. }
  40450. for (var key in label.states) {
  40451. if (label.states[key].ignore === false) {
  40452. return true;
  40453. }
  40454. }
  40455. return false;
  40456. }
  40457. data.each(function (idx) {
  40458. var sector = data.getItemGraphicEl(idx);
  40459. var sectorShape = sector.shape;
  40460. var label = sector.getTextContent();
  40461. var labelLine = sector.getTextGuideLine();
  40462. var itemModel = data.getItemModel(idx);
  40463. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  40464. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  40465. var labelDistance = labelModel.get('distanceToLabelLine');
  40466. var labelAlignTo = labelModel.get('alignTo');
  40467. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  40468. var bleedMargin = labelModel.get('bleedMargin');
  40469. var labelLineModel = itemModel.getModel('labelLine');
  40470. var labelLineLen = labelLineModel.get('length');
  40471. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  40472. var labelLineLen2 = labelLineModel.get('length2');
  40473. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  40474. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  40475. each(label.states, setNotShow);
  40476. label.ignore = true;
  40477. if (labelLine) {
  40478. each(labelLine.states, setNotShow);
  40479. labelLine.ignore = true;
  40480. }
  40481. return;
  40482. }
  40483. if (!isLabelShown(label)) {
  40484. return;
  40485. }
  40486. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  40487. var nx = Math.cos(midAngle);
  40488. var ny = Math.sin(midAngle);
  40489. var textX;
  40490. var textY;
  40491. var linePoints;
  40492. var textAlign;
  40493. cx = sectorShape.cx;
  40494. cy = sectorShape.cy;
  40495. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  40496. if (labelPosition === 'center') {
  40497. textX = sectorShape.cx;
  40498. textY = sectorShape.cy;
  40499. textAlign = 'center';
  40500. } else {
  40501. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  40502. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  40503. textX = x1 + nx * 3;
  40504. textY = y1 + ny * 3;
  40505. if (!isLabelInside) {
  40506. // For roseType
  40507. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  40508. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  40509. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  40510. var y3 = y2;
  40511. if (labelAlignTo === 'edge') {
  40512. // Adjust textX because text align of edge is opposite
  40513. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  40514. } else {
  40515. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  40516. }
  40517. textY = y3;
  40518. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  40519. }
  40520. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  40521. }
  40522. var PI = Math.PI;
  40523. var labelRotate = 0;
  40524. var rotate = labelModel.get('rotate');
  40525. if (isNumber(rotate)) {
  40526. labelRotate = rotate * (PI / 180);
  40527. } else if (labelPosition === 'center') {
  40528. labelRotate = 0;
  40529. } else if (rotate === 'radial' || rotate === true) {
  40530. var radialAngle = nx < 0 ? -midAngle + PI : -midAngle;
  40531. labelRotate = radialAngle;
  40532. } else if (rotate === 'tangential' && labelPosition !== 'outside' && labelPosition !== 'outer') {
  40533. var rad = Math.atan2(nx, ny);
  40534. if (rad < 0) {
  40535. rad = PI * 2 + rad;
  40536. }
  40537. var isDown = ny > 0;
  40538. if (isDown) {
  40539. rad = PI + rad;
  40540. }
  40541. labelRotate = rad - PI;
  40542. }
  40543. hasLabelRotate = !!labelRotate;
  40544. label.x = textX;
  40545. label.y = textY;
  40546. label.rotation = labelRotate;
  40547. label.setStyle({
  40548. verticalAlign: 'middle'
  40549. }); // Not sectorShape the inside label
  40550. if (!isLabelInside) {
  40551. var textRect = label.getBoundingRect().clone();
  40552. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  40553. var margin = (label.style.margin || 0) + 2.1;
  40554. textRect.y -= margin / 2;
  40555. textRect.height += margin;
  40556. labelLayoutList.push({
  40557. label: label,
  40558. labelLine: labelLine,
  40559. position: labelPosition,
  40560. len: labelLineLen,
  40561. len2: labelLineLen2,
  40562. minTurnAngle: labelLineModel.get('minTurnAngle'),
  40563. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  40564. surfaceNormal: new Point(nx, ny),
  40565. linePoints: linePoints,
  40566. textAlign: textAlign,
  40567. labelDistance: labelDistance,
  40568. labelAlignTo: labelAlignTo,
  40569. edgeDistance: edgeDistance,
  40570. bleedMargin: bleedMargin,
  40571. rect: textRect,
  40572. unconstrainedWidth: textRect.width,
  40573. labelStyleWidth: label.style.width
  40574. });
  40575. } else {
  40576. label.setStyle({
  40577. align: textAlign
  40578. });
  40579. var selectState = label.states.select;
  40580. if (selectState) {
  40581. selectState.x += label.x;
  40582. selectState.y += label.y;
  40583. }
  40584. }
  40585. sector.setTextConfig({
  40586. inside: isLabelInside
  40587. });
  40588. });
  40589. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  40590. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  40591. }
  40592. for (var i = 0; i < labelLayoutList.length; i++) {
  40593. var layout = labelLayoutList[i];
  40594. var label = layout.label;
  40595. var labelLine = layout.labelLine;
  40596. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  40597. if (label) {
  40598. label.setStyle({
  40599. align: layout.textAlign
  40600. });
  40601. if (notShowLabel) {
  40602. each(label.states, setNotShow);
  40603. label.ignore = true;
  40604. }
  40605. var selectState = label.states.select;
  40606. if (selectState) {
  40607. selectState.x += label.x;
  40608. selectState.y += label.y;
  40609. }
  40610. }
  40611. if (labelLine) {
  40612. var linePoints = layout.linePoints;
  40613. if (notShowLabel || !linePoints) {
  40614. each(labelLine.states, setNotShow);
  40615. labelLine.ignore = true;
  40616. } else {
  40617. limitTurnAngle(linePoints, layout.minTurnAngle);
  40618. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  40619. labelLine.setShape({
  40620. points: linePoints
  40621. }); // Set the anchor to the midpoint of sector
  40622. label.__hostTarget.textGuideLineConfig = {
  40623. anchor: new Point(linePoints[0][0], linePoints[0][1])
  40624. };
  40625. }
  40626. }
  40627. }
  40628. }
  40629. /**
  40630. * Piece of pie including Sector, Label, LabelLine
  40631. */
  40632. var PiePiece =
  40633. /** @class */
  40634. function (_super) {
  40635. __extends(PiePiece, _super);
  40636. function PiePiece(data, idx, startAngle) {
  40637. var _this = _super.call(this) || this;
  40638. _this.z2 = 2;
  40639. var text = new ZRText();
  40640. _this.setTextContent(text);
  40641. _this.updateData(data, idx, startAngle, true);
  40642. return _this;
  40643. }
  40644. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  40645. var sector = this;
  40646. var seriesModel = data.hostModel;
  40647. var itemModel = data.getItemModel(idx);
  40648. var emphasisModel = itemModel.getModel('emphasis');
  40649. var layout = data.getItemLayout(idx); // cornerRadius & innerCornerRadius doesn't exist in the item layout. Use `0` if null value is specified.
  40650. // see `setItemLayout` in `pieLayout.ts`.
  40651. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout, true), layout); // Ignore NaN data.
  40652. if (isNaN(sectorShape.startAngle)) {
  40653. // Use NaN shape to avoid drawing shape.
  40654. sector.setShape(sectorShape);
  40655. return;
  40656. }
  40657. if (firstCreate) {
  40658. sector.setShape(sectorShape);
  40659. var animationType = seriesModel.getShallow('animationType');
  40660. if (seriesModel.ecModel.ssr) {
  40661. // Use scale animation in SSR mode(opacity?)
  40662. // Because CSS SVG animation doesn't support very customized shape animation.
  40663. initProps(sector, {
  40664. scaleX: 0,
  40665. scaleY: 0
  40666. }, seriesModel, {
  40667. dataIndex: idx,
  40668. isFrom: true
  40669. });
  40670. sector.originX = sectorShape.cx;
  40671. sector.originY = sectorShape.cy;
  40672. } else if (animationType === 'scale') {
  40673. sector.shape.r = layout.r0;
  40674. initProps(sector, {
  40675. shape: {
  40676. r: layout.r
  40677. }
  40678. }, seriesModel, idx);
  40679. } // Expansion
  40680. else {
  40681. if (startAngle != null) {
  40682. sector.setShape({
  40683. startAngle: startAngle,
  40684. endAngle: startAngle
  40685. });
  40686. initProps(sector, {
  40687. shape: {
  40688. startAngle: layout.startAngle,
  40689. endAngle: layout.endAngle
  40690. }
  40691. }, seriesModel, idx);
  40692. } else {
  40693. sector.shape.endAngle = layout.startAngle;
  40694. updateProps(sector, {
  40695. shape: {
  40696. endAngle: layout.endAngle
  40697. }
  40698. }, seriesModel, idx);
  40699. }
  40700. }
  40701. } else {
  40702. saveOldStyle(sector); // Transition animation from the old shape
  40703. updateProps(sector, {
  40704. shape: sectorShape
  40705. }, seriesModel, idx);
  40706. }
  40707. sector.useStyle(data.getItemVisual(idx, 'style'));
  40708. setStatesStylesFromModel(sector, itemModel);
  40709. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  40710. var offset = seriesModel.get('selectedOffset');
  40711. var dx = Math.cos(midAngle) * offset;
  40712. var dy = Math.sin(midAngle) * offset;
  40713. var cursorStyle = itemModel.getShallow('cursor');
  40714. cursorStyle && sector.attr('cursor', cursorStyle);
  40715. this._updateLabel(seriesModel, data, idx);
  40716. sector.ensureState('emphasis').shape = extend({
  40717. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  40718. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  40719. extend(sector.ensureState('select'), {
  40720. x: dx,
  40721. y: dy,
  40722. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  40723. });
  40724. extend(sector.ensureState('blur'), {
  40725. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  40726. });
  40727. var labelLine = sector.getTextGuideLine();
  40728. var labelText = sector.getTextContent();
  40729. labelLine && extend(labelLine.ensureState('select'), {
  40730. x: dx,
  40731. y: dy
  40732. }); // TODO: needs dx, dy in zrender?
  40733. extend(labelText.ensureState('select'), {
  40734. x: dx,
  40735. y: dy
  40736. });
  40737. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  40738. };
  40739. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  40740. var sector = this;
  40741. var itemModel = data.getItemModel(idx);
  40742. var labelLineModel = itemModel.getModel('labelLine');
  40743. var style = data.getItemVisual(idx, 'style');
  40744. var visualColor = style && style.fill;
  40745. var visualOpacity = style && style.opacity;
  40746. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  40747. labelFetcher: data.hostModel,
  40748. labelDataIndex: idx,
  40749. inheritColor: visualColor,
  40750. defaultOpacity: visualOpacity,
  40751. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  40752. });
  40753. var labelText = sector.getTextContent(); // Set textConfig on sector.
  40754. sector.setTextConfig({
  40755. // reset position, rotation
  40756. position: null,
  40757. rotation: null
  40758. }); // Make sure update style on labelText after setLabelStyle.
  40759. // Because setLabelStyle will replace a new style on it.
  40760. labelText.attr({
  40761. z2: 10
  40762. });
  40763. var labelPosition = seriesModel.get(['label', 'position']);
  40764. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  40765. sector.removeTextGuideLine();
  40766. } else {
  40767. var polyline = this.getTextGuideLine();
  40768. if (!polyline) {
  40769. polyline = new Polyline();
  40770. this.setTextGuideLine(polyline);
  40771. } // Default use item visual color
  40772. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  40773. stroke: visualColor,
  40774. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  40775. });
  40776. }
  40777. };
  40778. return PiePiece;
  40779. }(Sector); // Pie view
  40780. var PieView =
  40781. /** @class */
  40782. function (_super) {
  40783. __extends(PieView, _super);
  40784. function PieView() {
  40785. var _this = _super !== null && _super.apply(this, arguments) || this;
  40786. _this.ignoreLabelLineUpdate = true;
  40787. return _this;
  40788. }
  40789. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  40790. var data = seriesModel.getData();
  40791. var oldData = this._data;
  40792. var group = this.group;
  40793. var startAngle; // First render
  40794. if (!oldData && data.count() > 0) {
  40795. var shape = data.getItemLayout(0);
  40796. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  40797. shape = data.getItemLayout(s);
  40798. }
  40799. if (shape) {
  40800. startAngle = shape.startAngle;
  40801. }
  40802. } // remove empty-circle if it exists
  40803. if (this._emptyCircleSector) {
  40804. group.remove(this._emptyCircleSector);
  40805. } // when all data are filtered, show lightgray empty circle
  40806. if (data.count() === 0 && seriesModel.get('showEmptyCircle')) {
  40807. var sector = new Sector({
  40808. shape: getBasicPieLayout(seriesModel, api)
  40809. });
  40810. sector.useStyle(seriesModel.getModel('emptyCircleStyle').getItemStyle());
  40811. this._emptyCircleSector = sector;
  40812. group.add(sector);
  40813. }
  40814. data.diff(oldData).add(function (idx) {
  40815. var piePiece = new PiePiece(data, idx, startAngle);
  40816. data.setItemGraphicEl(idx, piePiece);
  40817. group.add(piePiece);
  40818. }).update(function (newIdx, oldIdx) {
  40819. var piePiece = oldData.getItemGraphicEl(oldIdx);
  40820. piePiece.updateData(data, newIdx, startAngle);
  40821. piePiece.off('click');
  40822. group.add(piePiece);
  40823. data.setItemGraphicEl(newIdx, piePiece);
  40824. }).remove(function (idx) {
  40825. var piePiece = oldData.getItemGraphicEl(idx);
  40826. removeElementWithFadeOut(piePiece, seriesModel, idx);
  40827. }).execute();
  40828. pieLabelLayout(seriesModel); // Always use initial animation.
  40829. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  40830. this._data = data;
  40831. }
  40832. };
  40833. PieView.prototype.dispose = function () {};
  40834. PieView.prototype.containPoint = function (point, seriesModel) {
  40835. var data = seriesModel.getData();
  40836. var itemLayout = data.getItemLayout(0);
  40837. if (itemLayout) {
  40838. var dx = point[0] - itemLayout.cx;
  40839. var dy = point[1] - itemLayout.cy;
  40840. var radius = Math.sqrt(dx * dx + dy * dy);
  40841. return radius <= itemLayout.r && radius >= itemLayout.r0;
  40842. }
  40843. };
  40844. PieView.type = 'pie';
  40845. return PieView;
  40846. }(ChartView);
  40847. /**
  40848. * [Usage]:
  40849. * (1)
  40850. * createListSimply(seriesModel, ['value']);
  40851. * (2)
  40852. * createListSimply(seriesModel, {
  40853. * coordDimensions: ['value'],
  40854. * dimensionsCount: 5
  40855. * });
  40856. */
  40857. function createSeriesDataSimply(seriesModel, opt, nameList) {
  40858. opt = isArray(opt) && {
  40859. coordDimensions: opt
  40860. } || extend({
  40861. encodeDefine: seriesModel.getEncode()
  40862. }, opt);
  40863. var source = seriesModel.getSource();
  40864. var dimensions = prepareSeriesDataSchema(source, opt).dimensions;
  40865. var list = new SeriesData(dimensions, seriesModel);
  40866. list.initData(source, nameList);
  40867. return list;
  40868. }
  40869. /*
  40870. * Licensed to the Apache Software Foundation (ASF) under one
  40871. * or more contributor license agreements. See the NOTICE file
  40872. * distributed with this work for additional information
  40873. * regarding copyright ownership. The ASF licenses this file
  40874. * to you under the Apache License, Version 2.0 (the
  40875. * "License"); you may not use this file except in compliance
  40876. * with the License. You may obtain a copy of the License at
  40877. *
  40878. * http://www.apache.org/licenses/LICENSE-2.0
  40879. *
  40880. * Unless required by applicable law or agreed to in writing,
  40881. * software distributed under the License is distributed on an
  40882. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40883. * KIND, either express or implied. See the License for the
  40884. * specific language governing permissions and limitations
  40885. * under the License.
  40886. */
  40887. /**
  40888. * AUTO-GENERATED FILE. DO NOT MODIFY.
  40889. */
  40890. /*
  40891. * Licensed to the Apache Software Foundation (ASF) under one
  40892. * or more contributor license agreements. See the NOTICE file
  40893. * distributed with this work for additional information
  40894. * regarding copyright ownership. The ASF licenses this file
  40895. * to you under the Apache License, Version 2.0 (the
  40896. * "License"); you may not use this file except in compliance
  40897. * with the License. You may obtain a copy of the License at
  40898. *
  40899. * http://www.apache.org/licenses/LICENSE-2.0
  40900. *
  40901. * Unless required by applicable law or agreed to in writing,
  40902. * software distributed under the License is distributed on an
  40903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40904. * KIND, either express or implied. See the License for the
  40905. * specific language governing permissions and limitations
  40906. * under the License.
  40907. */
  40908. /**
  40909. * LegendVisualProvider is an bridge that pick encoded color from data and
  40910. * provide to the legend component.
  40911. */
  40912. var LegendVisualProvider =
  40913. /** @class */
  40914. function () {
  40915. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  40916. getDataWithEncodedVisual, // Function to get raw data before filtered.
  40917. getRawData) {
  40918. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  40919. this._getRawData = getRawData;
  40920. }
  40921. LegendVisualProvider.prototype.getAllNames = function () {
  40922. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  40923. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  40924. return rawData.mapArray(rawData.getName);
  40925. };
  40926. LegendVisualProvider.prototype.containName = function (name) {
  40927. var rawData = this._getRawData();
  40928. return rawData.indexOfName(name) >= 0;
  40929. };
  40930. LegendVisualProvider.prototype.indexOfName = function (name) {
  40931. // Only get data when necessary.
  40932. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  40933. // Invoking Series#getData immediately will throw an error.
  40934. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40935. return dataWithEncodedVisual.indexOfName(name);
  40936. };
  40937. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  40938. // Get encoded visual properties from final filtered data.
  40939. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  40940. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  40941. };
  40942. return LegendVisualProvider;
  40943. }();
  40944. var innerData = makeInner();
  40945. var PieSeriesModel =
  40946. /** @class */
  40947. function (_super) {
  40948. __extends(PieSeriesModel, _super);
  40949. function PieSeriesModel() {
  40950. return _super !== null && _super.apply(this, arguments) || this;
  40951. }
  40952. /**
  40953. * @overwrite
  40954. */
  40955. PieSeriesModel.prototype.init = function (option) {
  40956. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  40957. // Use a function instead of direct access because data reference may changed
  40958. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  40959. this._defaultLabelLine(option);
  40960. };
  40961. /**
  40962. * @overwrite
  40963. */
  40964. PieSeriesModel.prototype.mergeOption = function () {
  40965. _super.prototype.mergeOption.apply(this, arguments);
  40966. };
  40967. /**
  40968. * @overwrite
  40969. */
  40970. PieSeriesModel.prototype.getInitialData = function () {
  40971. return createSeriesDataSimply(this, {
  40972. coordDimensions: ['value'],
  40973. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  40974. });
  40975. };
  40976. /**
  40977. * @overwrite
  40978. */
  40979. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  40980. var data = this.getData(); // update seats when data is changed
  40981. var dataInner = innerData(data);
  40982. var seats = dataInner.seats;
  40983. if (!seats) {
  40984. var valueList_1 = [];
  40985. data.each(data.mapDimension('value'), function (value) {
  40986. valueList_1.push(value);
  40987. });
  40988. seats = dataInner.seats = getPercentSeats(valueList_1, data.hostModel.get('percentPrecision'));
  40989. }
  40990. var params = _super.prototype.getDataParams.call(this, dataIndex); // seats may be empty when sum is 0
  40991. params.percent = seats[dataIndex] || 0;
  40992. params.$vars.push('percent');
  40993. return params;
  40994. };
  40995. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  40996. // Extend labelLine emphasis
  40997. defaultEmphasis(option, 'labelLine', ['show']);
  40998. var labelLineNormalOpt = option.labelLine;
  40999. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  41000. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  41001. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  41002. };
  41003. PieSeriesModel.type = 'series.pie';
  41004. PieSeriesModel.defaultOption = {
  41005. // zlevel: 0,
  41006. z: 2,
  41007. legendHoverLink: true,
  41008. colorBy: 'data',
  41009. // 默认全局居中
  41010. center: ['50%', '50%'],
  41011. radius: [0, '75%'],
  41012. // 默认顺时针
  41013. clockwise: true,
  41014. startAngle: 90,
  41015. // 最小角度改为0
  41016. minAngle: 0,
  41017. // If the angle of a sector less than `minShowLabelAngle`,
  41018. // the label will not be displayed.
  41019. minShowLabelAngle: 0,
  41020. // 选中时扇区偏移量
  41021. selectedOffset: 10,
  41022. // 选择模式,默认关闭,可选single,multiple
  41023. // selectedMode: false,
  41024. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  41025. // roseType: null,
  41026. percentPrecision: 2,
  41027. // If still show when all data zero.
  41028. stillShowZeroSum: true,
  41029. // cursor: null,
  41030. left: 0,
  41031. top: 0,
  41032. right: 0,
  41033. bottom: 0,
  41034. width: null,
  41035. height: null,
  41036. label: {
  41037. // color: 'inherit',
  41038. // If rotate around circle
  41039. rotate: 0,
  41040. show: true,
  41041. overflow: 'truncate',
  41042. // 'outer', 'inside', 'center'
  41043. position: 'outer',
  41044. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  41045. alignTo: 'none',
  41046. // Closest distance between label and chart edge.
  41047. // Works only position is 'outer' and alignTo is 'edge'.
  41048. edgeDistance: '25%',
  41049. // Works only position is 'outer' and alignTo is not 'edge'.
  41050. bleedMargin: 10,
  41051. // Distance between text and label line.
  41052. distanceToLabelLine: 5 // formatter: 标签文本格式器,同 tooltip.formatter,不支持异步回调
  41053. // 默认使用全局文本样式,详见 textStyle
  41054. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  41055. },
  41056. // Enabled when label.normal.position is 'outer'
  41057. labelLine: {
  41058. show: true,
  41059. // 引导线两段中的第一段长度
  41060. length: 15,
  41061. // 引导线两段中的第二段长度
  41062. length2: 15,
  41063. smooth: false,
  41064. minTurnAngle: 90,
  41065. maxSurfaceAngle: 90,
  41066. lineStyle: {
  41067. // color: 各异,
  41068. width: 1,
  41069. type: 'solid'
  41070. }
  41071. },
  41072. itemStyle: {
  41073. borderWidth: 1,
  41074. borderJoin: 'round'
  41075. },
  41076. showEmptyCircle: true,
  41077. emptyCircleStyle: {
  41078. color: 'lightgray',
  41079. opacity: 1
  41080. },
  41081. labelLayout: {
  41082. // Hide the overlapped label.
  41083. hideOverlap: true
  41084. },
  41085. emphasis: {
  41086. scale: true,
  41087. scaleSize: 5
  41088. },
  41089. // If use strategy to avoid label overlapping
  41090. avoidLabelOverlap: true,
  41091. // Animation type. Valid values: expansion, scale
  41092. animationType: 'expansion',
  41093. animationDuration: 1000,
  41094. // Animation type when update. Valid values: transition, expansion
  41095. animationTypeUpdate: 'transition',
  41096. animationEasingUpdate: 'cubicInOut',
  41097. animationDurationUpdate: 500,
  41098. animationEasing: 'cubicInOut'
  41099. };
  41100. return PieSeriesModel;
  41101. }(SeriesModel);
  41102. function negativeDataFilter(seriesType) {
  41103. return {
  41104. seriesType: seriesType,
  41105. reset: function (seriesModel, ecModel) {
  41106. var data = seriesModel.getData();
  41107. data.filterSelf(function (idx) {
  41108. // handle negative value condition
  41109. var valueDim = data.mapDimension('value');
  41110. var curValue = data.get(valueDim, idx);
  41111. if (isNumber(curValue) && !isNaN(curValue) && curValue < 0) {
  41112. return false;
  41113. }
  41114. return true;
  41115. });
  41116. }
  41117. };
  41118. }
  41119. function install$4(registers) {
  41120. registers.registerChartView(PieView);
  41121. registers.registerSeriesModel(PieSeriesModel);
  41122. createLegacyDataSelectAction('pie', registers.registerAction);
  41123. registers.registerLayout(curry(pieLayout, 'pie'));
  41124. registers.registerProcessor(dataFilter('pie'));
  41125. registers.registerProcessor(negativeDataFilter('pie'));
  41126. }
  41127. var ScatterSeriesModel =
  41128. /** @class */
  41129. function (_super) {
  41130. __extends(ScatterSeriesModel, _super);
  41131. function ScatterSeriesModel() {
  41132. var _this = _super !== null && _super.apply(this, arguments) || this;
  41133. _this.type = ScatterSeriesModel.type;
  41134. _this.hasSymbolVisual = true;
  41135. return _this;
  41136. }
  41137. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41138. return createSeriesData(null, this, {
  41139. useEncodeDefaulter: true
  41140. });
  41141. };
  41142. ScatterSeriesModel.prototype.getProgressive = function () {
  41143. var progressive = this.option.progressive;
  41144. if (progressive == null) {
  41145. // PENDING
  41146. return this.option.large ? 5e3 : this.get('progressive');
  41147. }
  41148. return progressive;
  41149. };
  41150. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  41151. var progressiveThreshold = this.option.progressiveThreshold;
  41152. if (progressiveThreshold == null) {
  41153. // PENDING
  41154. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  41155. }
  41156. return progressiveThreshold;
  41157. };
  41158. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  41159. return selectors.point(data.getItemLayout(dataIndex));
  41160. };
  41161. ScatterSeriesModel.prototype.getZLevelKey = function () {
  41162. // Each progressive series has individual key.
  41163. return this.getData().count() > this.getProgressiveThreshold() ? this.id : '';
  41164. };
  41165. ScatterSeriesModel.type = 'series.scatter';
  41166. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  41167. ScatterSeriesModel.defaultOption = {
  41168. coordinateSystem: 'cartesian2d',
  41169. // zlevel: 0,
  41170. z: 2,
  41171. legendHoverLink: true,
  41172. symbolSize: 10,
  41173. // symbolRotate: null, // 图形旋转控制
  41174. large: false,
  41175. // Available when large is true
  41176. largeThreshold: 2000,
  41177. // cursor: null,
  41178. itemStyle: {
  41179. opacity: 0.8 // color: 各异
  41180. },
  41181. emphasis: {
  41182. scale: true
  41183. },
  41184. // If clip the overflow graphics
  41185. // Works on cartesian / polar series
  41186. clip: true,
  41187. select: {
  41188. itemStyle: {
  41189. borderColor: '#212121'
  41190. }
  41191. },
  41192. universalTransition: {
  41193. divideShape: 'clone'
  41194. } // progressive: null
  41195. };
  41196. return ScatterSeriesModel;
  41197. }(SeriesModel);
  41198. var BOOST_SIZE_THRESHOLD = 4;
  41199. var LargeSymbolPathShape =
  41200. /** @class */
  41201. function () {
  41202. function LargeSymbolPathShape() {}
  41203. return LargeSymbolPathShape;
  41204. }();
  41205. var LargeSymbolPath =
  41206. /** @class */
  41207. function (_super) {
  41208. __extends(LargeSymbolPath, _super);
  41209. function LargeSymbolPath(opts) {
  41210. var _this = _super.call(this, opts) || this;
  41211. _this._off = 0;
  41212. _this.hoverDataIdx = -1;
  41213. return _this;
  41214. }
  41215. LargeSymbolPath.prototype.getDefaultShape = function () {
  41216. return new LargeSymbolPathShape();
  41217. };
  41218. LargeSymbolPath.prototype.reset = function () {
  41219. this.notClear = false;
  41220. this._off = 0;
  41221. };
  41222. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  41223. var points = shape.points;
  41224. var size = shape.size;
  41225. var symbolProxy = this.symbolProxy;
  41226. var symbolProxyShape = symbolProxy.shape;
  41227. var ctx = path.getContext ? path.getContext() : path;
  41228. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  41229. var softClipShape = this.softClipShape;
  41230. var i; // Do draw in afterBrush.
  41231. if (canBoost) {
  41232. this._ctx = ctx;
  41233. return;
  41234. }
  41235. this._ctx = null;
  41236. for (i = this._off; i < points.length;) {
  41237. var x = points[i++];
  41238. var y = points[i++];
  41239. if (isNaN(x) || isNaN(y)) {
  41240. continue;
  41241. }
  41242. if (softClipShape && !softClipShape.contain(x, y)) {
  41243. continue;
  41244. }
  41245. symbolProxyShape.x = x - size[0] / 2;
  41246. symbolProxyShape.y = y - size[1] / 2;
  41247. symbolProxyShape.width = size[0];
  41248. symbolProxyShape.height = size[1];
  41249. symbolProxy.buildPath(path, symbolProxyShape, true);
  41250. }
  41251. if (this.incremental) {
  41252. this._off = i;
  41253. this.notClear = true;
  41254. }
  41255. };
  41256. LargeSymbolPath.prototype.afterBrush = function () {
  41257. var shape = this.shape;
  41258. var points = shape.points;
  41259. var size = shape.size;
  41260. var ctx = this._ctx;
  41261. var softClipShape = this.softClipShape;
  41262. var i;
  41263. if (!ctx) {
  41264. return;
  41265. } // PENDING If style or other canvas status changed?
  41266. for (i = this._off; i < points.length;) {
  41267. var x = points[i++];
  41268. var y = points[i++];
  41269. if (isNaN(x) || isNaN(y)) {
  41270. continue;
  41271. }
  41272. if (softClipShape && !softClipShape.contain(x, y)) {
  41273. continue;
  41274. } // fillRect is faster than building a rect path and draw.
  41275. // And it support light globalCompositeOperation.
  41276. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  41277. }
  41278. if (this.incremental) {
  41279. this._off = i;
  41280. this.notClear = true;
  41281. }
  41282. };
  41283. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  41284. // TODO ???
  41285. // Consider transform
  41286. var shape = this.shape;
  41287. var points = shape.points;
  41288. var size = shape.size;
  41289. var w = Math.max(size[0], 4);
  41290. var h = Math.max(size[1], 4); // Not consider transform
  41291. // Treat each element as a rect
  41292. // top down traverse
  41293. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  41294. var i = idx * 2;
  41295. var x0 = points[i] - w / 2;
  41296. var y0 = points[i + 1] - h / 2;
  41297. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  41298. return idx;
  41299. }
  41300. }
  41301. return -1;
  41302. };
  41303. LargeSymbolPath.prototype.contain = function (x, y) {
  41304. var localPos = this.transformCoordToLocal(x, y);
  41305. var rect = this.getBoundingRect();
  41306. x = localPos[0];
  41307. y = localPos[1];
  41308. if (rect.contain(x, y)) {
  41309. // Cache found data index.
  41310. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  41311. return dataIdx >= 0;
  41312. }
  41313. this.hoverDataIdx = -1;
  41314. return false;
  41315. };
  41316. LargeSymbolPath.prototype.getBoundingRect = function () {
  41317. // Ignore stroke for large symbol draw.
  41318. var rect = this._rect;
  41319. if (!rect) {
  41320. var shape = this.shape;
  41321. var points = shape.points;
  41322. var size = shape.size;
  41323. var w = size[0];
  41324. var h = size[1];
  41325. var minX = Infinity;
  41326. var minY = Infinity;
  41327. var maxX = -Infinity;
  41328. var maxY = -Infinity;
  41329. for (var i = 0; i < points.length;) {
  41330. var x = points[i++];
  41331. var y = points[i++];
  41332. minX = Math.min(x, minX);
  41333. maxX = Math.max(x, maxX);
  41334. minY = Math.min(y, minY);
  41335. maxY = Math.max(y, maxY);
  41336. }
  41337. rect = this._rect = new BoundingRect(minX - w / 2, minY - h / 2, maxX - minX + w, maxY - minY + h);
  41338. }
  41339. return rect;
  41340. };
  41341. return LargeSymbolPath;
  41342. }(Path);
  41343. var LargeSymbolDraw =
  41344. /** @class */
  41345. function () {
  41346. function LargeSymbolDraw() {
  41347. this.group = new Group();
  41348. }
  41349. /**
  41350. * Update symbols draw by new data
  41351. */
  41352. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  41353. this._clear();
  41354. var symbolEl = this._create();
  41355. symbolEl.setShape({
  41356. points: data.getLayout('points')
  41357. });
  41358. this._setCommon(symbolEl, data, opt);
  41359. };
  41360. LargeSymbolDraw.prototype.updateLayout = function (data) {
  41361. var points = data.getLayout('points');
  41362. this.group.eachChild(function (child) {
  41363. if (child.startIndex != null) {
  41364. var len = (child.endIndex - child.startIndex) * 2;
  41365. var byteOffset = child.startIndex * 4 * 2;
  41366. points = new Float32Array(points.buffer, byteOffset, len);
  41367. }
  41368. child.setShape('points', points); // Reset draw cursor.
  41369. child.reset();
  41370. });
  41371. };
  41372. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  41373. this._clear();
  41374. };
  41375. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  41376. var lastAdded = this._newAdded[0];
  41377. var points = data.getLayout('points');
  41378. var oldPoints = lastAdded && lastAdded.shape.points; // Merging the exists. Each element has 1e4 points.
  41379. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  41380. if (oldPoints && oldPoints.length < 2e4) {
  41381. var oldLen = oldPoints.length;
  41382. var newPoints = new Float32Array(oldLen + points.length); // Concat two array
  41383. newPoints.set(oldPoints);
  41384. newPoints.set(points, oldLen); // Update endIndex
  41385. lastAdded.endIndex = taskParams.end;
  41386. lastAdded.setShape({
  41387. points: newPoints
  41388. });
  41389. } else {
  41390. // Clear
  41391. this._newAdded = [];
  41392. var symbolEl = this._create();
  41393. symbolEl.startIndex = taskParams.start;
  41394. symbolEl.endIndex = taskParams.end;
  41395. symbolEl.incremental = true;
  41396. symbolEl.setShape({
  41397. points: points
  41398. });
  41399. this._setCommon(symbolEl, data, opt);
  41400. }
  41401. };
  41402. LargeSymbolDraw.prototype.eachRendered = function (cb) {
  41403. this._newAdded[0] && cb(this._newAdded[0]);
  41404. };
  41405. LargeSymbolDraw.prototype._create = function () {
  41406. var symbolEl = new LargeSymbolPath({
  41407. cursor: 'default'
  41408. });
  41409. symbolEl.ignoreCoarsePointer = true;
  41410. this.group.add(symbolEl);
  41411. this._newAdded.push(symbolEl);
  41412. return symbolEl;
  41413. };
  41414. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, opt) {
  41415. var hostModel = data.hostModel;
  41416. opt = opt || {};
  41417. var size = data.getVisual('symbolSize');
  41418. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  41419. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  41420. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  41421. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  41422. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  41423. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  41424. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  41425. var globalStyle = data.getVisual('style');
  41426. var visualColor = globalStyle && globalStyle.fill;
  41427. if (visualColor) {
  41428. symbolEl.setColor(visualColor);
  41429. }
  41430. var ecData = getECData(symbolEl); // Enable tooltip
  41431. // PENDING May have performance issue when path is extremely large
  41432. ecData.seriesIndex = hostModel.seriesIndex;
  41433. symbolEl.on('mousemove', function (e) {
  41434. ecData.dataIndex = null;
  41435. var dataIndex = symbolEl.hoverDataIdx;
  41436. if (dataIndex >= 0) {
  41437. // Provide dataIndex for tooltip
  41438. ecData.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  41439. }
  41440. });
  41441. };
  41442. LargeSymbolDraw.prototype.remove = function () {
  41443. this._clear();
  41444. };
  41445. LargeSymbolDraw.prototype._clear = function () {
  41446. this._newAdded = [];
  41447. this.group.removeAll();
  41448. };
  41449. return LargeSymbolDraw;
  41450. }();
  41451. var ScatterView =
  41452. /** @class */
  41453. function (_super) {
  41454. __extends(ScatterView, _super);
  41455. function ScatterView() {
  41456. var _this = _super !== null && _super.apply(this, arguments) || this;
  41457. _this.type = ScatterView.type;
  41458. return _this;
  41459. }
  41460. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  41461. var data = seriesModel.getData();
  41462. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41463. symbolDraw.updateData(data, {
  41464. // TODO
  41465. // If this parameter should be a shape or a bounding volume
  41466. // shape will be more general.
  41467. // But bounding volume like bounding rect will be much faster in the contain calculation
  41468. clipShape: this._getClipShape(seriesModel)
  41469. });
  41470. this._finished = true;
  41471. };
  41472. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  41473. var data = seriesModel.getData();
  41474. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  41475. symbolDraw.incrementalPrepareUpdate(data);
  41476. this._finished = false;
  41477. };
  41478. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  41479. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  41480. clipShape: this._getClipShape(seriesModel)
  41481. });
  41482. this._finished = taskParams.end === seriesModel.getData().count();
  41483. };
  41484. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  41485. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  41486. // PENDING
  41487. this.group.dirty();
  41488. if (!this._finished || data.count() > 1e4) {
  41489. return {
  41490. update: true
  41491. };
  41492. } else {
  41493. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  41494. if (res.progress) {
  41495. res.progress({
  41496. start: 0,
  41497. end: data.count(),
  41498. count: data.count()
  41499. }, data);
  41500. }
  41501. this._symbolDraw.updateLayout(data);
  41502. }
  41503. };
  41504. ScatterView.prototype.eachRendered = function (cb) {
  41505. this._symbolDraw && this._symbolDraw.eachRendered(cb);
  41506. };
  41507. ScatterView.prototype._getClipShape = function (seriesModel) {
  41508. var coordSys = seriesModel.coordinateSystem;
  41509. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  41510. return seriesModel.get('clip', true) ? clipArea : null;
  41511. };
  41512. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  41513. var symbolDraw = this._symbolDraw;
  41514. var pipelineContext = seriesModel.pipelineContext;
  41515. var isLargeDraw = pipelineContext.large;
  41516. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  41517. symbolDraw && symbolDraw.remove();
  41518. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  41519. this._isLargeDraw = isLargeDraw;
  41520. this.group.removeAll();
  41521. }
  41522. this.group.add(symbolDraw.group);
  41523. return symbolDraw;
  41524. };
  41525. ScatterView.prototype.remove = function (ecModel, api) {
  41526. this._symbolDraw && this._symbolDraw.remove(true);
  41527. this._symbolDraw = null;
  41528. };
  41529. ScatterView.prototype.dispose = function () {};
  41530. ScatterView.type = 'scatter';
  41531. return ScatterView;
  41532. }(ChartView);
  41533. var GridModel =
  41534. /** @class */
  41535. function (_super) {
  41536. __extends(GridModel, _super);
  41537. function GridModel() {
  41538. return _super !== null && _super.apply(this, arguments) || this;
  41539. }
  41540. GridModel.type = 'grid';
  41541. GridModel.dependencies = ['xAxis', 'yAxis'];
  41542. GridModel.layoutMode = 'box';
  41543. GridModel.defaultOption = {
  41544. show: false,
  41545. // zlevel: 0,
  41546. z: 0,
  41547. left: '10%',
  41548. top: 60,
  41549. right: '10%',
  41550. bottom: 70,
  41551. // If grid size contain label
  41552. containLabel: false,
  41553. // width: {totalWidth} - left - right,
  41554. // height: {totalHeight} - top - bottom,
  41555. backgroundColor: 'rgba(0,0,0,0)',
  41556. borderWidth: 1,
  41557. borderColor: '#ccc'
  41558. };
  41559. return GridModel;
  41560. }(ComponentModel);
  41561. var CartesianAxisModel =
  41562. /** @class */
  41563. function (_super) {
  41564. __extends(CartesianAxisModel, _super);
  41565. function CartesianAxisModel() {
  41566. return _super !== null && _super.apply(this, arguments) || this;
  41567. }
  41568. CartesianAxisModel.prototype.getCoordSysModel = function () {
  41569. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  41570. };
  41571. CartesianAxisModel.type = 'cartesian2dAxis';
  41572. return CartesianAxisModel;
  41573. }(ComponentModel);
  41574. mixin(CartesianAxisModel, AxisModelCommonMixin);
  41575. var defaultOption = {
  41576. show: true,
  41577. // zlevel: 0,
  41578. z: 0,
  41579. // Inverse the axis.
  41580. inverse: false,
  41581. // Axis name displayed.
  41582. name: '',
  41583. // 'start' | 'middle' | 'end'
  41584. nameLocation: 'end',
  41585. // By degree. By default auto rotate by nameLocation.
  41586. nameRotate: null,
  41587. nameTruncate: {
  41588. maxWidth: null,
  41589. ellipsis: '...',
  41590. placeholder: '.'
  41591. },
  41592. // Use global text style by default.
  41593. nameTextStyle: {},
  41594. // The gap between axisName and axisLine.
  41595. nameGap: 15,
  41596. // Default `false` to support tooltip.
  41597. silent: false,
  41598. // Default `false` to avoid legacy user event listener fail.
  41599. triggerEvent: false,
  41600. tooltip: {
  41601. show: false
  41602. },
  41603. axisPointer: {},
  41604. axisLine: {
  41605. show: true,
  41606. onZero: true,
  41607. onZeroAxisIndex: null,
  41608. lineStyle: {
  41609. color: '#6E7079',
  41610. width: 1,
  41611. type: 'solid'
  41612. },
  41613. // The arrow at both ends the the axis.
  41614. symbol: ['none', 'none'],
  41615. symbolSize: [10, 15]
  41616. },
  41617. axisTick: {
  41618. show: true,
  41619. // Whether axisTick is inside the grid or outside the grid.
  41620. inside: false,
  41621. // The length of axisTick.
  41622. length: 5,
  41623. lineStyle: {
  41624. width: 1
  41625. }
  41626. },
  41627. axisLabel: {
  41628. show: true,
  41629. // Whether axisLabel is inside the grid or outside the grid.
  41630. inside: false,
  41631. rotate: 0,
  41632. // true | false | null/undefined (auto)
  41633. showMinLabel: null,
  41634. // true | false | null/undefined (auto)
  41635. showMaxLabel: null,
  41636. margin: 8,
  41637. // formatter: null,
  41638. fontSize: 12
  41639. },
  41640. splitLine: {
  41641. show: true,
  41642. lineStyle: {
  41643. color: ['#E0E6F1'],
  41644. width: 1,
  41645. type: 'solid'
  41646. }
  41647. },
  41648. splitArea: {
  41649. show: false,
  41650. areaStyle: {
  41651. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  41652. }
  41653. }
  41654. };
  41655. var categoryAxis = merge({
  41656. // The gap at both ends of the axis. For categoryAxis, boolean.
  41657. boundaryGap: true,
  41658. // Set false to faster category collection.
  41659. deduplication: null,
  41660. // splitArea: {
  41661. // show: false
  41662. // },
  41663. splitLine: {
  41664. show: false
  41665. },
  41666. axisTick: {
  41667. // If tick is align with label when boundaryGap is true
  41668. alignWithLabel: false,
  41669. interval: 'auto'
  41670. },
  41671. axisLabel: {
  41672. interval: 'auto'
  41673. }
  41674. }, defaultOption);
  41675. var valueAxis = merge({
  41676. boundaryGap: [0, 0],
  41677. axisLine: {
  41678. // Not shown when other axis is categoryAxis in cartesian
  41679. show: 'auto'
  41680. },
  41681. axisTick: {
  41682. // Not shown when other axis is categoryAxis in cartesian
  41683. show: 'auto'
  41684. },
  41685. // TODO
  41686. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  41687. splitNumber: 5,
  41688. minorTick: {
  41689. // Minor tick, not available for cateogry axis.
  41690. show: false,
  41691. // Split number of minor ticks. The value should be in range of (0, 100)
  41692. splitNumber: 5,
  41693. // Length of minor tick
  41694. length: 3,
  41695. // Line style
  41696. lineStyle: {// Default to be same with axisTick
  41697. }
  41698. },
  41699. minorSplitLine: {
  41700. show: false,
  41701. lineStyle: {
  41702. color: '#F4F7FD',
  41703. width: 1
  41704. }
  41705. }
  41706. }, defaultOption);
  41707. var timeAxis = merge({
  41708. splitNumber: 6,
  41709. axisLabel: {
  41710. // To eliminate labels that are not nice
  41711. showMinLabel: false,
  41712. showMaxLabel: false,
  41713. rich: {
  41714. primary: {
  41715. fontWeight: 'bold'
  41716. }
  41717. }
  41718. },
  41719. splitLine: {
  41720. show: false
  41721. }
  41722. }, valueAxis);
  41723. var logAxis = defaults({
  41724. logBase: 10
  41725. }, valueAxis);
  41726. var axisDefault = {
  41727. category: categoryAxis,
  41728. value: valueAxis,
  41729. time: timeAxis,
  41730. log: logAxis
  41731. };
  41732. /*
  41733. * Licensed to the Apache Software Foundation (ASF) under one
  41734. * or more contributor license agreements. See the NOTICE file
  41735. * distributed with this work for additional information
  41736. * regarding copyright ownership. The ASF licenses this file
  41737. * to you under the Apache License, Version 2.0 (the
  41738. * "License"); you may not use this file except in compliance
  41739. * with the License. You may obtain a copy of the License at
  41740. *
  41741. * http://www.apache.org/licenses/LICENSE-2.0
  41742. *
  41743. * Unless required by applicable law or agreed to in writing,
  41744. * software distributed under the License is distributed on an
  41745. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41746. * KIND, either express or implied. See the License for the
  41747. * specific language governing permissions and limitations
  41748. * under the License.
  41749. */
  41750. /**
  41751. * AUTO-GENERATED FILE. DO NOT MODIFY.
  41752. */
  41753. /*
  41754. * Licensed to the Apache Software Foundation (ASF) under one
  41755. * or more contributor license agreements. See the NOTICE file
  41756. * distributed with this work for additional information
  41757. * regarding copyright ownership. The ASF licenses this file
  41758. * to you under the Apache License, Version 2.0 (the
  41759. * "License"); you may not use this file except in compliance
  41760. * with the License. You may obtain a copy of the License at
  41761. *
  41762. * http://www.apache.org/licenses/LICENSE-2.0
  41763. *
  41764. * Unless required by applicable law or agreed to in writing,
  41765. * software distributed under the License is distributed on an
  41766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41767. * KIND, either express or implied. See the License for the
  41768. * specific language governing permissions and limitations
  41769. * under the License.
  41770. */
  41771. var AXIS_TYPES = {
  41772. value: 1,
  41773. category: 1,
  41774. time: 1,
  41775. log: 1
  41776. };
  41777. /**
  41778. * Generate sub axis model class
  41779. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  41780. */
  41781. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  41782. each(AXIS_TYPES, function (v, axisType) {
  41783. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  41784. var AxisModel =
  41785. /** @class */
  41786. function (_super) {
  41787. __extends(AxisModel, _super);
  41788. function AxisModel() {
  41789. var _this = _super !== null && _super.apply(this, arguments) || this;
  41790. _this.type = axisName + 'Axis.' + axisType;
  41791. return _this;
  41792. }
  41793. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  41794. var layoutMode = fetchLayoutMode(this);
  41795. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  41796. var themeModel = ecModel.getTheme();
  41797. merge(option, themeModel.get(axisType + 'Axis'));
  41798. merge(option, this.getDefaultOption());
  41799. option.type = getAxisType(option);
  41800. if (layoutMode) {
  41801. mergeLayoutParam(option, inputPositionParams, layoutMode);
  41802. }
  41803. };
  41804. AxisModel.prototype.optionUpdated = function () {
  41805. var thisOption = this.option;
  41806. if (thisOption.type === 'category') {
  41807. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  41808. }
  41809. };
  41810. /**
  41811. * Should not be called before all of 'getInitailData' finished.
  41812. * Because categories are collected during initializing data.
  41813. */
  41814. AxisModel.prototype.getCategories = function (rawData) {
  41815. var option = this.option; // FIXME
  41816. // warning if called before all of 'getInitailData' finished.
  41817. if (option.type === 'category') {
  41818. if (rawData) {
  41819. return option.data;
  41820. }
  41821. return this.__ordinalMeta.categories;
  41822. }
  41823. };
  41824. AxisModel.prototype.getOrdinalMeta = function () {
  41825. return this.__ordinalMeta;
  41826. };
  41827. AxisModel.type = axisName + 'Axis.' + axisType;
  41828. AxisModel.defaultOption = defaultOption;
  41829. return AxisModel;
  41830. }(BaseAxisModelClass);
  41831. registers.registerComponentModel(AxisModel);
  41832. });
  41833. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  41834. }
  41835. function getAxisType(option) {
  41836. // Default axis with data is category axis
  41837. return option.type || (option.data ? 'category' : 'value');
  41838. }
  41839. var Cartesian =
  41840. /** @class */
  41841. function () {
  41842. function Cartesian(name) {
  41843. this.type = 'cartesian';
  41844. this._dimList = [];
  41845. this._axes = {};
  41846. this.name = name || '';
  41847. }
  41848. Cartesian.prototype.getAxis = function (dim) {
  41849. return this._axes[dim];
  41850. };
  41851. Cartesian.prototype.getAxes = function () {
  41852. return map(this._dimList, function (dim) {
  41853. return this._axes[dim];
  41854. }, this);
  41855. };
  41856. Cartesian.prototype.getAxesByScale = function (scaleType) {
  41857. scaleType = scaleType.toLowerCase();
  41858. return filter(this.getAxes(), function (axis) {
  41859. return axis.scale.type === scaleType;
  41860. });
  41861. };
  41862. Cartesian.prototype.addAxis = function (axis) {
  41863. var dim = axis.dim;
  41864. this._axes[dim] = axis;
  41865. this._dimList.push(dim);
  41866. };
  41867. return Cartesian;
  41868. }();
  41869. var cartesian2DDimensions = ['x', 'y'];
  41870. function canCalculateAffineTransform(scale) {
  41871. return scale.type === 'interval' || scale.type === 'time';
  41872. }
  41873. var Cartesian2D =
  41874. /** @class */
  41875. function (_super) {
  41876. __extends(Cartesian2D, _super);
  41877. function Cartesian2D() {
  41878. var _this = _super !== null && _super.apply(this, arguments) || this;
  41879. _this.type = 'cartesian2d';
  41880. _this.dimensions = cartesian2DDimensions;
  41881. return _this;
  41882. }
  41883. /**
  41884. * Calculate an affine transform matrix if two axes are time or value.
  41885. * It's mainly for accelartion on the large time series data.
  41886. */
  41887. Cartesian2D.prototype.calcAffineTransform = function () {
  41888. this._transform = this._invTransform = null;
  41889. var xAxisScale = this.getAxis('x').scale;
  41890. var yAxisScale = this.getAxis('y').scale;
  41891. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  41892. return;
  41893. }
  41894. var xScaleExtent = xAxisScale.getExtent();
  41895. var yScaleExtent = yAxisScale.getExtent();
  41896. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  41897. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  41898. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  41899. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  41900. if (!xScaleSpan || !yScaleSpan) {
  41901. return;
  41902. } // Accelerate data to point calculation on the special large time series data.
  41903. var scaleX = (end[0] - start[0]) / xScaleSpan;
  41904. var scaleY = (end[1] - start[1]) / yScaleSpan;
  41905. var translateX = start[0] - xScaleExtent[0] * scaleX;
  41906. var translateY = start[1] - yScaleExtent[0] * scaleY;
  41907. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  41908. this._invTransform = invert([], m);
  41909. };
  41910. /**
  41911. * Base axis will be used on stacking.
  41912. */
  41913. Cartesian2D.prototype.getBaseAxis = function () {
  41914. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  41915. };
  41916. Cartesian2D.prototype.containPoint = function (point) {
  41917. var axisX = this.getAxis('x');
  41918. var axisY = this.getAxis('y');
  41919. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  41920. };
  41921. Cartesian2D.prototype.containData = function (data) {
  41922. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  41923. };
  41924. Cartesian2D.prototype.containZone = function (data1, data2) {
  41925. var zoneDiag1 = this.dataToPoint(data1);
  41926. var zoneDiag2 = this.dataToPoint(data2);
  41927. var area = this.getArea();
  41928. var zone = new BoundingRect(zoneDiag1[0], zoneDiag1[1], zoneDiag2[0] - zoneDiag1[0], zoneDiag2[1] - zoneDiag1[1]);
  41929. return area.intersect(zone);
  41930. };
  41931. Cartesian2D.prototype.dataToPoint = function (data, clamp, out) {
  41932. out = out || [];
  41933. var xVal = data[0];
  41934. var yVal = data[1]; // Fast path
  41935. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  41936. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  41937. return applyTransform(out, data, this._transform);
  41938. }
  41939. var xAxis = this.getAxis('x');
  41940. var yAxis = this.getAxis('y');
  41941. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal, clamp));
  41942. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal, clamp));
  41943. return out;
  41944. };
  41945. Cartesian2D.prototype.clampData = function (data, out) {
  41946. var xScale = this.getAxis('x').scale;
  41947. var yScale = this.getAxis('y').scale;
  41948. var xAxisExtent = xScale.getExtent();
  41949. var yAxisExtent = yScale.getExtent();
  41950. var x = xScale.parse(data[0]);
  41951. var y = yScale.parse(data[1]);
  41952. out = out || [];
  41953. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  41954. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  41955. return out;
  41956. };
  41957. Cartesian2D.prototype.pointToData = function (point, clamp) {
  41958. var out = [];
  41959. if (this._invTransform) {
  41960. return applyTransform(out, point, this._invTransform);
  41961. }
  41962. var xAxis = this.getAxis('x');
  41963. var yAxis = this.getAxis('y');
  41964. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp);
  41965. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp);
  41966. return out;
  41967. };
  41968. Cartesian2D.prototype.getOtherAxis = function (axis) {
  41969. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  41970. };
  41971. /**
  41972. * Get rect area of cartesian.
  41973. * Area will have a contain function to determine if a point is in the coordinate system.
  41974. */
  41975. Cartesian2D.prototype.getArea = function () {
  41976. var xExtent = this.getAxis('x').getGlobalExtent();
  41977. var yExtent = this.getAxis('y').getGlobalExtent();
  41978. var x = Math.min(xExtent[0], xExtent[1]);
  41979. var y = Math.min(yExtent[0], yExtent[1]);
  41980. var width = Math.max(xExtent[0], xExtent[1]) - x;
  41981. var height = Math.max(yExtent[0], yExtent[1]) - y;
  41982. return new BoundingRect(x, y, width, height);
  41983. };
  41984. return Cartesian2D;
  41985. }(Cartesian);
  41986. var Axis2D =
  41987. /** @class */
  41988. function (_super) {
  41989. __extends(Axis2D, _super);
  41990. function Axis2D(dim, scale, coordExtent, axisType, position) {
  41991. var _this = _super.call(this, dim, scale, coordExtent) || this;
  41992. /**
  41993. * Index of axis, can be used as key
  41994. * Injected outside.
  41995. */
  41996. _this.index = 0;
  41997. _this.type = axisType || 'value';
  41998. _this.position = position || 'bottom';
  41999. return _this;
  42000. }
  42001. Axis2D.prototype.isHorizontal = function () {
  42002. var position = this.position;
  42003. return position === 'top' || position === 'bottom';
  42004. };
  42005. /**
  42006. * Each item cooresponds to this.getExtent(), which
  42007. * means globalExtent[0] may greater than globalExtent[1],
  42008. * unless `asc` is input.
  42009. *
  42010. * @param {boolean} [asc]
  42011. * @return {Array.<number>}
  42012. */
  42013. Axis2D.prototype.getGlobalExtent = function (asc) {
  42014. var ret = this.getExtent();
  42015. ret[0] = this.toGlobalCoord(ret[0]);
  42016. ret[1] = this.toGlobalCoord(ret[1]);
  42017. asc && ret[0] > ret[1] && ret.reverse();
  42018. return ret;
  42019. };
  42020. Axis2D.prototype.pointToData = function (point, clamp) {
  42021. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  42022. };
  42023. /**
  42024. * Set ordinalSortInfo
  42025. * @param info new OrdinalSortInfo
  42026. */
  42027. Axis2D.prototype.setCategorySortInfo = function (info) {
  42028. if (this.type !== 'category') {
  42029. return false;
  42030. }
  42031. this.model.option.categorySortInfo = info;
  42032. this.scale.setSortInfo(info);
  42033. };
  42034. return Axis2D;
  42035. }(Axis);
  42036. /**
  42037. * Can only be called after coordinate system creation stage.
  42038. * (Can be called before coordinate system update stage).
  42039. */
  42040. function layout$1(gridModel, axisModel, opt) {
  42041. opt = opt || {};
  42042. var grid = gridModel.coordinateSystem;
  42043. var axis = axisModel.axis;
  42044. var layout = {};
  42045. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  42046. var rawAxisPosition = axis.position;
  42047. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  42048. var axisDim = axis.dim;
  42049. var rect = grid.getRect();
  42050. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  42051. var idx = {
  42052. left: 0,
  42053. right: 1,
  42054. top: 0,
  42055. bottom: 1,
  42056. onZero: 2
  42057. };
  42058. var axisOffset = axisModel.get('offset') || 0;
  42059. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  42060. if (otherAxisOnZeroOf) {
  42061. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  42062. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  42063. } // Axis position
  42064. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  42065. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  42066. var dirMap = {
  42067. top: -1,
  42068. bottom: 1,
  42069. left: -1,
  42070. right: 1
  42071. };
  42072. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  42073. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  42074. if (axisModel.get(['axisTick', 'inside'])) {
  42075. layout.tickDirection = -layout.tickDirection;
  42076. }
  42077. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  42078. layout.labelDirection = -layout.labelDirection;
  42079. } // Special label rotation
  42080. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  42081. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  42082. layout.z2 = 1;
  42083. return layout;
  42084. }
  42085. function isCartesian2DSeries(seriesModel) {
  42086. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  42087. }
  42088. function findAxisModels(seriesModel) {
  42089. var axisModelMap = {
  42090. xAxisModel: null,
  42091. yAxisModel: null
  42092. };
  42093. each(axisModelMap, function (v, key) {
  42094. var axisType = key.replace(/Model$/, '');
  42095. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  42096. if ("development" !== 'production') {
  42097. if (!axisModel) {
  42098. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  42099. }
  42100. }
  42101. axisModelMap[key] = axisModel;
  42102. });
  42103. return axisModelMap;
  42104. }
  42105. var mathLog$1 = Math.log;
  42106. function alignScaleTicks(scale, axisModel, alignToScale) {
  42107. var intervalScaleProto = IntervalScale.prototype; // NOTE: There is a precondition for log scale here:
  42108. // In log scale we store _interval and _extent of exponent value.
  42109. // So if we use the method of InternalScale to set/get these data.
  42110. // It process the exponent value, which is linear and what we want here.
  42111. var alignToTicks = intervalScaleProto.getTicks.call(alignToScale);
  42112. var alignToNicedTicks = intervalScaleProto.getTicks.call(alignToScale, true);
  42113. var alignToSplitNumber = alignToTicks.length - 1;
  42114. var alignToInterval = intervalScaleProto.getInterval.call(alignToScale);
  42115. var scaleExtent = getScaleExtent(scale, axisModel);
  42116. var rawExtent = scaleExtent.extent;
  42117. var isMinFixed = scaleExtent.fixMin;
  42118. var isMaxFixed = scaleExtent.fixMax;
  42119. if (scale.type === 'log') {
  42120. var logBase = mathLog$1(scale.base);
  42121. rawExtent = [mathLog$1(rawExtent[0]) / logBase, mathLog$1(rawExtent[1]) / logBase];
  42122. }
  42123. scale.setExtent(rawExtent[0], rawExtent[1]);
  42124. scale.calcNiceExtent({
  42125. splitNumber: alignToSplitNumber,
  42126. fixMin: isMinFixed,
  42127. fixMax: isMaxFixed
  42128. });
  42129. var extent = intervalScaleProto.getExtent.call(scale); // Need to update the rawExtent.
  42130. // Because value in rawExtent may be not parsed. e.g. 'dataMin', 'dataMax'
  42131. if (isMinFixed) {
  42132. rawExtent[0] = extent[0];
  42133. }
  42134. if (isMaxFixed) {
  42135. rawExtent[1] = extent[1];
  42136. }
  42137. var interval = intervalScaleProto.getInterval.call(scale);
  42138. var min = rawExtent[0];
  42139. var max = rawExtent[1];
  42140. if (isMinFixed && isMaxFixed) {
  42141. // User set min, max, divide to get new interval
  42142. interval = (max - min) / alignToSplitNumber;
  42143. } else if (isMinFixed) {
  42144. max = rawExtent[0] + interval * alignToSplitNumber; // User set min, expand extent on the other side
  42145. while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1])) {
  42146. interval = increaseInterval(interval);
  42147. max = rawExtent[0] + interval * alignToSplitNumber;
  42148. }
  42149. } else if (isMaxFixed) {
  42150. // User set max, expand extent on the other side
  42151. min = rawExtent[1] - interval * alignToSplitNumber;
  42152. while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0])) {
  42153. interval = increaseInterval(interval);
  42154. min = rawExtent[1] - interval * alignToSplitNumber;
  42155. }
  42156. } else {
  42157. var nicedSplitNumber = scale.getTicks().length - 1;
  42158. if (nicedSplitNumber > alignToSplitNumber) {
  42159. interval = increaseInterval(interval);
  42160. }
  42161. var range = interval * alignToSplitNumber;
  42162. max = Math.ceil(rawExtent[1] / interval) * interval;
  42163. min = round(max - range); // Not change the result that crossing zero.
  42164. if (min < 0 && rawExtent[0] >= 0) {
  42165. min = 0;
  42166. max = round(range);
  42167. } else if (max > 0 && rawExtent[1] <= 0) {
  42168. max = 0;
  42169. min = -round(range);
  42170. }
  42171. } // Adjust min, max based on the extent of alignTo. When min or max is set in alignTo scale
  42172. var t0 = (alignToTicks[0].value - alignToNicedTicks[0].value) / alignToInterval;
  42173. var t1 = (alignToTicks[alignToSplitNumber].value - alignToNicedTicks[alignToSplitNumber].value) / alignToInterval; // NOTE: Must in setExtent -> setInterval -> setNiceExtent order.
  42174. intervalScaleProto.setExtent.call(scale, min + interval * t0, max + interval * t1);
  42175. intervalScaleProto.setInterval.call(scale, interval);
  42176. if (t0 || t1) {
  42177. intervalScaleProto.setNiceExtent.call(scale, min + interval, max - interval);
  42178. }
  42179. if ("development" !== 'production') {
  42180. var ticks = intervalScaleProto.getTicks.call(scale);
  42181. if (ticks[1] && (!isValueNice(interval) || getPrecisionSafe(ticks[1].value) > getPrecisionSafe(interval))) {
  42182. warn( // eslint-disable-next-line
  42183. "The ticks may be not readable when set min: " + axisModel.get('min') + ", max: " + axisModel.get('max') + " and alignTicks: true");
  42184. }
  42185. }
  42186. }
  42187. var Grid =
  42188. /** @class */
  42189. function () {
  42190. function Grid(gridModel, ecModel, api) {
  42191. // FIXME:TS where used (different from registered type 'cartesian2d')?
  42192. this.type = 'grid';
  42193. this._coordsMap = {};
  42194. this._coordsList = [];
  42195. this._axesMap = {};
  42196. this._axesList = [];
  42197. this.axisPointerEnabled = true;
  42198. this.dimensions = cartesian2DDimensions;
  42199. this._initCartesian(gridModel, ecModel, api);
  42200. this.model = gridModel;
  42201. }
  42202. Grid.prototype.getRect = function () {
  42203. return this._rect;
  42204. };
  42205. Grid.prototype.update = function (ecModel, api) {
  42206. var axesMap = this._axesMap;
  42207. this._updateScale(ecModel, this.model);
  42208. function updateAxisTicks(axes) {
  42209. var alignTo; // Axis is added in order of axisIndex.
  42210. var axesIndices = keys(axes);
  42211. var len = axesIndices.length;
  42212. if (!len) {
  42213. return;
  42214. }
  42215. var axisNeedsAlign = []; // Process once and calculate the ticks for those don't use alignTicks.
  42216. for (var i = len - 1; i >= 0; i--) {
  42217. var idx = +axesIndices[i]; // Convert to number.
  42218. var axis = axes[idx];
  42219. var model = axis.model;
  42220. var scale = axis.scale;
  42221. if ( // Only value and log axis without interval support alignTicks.
  42222. isIntervalOrLogScale(scale) && model.get('alignTicks') && model.get('interval') == null) {
  42223. axisNeedsAlign.push(axis);
  42224. } else {
  42225. niceScaleExtent(scale, model);
  42226. if (isIntervalOrLogScale(scale)) {
  42227. // Can only align to interval or log axis.
  42228. alignTo = axis;
  42229. }
  42230. }
  42231. }
  42232. // PENDING. Should we find the axis that both set interval, min, max and align to this one?
  42233. if (axisNeedsAlign.length) {
  42234. if (!alignTo) {
  42235. alignTo = axisNeedsAlign.pop();
  42236. niceScaleExtent(alignTo.scale, alignTo.model);
  42237. }
  42238. each(axisNeedsAlign, function (axis) {
  42239. alignScaleTicks(axis.scale, axis.model, alignTo.scale);
  42240. });
  42241. }
  42242. }
  42243. updateAxisTicks(axesMap.x);
  42244. updateAxisTicks(axesMap.y); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  42245. var onZeroRecords = {};
  42246. each(axesMap.x, function (xAxis) {
  42247. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  42248. });
  42249. each(axesMap.y, function (yAxis) {
  42250. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  42251. }); // Resize again if containLabel is enabled
  42252. // FIXME It may cause getting wrong grid size in data processing stage
  42253. this.resize(this.model, api);
  42254. };
  42255. /**
  42256. * Resize the grid
  42257. */
  42258. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  42259. var boxLayoutParams = gridModel.getBoxLayoutParams();
  42260. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  42261. var gridRect = getLayoutRect(boxLayoutParams, {
  42262. width: api.getWidth(),
  42263. height: api.getHeight()
  42264. });
  42265. this._rect = gridRect;
  42266. var axesList = this._axesList;
  42267. adjustAxes(); // Minus label size
  42268. if (isContainLabel) {
  42269. each(axesList, function (axis) {
  42270. if (!axis.model.get(['axisLabel', 'inside'])) {
  42271. var labelUnionRect = estimateLabelUnionRect(axis);
  42272. if (labelUnionRect) {
  42273. var dim = axis.isHorizontal() ? 'height' : 'width';
  42274. var margin = axis.model.get(['axisLabel', 'margin']);
  42275. gridRect[dim] -= labelUnionRect[dim] + margin;
  42276. if (axis.position === 'top') {
  42277. gridRect.y += labelUnionRect.height + margin;
  42278. } else if (axis.position === 'left') {
  42279. gridRect.x += labelUnionRect.width + margin;
  42280. }
  42281. }
  42282. }
  42283. });
  42284. adjustAxes();
  42285. }
  42286. each(this._coordsList, function (coord) {
  42287. // Calculate affine matrix to accelerate the data to point transform.
  42288. // If all the axes scales are time or value.
  42289. coord.calcAffineTransform();
  42290. });
  42291. function adjustAxes() {
  42292. each(axesList, function (axis) {
  42293. var isHorizontal = axis.isHorizontal();
  42294. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  42295. var idx = axis.inverse ? 1 : 0;
  42296. axis.setExtent(extent[idx], extent[1 - idx]);
  42297. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  42298. });
  42299. }
  42300. };
  42301. Grid.prototype.getAxis = function (dim, axisIndex) {
  42302. var axesMapOnDim = this._axesMap[dim];
  42303. if (axesMapOnDim != null) {
  42304. return axesMapOnDim[axisIndex || 0];
  42305. }
  42306. };
  42307. Grid.prototype.getAxes = function () {
  42308. return this._axesList.slice();
  42309. };
  42310. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  42311. if (xAxisIndex != null && yAxisIndex != null) {
  42312. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42313. return this._coordsMap[key];
  42314. }
  42315. if (isObject(xAxisIndex)) {
  42316. yAxisIndex = xAxisIndex.yAxisIndex;
  42317. xAxisIndex = xAxisIndex.xAxisIndex;
  42318. }
  42319. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  42320. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  42321. return coordList[i];
  42322. }
  42323. }
  42324. };
  42325. Grid.prototype.getCartesians = function () {
  42326. return this._coordsList.slice();
  42327. };
  42328. /**
  42329. * @implements
  42330. */
  42331. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  42332. var target = this._findConvertTarget(finder);
  42333. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  42334. };
  42335. /**
  42336. * @implements
  42337. */
  42338. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  42339. var target = this._findConvertTarget(finder);
  42340. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  42341. };
  42342. Grid.prototype._findConvertTarget = function (finder) {
  42343. var seriesModel = finder.seriesModel;
  42344. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  42345. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  42346. var gridModel = finder.gridModel;
  42347. var coordsList = this._coordsList;
  42348. var cartesian;
  42349. var axis;
  42350. if (seriesModel) {
  42351. cartesian = seriesModel.coordinateSystem;
  42352. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  42353. } else if (xAxisModel && yAxisModel) {
  42354. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42355. } else if (xAxisModel) {
  42356. axis = this.getAxis('x', xAxisModel.componentIndex);
  42357. } else if (yAxisModel) {
  42358. axis = this.getAxis('y', yAxisModel.componentIndex);
  42359. } // Lowest priority.
  42360. else if (gridModel) {
  42361. var grid = gridModel.coordinateSystem;
  42362. if (grid === this) {
  42363. cartesian = this._coordsList[0];
  42364. }
  42365. }
  42366. return {
  42367. cartesian: cartesian,
  42368. axis: axis
  42369. };
  42370. };
  42371. /**
  42372. * @implements
  42373. */
  42374. Grid.prototype.containPoint = function (point) {
  42375. var coord = this._coordsList[0];
  42376. if (coord) {
  42377. return coord.containPoint(point);
  42378. }
  42379. };
  42380. /**
  42381. * Initialize cartesian coordinate systems
  42382. */
  42383. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  42384. var _this = this;
  42385. var grid = this;
  42386. var axisPositionUsed = {
  42387. left: false,
  42388. right: false,
  42389. top: false,
  42390. bottom: false
  42391. };
  42392. var axesMap = {
  42393. x: {},
  42394. y: {}
  42395. };
  42396. var axesCount = {
  42397. x: 0,
  42398. y: 0
  42399. }; // Create axis
  42400. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  42401. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  42402. if (!axesCount.x || !axesCount.y) {
  42403. // Roll back when there no either x or y axis
  42404. this._axesMap = {};
  42405. this._axesList = [];
  42406. return;
  42407. }
  42408. this._axesMap = axesMap; // Create cartesian2d
  42409. each(axesMap.x, function (xAxis, xAxisIndex) {
  42410. each(axesMap.y, function (yAxis, yAxisIndex) {
  42411. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  42412. var cartesian = new Cartesian2D(key);
  42413. cartesian.master = _this;
  42414. cartesian.model = gridModel;
  42415. _this._coordsMap[key] = cartesian;
  42416. _this._coordsList.push(cartesian);
  42417. cartesian.addAxis(xAxis);
  42418. cartesian.addAxis(yAxis);
  42419. });
  42420. });
  42421. function createAxisCreator(dimName) {
  42422. return function (axisModel, idx) {
  42423. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  42424. return;
  42425. }
  42426. var axisPosition = axisModel.get('position');
  42427. if (dimName === 'x') {
  42428. // Fix position
  42429. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  42430. // Default bottom of X
  42431. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  42432. }
  42433. } else {
  42434. // Fix position
  42435. if (axisPosition !== 'left' && axisPosition !== 'right') {
  42436. // Default left of Y
  42437. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  42438. }
  42439. }
  42440. axisPositionUsed[axisPosition] = true;
  42441. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  42442. var isCategory = axis.type === 'category';
  42443. axis.onBand = isCategory && axisModel.get('boundaryGap');
  42444. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  42445. axisModel.axis = axis; // Inject axisModel into axis
  42446. axis.model = axisModel; // Inject grid info axis
  42447. axis.grid = grid; // Index of axis, can be used as key
  42448. axis.index = idx;
  42449. grid._axesList.push(axis);
  42450. axesMap[dimName][idx] = axis;
  42451. axesCount[dimName]++;
  42452. };
  42453. }
  42454. };
  42455. /**
  42456. * Update cartesian properties from series.
  42457. */
  42458. Grid.prototype._updateScale = function (ecModel, gridModel) {
  42459. // Reset scale
  42460. each(this._axesList, function (axis) {
  42461. axis.scale.setExtent(Infinity, -Infinity);
  42462. if (axis.type === 'category') {
  42463. var categorySortInfo = axis.model.get('categorySortInfo');
  42464. axis.scale.setSortInfo(categorySortInfo);
  42465. }
  42466. });
  42467. ecModel.eachSeries(function (seriesModel) {
  42468. if (isCartesian2DSeries(seriesModel)) {
  42469. var axesModelMap = findAxisModels(seriesModel);
  42470. var xAxisModel = axesModelMap.xAxisModel;
  42471. var yAxisModel = axesModelMap.yAxisModel;
  42472. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  42473. return;
  42474. }
  42475. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42476. var data = seriesModel.getData();
  42477. var xAxis = cartesian.getAxis('x');
  42478. var yAxis = cartesian.getAxis('y');
  42479. unionExtent(data, xAxis);
  42480. unionExtent(data, yAxis);
  42481. }
  42482. }, this);
  42483. function unionExtent(data, axis) {
  42484. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  42485. axis.scale.unionExtentFromData(data, dim);
  42486. });
  42487. }
  42488. };
  42489. /**
  42490. * @param dim 'x' or 'y' or 'auto' or null/undefined
  42491. */
  42492. Grid.prototype.getTooltipAxes = function (dim) {
  42493. var baseAxes = [];
  42494. var otherAxes = [];
  42495. each(this.getCartesians(), function (cartesian) {
  42496. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  42497. var otherAxis = cartesian.getOtherAxis(baseAxis);
  42498. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  42499. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  42500. });
  42501. return {
  42502. baseAxes: baseAxes,
  42503. otherAxes: otherAxes
  42504. };
  42505. };
  42506. Grid.create = function (ecModel, api) {
  42507. var grids = [];
  42508. ecModel.eachComponent('grid', function (gridModel, idx) {
  42509. var grid = new Grid(gridModel, ecModel, api);
  42510. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  42511. // should be performed in create stage.
  42512. grid.resize(gridModel, api, true);
  42513. gridModel.coordinateSystem = grid;
  42514. grids.push(grid);
  42515. }); // Inject the coordinateSystems into seriesModel
  42516. ecModel.eachSeries(function (seriesModel) {
  42517. if (!isCartesian2DSeries(seriesModel)) {
  42518. return;
  42519. }
  42520. var axesModelMap = findAxisModels(seriesModel);
  42521. var xAxisModel = axesModelMap.xAxisModel;
  42522. var yAxisModel = axesModelMap.yAxisModel;
  42523. var gridModel = xAxisModel.getCoordSysModel();
  42524. if ("development" !== 'production') {
  42525. if (!gridModel) {
  42526. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  42527. }
  42528. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  42529. throw new Error('xAxis and yAxis must use the same grid');
  42530. }
  42531. }
  42532. var grid = gridModel.coordinateSystem;
  42533. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  42534. });
  42535. return grids;
  42536. }; // For deciding which dimensions to use when creating list data
  42537. Grid.dimensions = cartesian2DDimensions;
  42538. return Grid;
  42539. }();
  42540. /**
  42541. * Check if the axis is used in the specified grid.
  42542. */
  42543. function isAxisUsedInTheGrid(axisModel, gridModel) {
  42544. return axisModel.getCoordSysModel() === gridModel;
  42545. }
  42546. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  42547. onZeroRecords) {
  42548. axis.getAxesOnZeroOf = function () {
  42549. // TODO: onZero of multiple axes.
  42550. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  42551. }; // onZero can not be enabled in these two situations:
  42552. // 1. When any other axis is a category axis.
  42553. // 2. When no axis is cross 0 point.
  42554. var otherAxes = axesMap[otherAxisDim];
  42555. var otherAxisOnZeroOf;
  42556. var axisModel = axis.model;
  42557. var onZero = axisModel.get(['axisLine', 'onZero']);
  42558. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  42559. if (!onZero) {
  42560. return;
  42561. } // If target axis is specified.
  42562. if (onZeroAxisIndex != null) {
  42563. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  42564. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  42565. }
  42566. } else {
  42567. // Find the first available other axis.
  42568. for (var idx in otherAxes) {
  42569. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  42570. // if both onZero, the two Y axes overlap.
  42571. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  42572. otherAxisOnZeroOf = otherAxes[idx];
  42573. break;
  42574. }
  42575. }
  42576. }
  42577. if (otherAxisOnZeroOf) {
  42578. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  42579. }
  42580. function getOnZeroRecordKey(axis) {
  42581. return axis.dim + '_' + axis.index;
  42582. }
  42583. }
  42584. function canOnZeroToAxis(axis) {
  42585. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  42586. }
  42587. function updateAxisTransform(axis, coordBase) {
  42588. var axisExtent = axis.getExtent();
  42589. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  42590. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  42591. return coord + coordBase;
  42592. } : function (coord) {
  42593. return axisExtentSum - coord + coordBase;
  42594. };
  42595. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  42596. return coord - coordBase;
  42597. } : function (coord) {
  42598. return axisExtentSum - coord + coordBase;
  42599. };
  42600. }
  42601. var PI$5 = Math.PI;
  42602. /**
  42603. * A final axis is translated and rotated from a "standard axis".
  42604. * So opt.position and opt.rotation is required.
  42605. *
  42606. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  42607. * for example: (0, 0) ------------> (0, 50)
  42608. *
  42609. * nameDirection or tickDirection or labelDirection is 1 means tick
  42610. * or label is below the standard axis, whereas is -1 means above
  42611. * the standard axis. labelOffset means offset between label and axis,
  42612. * which is useful when 'onZero', where axisLabel is in the grid and
  42613. * label in outside grid.
  42614. *
  42615. * Tips: like always,
  42616. * positive rotation represents anticlockwise, and negative rotation
  42617. * represents clockwise.
  42618. * The direction of position coordinate is the same as the direction
  42619. * of screen coordinate.
  42620. *
  42621. * Do not need to consider axis 'inverse', which is auto processed by
  42622. * axis extent.
  42623. */
  42624. var AxisBuilder =
  42625. /** @class */
  42626. function () {
  42627. function AxisBuilder(axisModel, opt) {
  42628. this.group = new Group();
  42629. this.opt = opt;
  42630. this.axisModel = axisModel; // Default value
  42631. defaults(opt, {
  42632. labelOffset: 0,
  42633. nameDirection: 1,
  42634. tickDirection: 1,
  42635. labelDirection: 1,
  42636. silent: true,
  42637. handleAutoShown: function () {
  42638. return true;
  42639. }
  42640. }); // FIXME Not use a separate text group?
  42641. var transformGroup = new Group({
  42642. x: opt.position[0],
  42643. y: opt.position[1],
  42644. rotation: opt.rotation
  42645. }); // this.group.add(transformGroup);
  42646. // this._transformGroup = transformGroup;
  42647. transformGroup.updateTransform();
  42648. this._transformGroup = transformGroup;
  42649. }
  42650. AxisBuilder.prototype.hasBuilder = function (name) {
  42651. return !!builders[name];
  42652. };
  42653. AxisBuilder.prototype.add = function (name) {
  42654. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  42655. };
  42656. AxisBuilder.prototype.getGroup = function () {
  42657. return this.group;
  42658. };
  42659. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  42660. var rotationDiff = remRadian(textRotation - axisRotation);
  42661. var textAlign;
  42662. var textVerticalAlign;
  42663. if (isRadianAroundZero(rotationDiff)) {
  42664. // Label is parallel with axis line.
  42665. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  42666. textAlign = 'center';
  42667. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  42668. // Label is inverse parallel with axis line.
  42669. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  42670. textAlign = 'center';
  42671. } else {
  42672. textVerticalAlign = 'middle';
  42673. if (rotationDiff > 0 && rotationDiff < PI$5) {
  42674. textAlign = direction > 0 ? 'right' : 'left';
  42675. } else {
  42676. textAlign = direction > 0 ? 'left' : 'right';
  42677. }
  42678. }
  42679. return {
  42680. rotation: rotationDiff,
  42681. textAlign: textAlign,
  42682. textVerticalAlign: textVerticalAlign
  42683. };
  42684. };
  42685. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  42686. var eventData = {
  42687. componentType: axisModel.mainType,
  42688. componentIndex: axisModel.componentIndex
  42689. };
  42690. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  42691. return eventData;
  42692. };
  42693. AxisBuilder.isLabelSilent = function (axisModel) {
  42694. var tooltipOpt = axisModel.get('tooltip');
  42695. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  42696. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  42697. };
  42698. return AxisBuilder;
  42699. }();
  42700. var builders = {
  42701. axisLine: function (opt, axisModel, group, transformGroup) {
  42702. var shown = axisModel.get(['axisLine', 'show']);
  42703. if (shown === 'auto' && opt.handleAutoShown) {
  42704. shown = opt.handleAutoShown('axisLine');
  42705. }
  42706. if (!shown) {
  42707. return;
  42708. }
  42709. var extent = axisModel.axis.getExtent();
  42710. var matrix = transformGroup.transform;
  42711. var pt1 = [extent[0], 0];
  42712. var pt2 = [extent[1], 0];
  42713. var inverse = pt1[0] > pt2[0];
  42714. if (matrix) {
  42715. applyTransform(pt1, pt1, matrix);
  42716. applyTransform(pt2, pt2, matrix);
  42717. }
  42718. var lineStyle = extend({
  42719. lineCap: 'round'
  42720. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  42721. var line = new Line({
  42722. shape: {
  42723. x1: pt1[0],
  42724. y1: pt1[1],
  42725. x2: pt2[0],
  42726. y2: pt2[1]
  42727. },
  42728. style: lineStyle,
  42729. strokeContainThreshold: opt.strokeContainThreshold || 5,
  42730. silent: true,
  42731. z2: 1
  42732. });
  42733. subPixelOptimizeLine$1(line.shape, line.style.lineWidth);
  42734. line.anid = 'line';
  42735. group.add(line);
  42736. var arrows = axisModel.get(['axisLine', 'symbol']);
  42737. if (arrows != null) {
  42738. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  42739. if (isString(arrows)) {
  42740. // Use the same arrow for start and end point
  42741. arrows = [arrows, arrows];
  42742. }
  42743. if (isString(arrowSize) || isNumber(arrowSize)) {
  42744. // Use the same size for width and height
  42745. arrowSize = [arrowSize, arrowSize];
  42746. }
  42747. var arrowOffset = normalizeSymbolOffset(axisModel.get(['axisLine', 'symbolOffset']) || 0, arrowSize);
  42748. var symbolWidth_1 = arrowSize[0];
  42749. var symbolHeight_1 = arrowSize[1];
  42750. each([{
  42751. rotate: opt.rotation + Math.PI / 2,
  42752. offset: arrowOffset[0],
  42753. r: 0
  42754. }, {
  42755. rotate: opt.rotation - Math.PI / 2,
  42756. offset: arrowOffset[1],
  42757. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  42758. }], function (point, index) {
  42759. if (arrows[index] !== 'none' && arrows[index] != null) {
  42760. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  42761. var r = point.r + point.offset;
  42762. var pt = inverse ? pt2 : pt1;
  42763. symbol.attr({
  42764. rotation: point.rotate,
  42765. x: pt[0] + r * Math.cos(opt.rotation),
  42766. y: pt[1] - r * Math.sin(opt.rotation),
  42767. silent: true,
  42768. z2: 11
  42769. });
  42770. group.add(symbol);
  42771. }
  42772. });
  42773. }
  42774. },
  42775. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  42776. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  42777. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  42778. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  42779. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection); // This bit fixes the label overlap issue for the time chart.
  42780. // See https://github.com/apache/echarts/issues/14266 for more.
  42781. if (axisModel.get(['axisLabel', 'hideOverlap'])) {
  42782. var labelList = prepareLayoutList(map(labelEls, function (label) {
  42783. return {
  42784. label: label,
  42785. priority: label.z2,
  42786. defaultAttr: {
  42787. ignore: label.ignore
  42788. }
  42789. };
  42790. }));
  42791. hideOverlap(labelList);
  42792. }
  42793. },
  42794. axisName: function (opt, axisModel, group, transformGroup) {
  42795. var name = retrieve(opt.axisName, axisModel.get('name'));
  42796. if (!name) {
  42797. return;
  42798. }
  42799. var nameLocation = axisModel.get('nameLocation');
  42800. var nameDirection = opt.nameDirection;
  42801. var textStyleModel = axisModel.getModel('nameTextStyle');
  42802. var gap = axisModel.get('nameGap') || 0;
  42803. var extent = axisModel.axis.getExtent();
  42804. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  42805. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  42806. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  42807. var labelLayout;
  42808. var nameRotation = axisModel.get('nameRotate');
  42809. if (nameRotation != null) {
  42810. nameRotation = nameRotation * PI$5 / 180; // To radian.
  42811. }
  42812. var axisNameAvailableWidth;
  42813. if (isNameLocationCenter(nameLocation)) {
  42814. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  42815. nameDirection);
  42816. } else {
  42817. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  42818. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  42819. if (axisNameAvailableWidth != null) {
  42820. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  42821. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  42822. }
  42823. }
  42824. var textFont = textStyleModel.getFont();
  42825. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  42826. var ellipsis = truncateOpt.ellipsis;
  42827. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  42828. var textEl = new ZRText({
  42829. x: pos[0],
  42830. y: pos[1],
  42831. rotation: labelLayout.rotation,
  42832. silent: AxisBuilder.isLabelSilent(axisModel),
  42833. style: createTextStyle(textStyleModel, {
  42834. text: name,
  42835. font: textFont,
  42836. overflow: 'truncate',
  42837. width: maxWidth,
  42838. ellipsis: ellipsis,
  42839. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  42840. align: textStyleModel.get('align') || labelLayout.textAlign,
  42841. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  42842. }),
  42843. z2: 1
  42844. });
  42845. setTooltipConfig({
  42846. el: textEl,
  42847. componentModel: axisModel,
  42848. itemName: name
  42849. });
  42850. textEl.__fullText = name; // Id for animation
  42851. textEl.anid = 'name';
  42852. if (axisModel.get('triggerEvent')) {
  42853. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  42854. eventData.targetType = 'axisName';
  42855. eventData.name = name;
  42856. getECData(textEl).eventData = eventData;
  42857. } // FIXME
  42858. transformGroup.add(textEl);
  42859. textEl.updateTransform();
  42860. group.add(textEl);
  42861. textEl.decomposeTransform();
  42862. }
  42863. };
  42864. function endTextLayout(rotation, textPosition, textRotate, extent) {
  42865. var rotationDiff = remRadian(textRotate - rotation);
  42866. var textAlign;
  42867. var textVerticalAlign;
  42868. var inverse = extent[0] > extent[1];
  42869. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  42870. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  42871. textVerticalAlign = onLeft ? 'bottom' : 'top';
  42872. textAlign = 'center';
  42873. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  42874. textVerticalAlign = onLeft ? 'top' : 'bottom';
  42875. textAlign = 'center';
  42876. } else {
  42877. textVerticalAlign = 'middle';
  42878. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  42879. textAlign = onLeft ? 'left' : 'right';
  42880. } else {
  42881. textAlign = onLeft ? 'right' : 'left';
  42882. }
  42883. }
  42884. return {
  42885. rotation: rotationDiff,
  42886. textAlign: textAlign,
  42887. textVerticalAlign: textVerticalAlign
  42888. };
  42889. }
  42890. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  42891. if (shouldShowAllLabels(axisModel.axis)) {
  42892. return;
  42893. } // If min or max are user set, we need to check
  42894. // If the tick on min(max) are overlap on their neighbour tick
  42895. // If they are overlapped, we need to hide the min(max) tick label
  42896. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  42897. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  42898. // Have not consider onBand yet, where tick els is more than label els.
  42899. labelEls = labelEls || [];
  42900. tickEls = tickEls || [];
  42901. var firstLabel = labelEls[0];
  42902. var nextLabel = labelEls[1];
  42903. var lastLabel = labelEls[labelEls.length - 1];
  42904. var prevLabel = labelEls[labelEls.length - 2];
  42905. var firstTick = tickEls[0];
  42906. var nextTick = tickEls[1];
  42907. var lastTick = tickEls[tickEls.length - 1];
  42908. var prevTick = tickEls[tickEls.length - 2];
  42909. if (showMinLabel === false) {
  42910. ignoreEl(firstLabel);
  42911. ignoreEl(firstTick);
  42912. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  42913. if (showMinLabel) {
  42914. ignoreEl(nextLabel);
  42915. ignoreEl(nextTick);
  42916. } else {
  42917. ignoreEl(firstLabel);
  42918. ignoreEl(firstTick);
  42919. }
  42920. }
  42921. if (showMaxLabel === false) {
  42922. ignoreEl(lastLabel);
  42923. ignoreEl(lastTick);
  42924. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  42925. if (showMaxLabel) {
  42926. ignoreEl(prevLabel);
  42927. ignoreEl(prevTick);
  42928. } else {
  42929. ignoreEl(lastLabel);
  42930. ignoreEl(lastTick);
  42931. }
  42932. }
  42933. }
  42934. function ignoreEl(el) {
  42935. el && (el.ignore = true);
  42936. }
  42937. function isTwoLabelOverlapped(current, next) {
  42938. // current and next has the same rotation.
  42939. var firstRect = current && current.getBoundingRect().clone();
  42940. var nextRect = next && next.getBoundingRect().clone();
  42941. if (!firstRect || !nextRect) {
  42942. return;
  42943. } // When checking intersect of two rotated labels, we use mRotationBack
  42944. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  42945. var mRotationBack = identity([]);
  42946. rotate(mRotationBack, mRotationBack, -current.rotation);
  42947. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  42948. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  42949. return firstRect.intersect(nextRect);
  42950. }
  42951. function isNameLocationCenter(nameLocation) {
  42952. return nameLocation === 'middle' || nameLocation === 'center';
  42953. }
  42954. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  42955. var tickEls = [];
  42956. var pt1 = [];
  42957. var pt2 = [];
  42958. for (var i = 0; i < ticksCoords.length; i++) {
  42959. var tickCoord = ticksCoords[i].coord;
  42960. pt1[0] = tickCoord;
  42961. pt1[1] = 0;
  42962. pt2[0] = tickCoord;
  42963. pt2[1] = tickEndCoord;
  42964. if (tickTransform) {
  42965. applyTransform(pt1, pt1, tickTransform);
  42966. applyTransform(pt2, pt2, tickTransform);
  42967. } // Tick line, Not use group transform to have better line draw
  42968. var tickEl = new Line({
  42969. shape: {
  42970. x1: pt1[0],
  42971. y1: pt1[1],
  42972. x2: pt2[0],
  42973. y2: pt2[1]
  42974. },
  42975. style: tickLineStyle,
  42976. z2: 2,
  42977. autoBatch: true,
  42978. silent: true
  42979. });
  42980. subPixelOptimizeLine$1(tickEl.shape, tickEl.style.lineWidth);
  42981. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  42982. tickEls.push(tickEl);
  42983. }
  42984. return tickEls;
  42985. }
  42986. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  42987. var axis = axisModel.axis;
  42988. var tickModel = axisModel.getModel('axisTick');
  42989. var shown = tickModel.get('show');
  42990. if (shown === 'auto' && opt.handleAutoShown) {
  42991. shown = opt.handleAutoShown('axisTick');
  42992. }
  42993. if (!shown || axis.scale.isBlank()) {
  42994. return;
  42995. }
  42996. var lineStyleModel = tickModel.getModel('lineStyle');
  42997. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  42998. var ticksCoords = axis.getTicksCoords();
  42999. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  43000. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43001. }), 'ticks');
  43002. for (var i = 0; i < ticksEls.length; i++) {
  43003. group.add(ticksEls[i]);
  43004. }
  43005. return ticksEls;
  43006. }
  43007. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  43008. var axis = axisModel.axis;
  43009. var minorTickModel = axisModel.getModel('minorTick');
  43010. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  43011. return;
  43012. }
  43013. var minorTicksCoords = axis.getMinorTicksCoords();
  43014. if (!minorTicksCoords.length) {
  43015. return;
  43016. }
  43017. var lineStyleModel = minorTickModel.getModel('lineStyle');
  43018. var tickEndCoord = tickDirection * minorTickModel.get('length');
  43019. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  43020. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  43021. }));
  43022. for (var i = 0; i < minorTicksCoords.length; i++) {
  43023. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  43024. for (var k = 0; k < minorTicksEls.length; k++) {
  43025. group.add(minorTicksEls[k]);
  43026. }
  43027. }
  43028. }
  43029. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  43030. var axis = axisModel.axis;
  43031. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  43032. if (!show || axis.scale.isBlank()) {
  43033. return;
  43034. }
  43035. var labelModel = axisModel.getModel('axisLabel');
  43036. var labelMargin = labelModel.get('margin');
  43037. var labels = axis.getViewLabels(); // Special label rotate.
  43038. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  43039. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  43040. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  43041. var labelEls = [];
  43042. var silent = AxisBuilder.isLabelSilent(axisModel);
  43043. var triggerEvent = axisModel.get('triggerEvent');
  43044. each(labels, function (labelItem, index) {
  43045. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  43046. var formattedLabel = labelItem.formattedLabel;
  43047. var rawLabel = labelItem.rawLabel;
  43048. var itemLabelModel = labelModel;
  43049. if (rawCategoryData && rawCategoryData[tickValue]) {
  43050. var rawCategoryItem = rawCategoryData[tickValue];
  43051. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  43052. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  43053. }
  43054. }
  43055. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  43056. var tickCoord = axis.dataToCoord(tickValue);
  43057. var textEl = new ZRText({
  43058. x: tickCoord,
  43059. y: opt.labelOffset + opt.labelDirection * labelMargin,
  43060. rotation: labelLayout.rotation,
  43061. silent: silent,
  43062. z2: 10 + (labelItem.level || 0),
  43063. style: createTextStyle(itemLabelModel, {
  43064. text: formattedLabel,
  43065. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  43066. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  43067. fill: isFunction(textColor) ? textColor( // (1) In category axis with data zoom, tick is not the original
  43068. // index of axis.data. So tick should not be exposed to user
  43069. // in category axis.
  43070. // (2) Compatible with previous version, which always use formatted label as
  43071. // input. But in interval scale the formatted label is like '223,445', which
  43072. // maked user replace ','. So we modify it to return original val but remain
  43073. // it as 'string' to avoid error in replacing.
  43074. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  43075. })
  43076. });
  43077. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  43078. if (triggerEvent) {
  43079. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  43080. eventData.targetType = 'axisLabel';
  43081. eventData.value = rawLabel;
  43082. eventData.tickIndex = index;
  43083. if (axis.type === 'category') {
  43084. eventData.dataIndex = tickValue;
  43085. }
  43086. getECData(textEl).eventData = eventData;
  43087. } // FIXME
  43088. transformGroup.add(textEl);
  43089. textEl.updateTransform();
  43090. labelEls.push(textEl);
  43091. group.add(textEl);
  43092. textEl.decomposeTransform();
  43093. });
  43094. return labelEls;
  43095. }
  43096. // allAxesInfo should be updated when setOption performed.
  43097. function collect(ecModel, api) {
  43098. var result = {
  43099. /**
  43100. * key: makeKey(axis.model)
  43101. * value: {
  43102. * axis,
  43103. * coordSys,
  43104. * axisPointerModel,
  43105. * triggerTooltip,
  43106. * triggerEmphasis,
  43107. * involveSeries,
  43108. * snap,
  43109. * seriesModels,
  43110. * seriesDataCount
  43111. * }
  43112. */
  43113. axesInfo: {},
  43114. seriesInvolved: false,
  43115. /**
  43116. * key: makeKey(coordSys.model)
  43117. * value: Object: key makeKey(axis.model), value: axisInfo
  43118. */
  43119. coordSysAxesInfo: {},
  43120. coordSysMap: {}
  43121. };
  43122. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  43123. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  43124. return result;
  43125. }
  43126. function collectAxesInfo(result, ecModel, api) {
  43127. var globalTooltipModel = ecModel.getComponent('tooltip');
  43128. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  43129. var linksOption = globalAxisPointerModel.get('link', true) || [];
  43130. var linkGroups = []; // Collect axes info.
  43131. each(api.getCoordinateSystems(), function (coordSys) {
  43132. // Some coordinate system do not support axes, like geo.
  43133. if (!coordSys.axisPointerEnabled) {
  43134. return;
  43135. }
  43136. var coordSysKey = makeKey(coordSys.model);
  43137. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  43138. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convenient way to show axisPointer
  43139. // for user. So we enable setting tooltip on coordSys model.
  43140. var coordSysModel = coordSys.model;
  43141. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  43142. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  43143. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  43144. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  43145. // show but axisPointer will show as normal.
  43146. && baseTooltipModel.get('show')) {
  43147. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  43148. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  43149. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  43150. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  43151. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  43152. if (triggerAxis || cross) {
  43153. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  43154. }
  43155. if (cross) {
  43156. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  43157. }
  43158. } // fromTooltip: true | false | 'cross'
  43159. // triggerTooltip: true | false | null
  43160. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  43161. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  43162. var axisPointerShow = axisPointerModel.get('show');
  43163. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  43164. return;
  43165. }
  43166. if (triggerTooltip == null) {
  43167. triggerTooltip = axisPointerModel.get('triggerTooltip');
  43168. }
  43169. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  43170. var snap = axisPointerModel.get('snap');
  43171. var triggerEmphasis = axisPointerModel.get('triggerEmphasis');
  43172. var axisKey = makeKey(axis.model);
  43173. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  43174. var axisInfo = result.axesInfo[axisKey] = {
  43175. key: axisKey,
  43176. axis: axis,
  43177. coordSys: coordSys,
  43178. axisPointerModel: axisPointerModel,
  43179. triggerTooltip: triggerTooltip,
  43180. triggerEmphasis: triggerEmphasis,
  43181. involveSeries: involveSeries,
  43182. snap: snap,
  43183. useHandle: isHandleTrigger(axisPointerModel),
  43184. seriesModels: [],
  43185. linkGroup: null
  43186. };
  43187. axesInfoInCoordSys[axisKey] = axisInfo;
  43188. result.seriesInvolved = result.seriesInvolved || involveSeries;
  43189. var groupIndex = getLinkGroupIndex(linksOption, axis);
  43190. if (groupIndex != null) {
  43191. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  43192. axesInfo: {}
  43193. });
  43194. linkGroup.axesInfo[axisKey] = axisInfo;
  43195. linkGroup.mapper = linksOption[groupIndex].mapper;
  43196. axisInfo.linkGroup = linkGroup;
  43197. }
  43198. }
  43199. });
  43200. }
  43201. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  43202. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  43203. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  43204. var volatileOption = {};
  43205. each(fields, function (field) {
  43206. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  43207. }); // category axis do not auto snap, otherwise some tick that do not
  43208. // has value can not be hovered. value/time/log axis default snap if
  43209. // triggered from tooltip and trigger tooltip.
  43210. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatible with previous behavior, tooltip axis does not show label by default.
  43211. // Only these properties can be overridden from tooltip to axisPointer.
  43212. if (tooltipAxisPointerModel.get('type') === 'cross') {
  43213. volatileOption.type = 'line';
  43214. }
  43215. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  43216. labelOption.show == null && (labelOption.show = false);
  43217. if (fromTooltip === 'cross') {
  43218. // When 'cross', both axes show labels.
  43219. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  43220. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  43221. // (cross style is dashed by default)
  43222. if (!triggerTooltip) {
  43223. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  43224. crossStyle && defaults(labelOption, crossStyle.textStyle);
  43225. }
  43226. }
  43227. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  43228. }
  43229. function collectSeriesInfo(result, ecModel) {
  43230. // Prepare data for axis trigger
  43231. ecModel.eachSeries(function (seriesModel) {
  43232. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  43233. var coordSys = seriesModel.coordinateSystem;
  43234. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  43235. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  43236. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  43237. return;
  43238. }
  43239. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  43240. var axis = axisInfo.axis;
  43241. if (coordSys.getAxis(axis.dim) === axis) {
  43242. axisInfo.seriesModels.push(seriesModel);
  43243. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  43244. axisInfo.seriesDataCount += seriesModel.getData().count();
  43245. }
  43246. });
  43247. });
  43248. }
  43249. /**
  43250. * For example:
  43251. * {
  43252. * axisPointer: {
  43253. * links: [{
  43254. * xAxisIndex: [2, 4],
  43255. * yAxisIndex: 'all'
  43256. * }, {
  43257. * xAxisId: ['a5', 'a7'],
  43258. * xAxisName: 'xxx'
  43259. * }]
  43260. * }
  43261. * }
  43262. */
  43263. function getLinkGroupIndex(linksOption, axis) {
  43264. var axisModel = axis.model;
  43265. var dim = axis.dim;
  43266. for (var i = 0; i < linksOption.length; i++) {
  43267. var linkOption = linksOption[i] || {};
  43268. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  43269. return i;
  43270. }
  43271. }
  43272. }
  43273. function checkPropInLink(linkPropValue, axisPropValue) {
  43274. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  43275. }
  43276. function fixValue(axisModel) {
  43277. var axisInfo = getAxisInfo(axisModel);
  43278. if (!axisInfo) {
  43279. return;
  43280. }
  43281. var axisPointerModel = axisInfo.axisPointerModel;
  43282. var scale = axisInfo.axis.scale;
  43283. var option = axisPointerModel.option;
  43284. var status = axisPointerModel.get('status');
  43285. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  43286. if (value != null) {
  43287. value = scale.parse(value);
  43288. }
  43289. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  43290. // and status should be initialized.
  43291. if (status == null) {
  43292. option.status = useHandle ? 'show' : 'hide';
  43293. }
  43294. var extent = scale.getExtent().slice();
  43295. extent[0] > extent[1] && extent.reverse();
  43296. if ( // Pick a value on axis when initializing.
  43297. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  43298. // where we should re-pick a value to keep `handle` displaying normally.
  43299. || value > extent[1]) {
  43300. // Make handle displayed on the end of the axis when init, which looks better.
  43301. value = extent[1];
  43302. }
  43303. if (value < extent[0]) {
  43304. value = extent[0];
  43305. }
  43306. option.value = value;
  43307. if (useHandle) {
  43308. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  43309. }
  43310. }
  43311. function getAxisInfo(axisModel) {
  43312. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  43313. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  43314. }
  43315. function getAxisPointerModel(axisModel) {
  43316. var axisInfo = getAxisInfo(axisModel);
  43317. return axisInfo && axisInfo.axisPointerModel;
  43318. }
  43319. function isHandleTrigger(axisPointerModel) {
  43320. return !!axisPointerModel.get(['handle', 'show']);
  43321. }
  43322. /**
  43323. * @param {module:echarts/model/Model} model
  43324. * @return {string} unique key
  43325. */
  43326. function makeKey(model) {
  43327. return model.type + '||' + model.id;
  43328. }
  43329. var axisPointerClazz = {};
  43330. /**
  43331. * Base class of AxisView.
  43332. */
  43333. var AxisView =
  43334. /** @class */
  43335. function (_super) {
  43336. __extends(AxisView, _super);
  43337. function AxisView() {
  43338. var _this = _super !== null && _super.apply(this, arguments) || this;
  43339. _this.type = AxisView.type;
  43340. return _this;
  43341. }
  43342. /**
  43343. * @override
  43344. */
  43345. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43346. // FIXME
  43347. // This process should proformed after coordinate systems updated
  43348. // (axis scale updated), and should be performed each time update.
  43349. // So put it here temporarily, although it is not appropriate to
  43350. // put a model-writing procedure in `view`.
  43351. this.axisPointerClass && fixValue(axisModel);
  43352. _super.prototype.render.apply(this, arguments);
  43353. this._doUpdateAxisPointerClass(axisModel, api, true);
  43354. };
  43355. /**
  43356. * Action handler.
  43357. */
  43358. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  43359. this._doUpdateAxisPointerClass(axisModel, api, false);
  43360. };
  43361. /**
  43362. * @override
  43363. */
  43364. AxisView.prototype.remove = function (ecModel, api) {
  43365. var axisPointer = this._axisPointer;
  43366. axisPointer && axisPointer.remove(api);
  43367. };
  43368. /**
  43369. * @override
  43370. */
  43371. AxisView.prototype.dispose = function (ecModel, api) {
  43372. this._disposeAxisPointer(api);
  43373. _super.prototype.dispose.apply(this, arguments);
  43374. };
  43375. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  43376. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  43377. if (!Clazz) {
  43378. return;
  43379. }
  43380. var axisPointerModel = getAxisPointerModel(axisModel);
  43381. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  43382. };
  43383. AxisView.prototype._disposeAxisPointer = function (api) {
  43384. this._axisPointer && this._axisPointer.dispose(api);
  43385. this._axisPointer = null;
  43386. };
  43387. AxisView.registerAxisPointerClass = function (type, clazz) {
  43388. if ("development" !== 'production') {
  43389. if (axisPointerClazz[type]) {
  43390. throw new Error('axisPointer ' + type + ' exists');
  43391. }
  43392. }
  43393. axisPointerClazz[type] = clazz;
  43394. };
  43395. AxisView.getAxisPointerClass = function (type) {
  43396. return type && axisPointerClazz[type];
  43397. };
  43398. AxisView.type = 'axis';
  43399. return AxisView;
  43400. }(ComponentView);
  43401. var inner$6 = makeInner();
  43402. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  43403. var axis = axisModel.axis;
  43404. if (axis.scale.isBlank()) {
  43405. return;
  43406. } // TODO: TYPE
  43407. var splitAreaModel = axisModel.getModel('splitArea');
  43408. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  43409. var areaColors = areaStyleModel.get('color');
  43410. var gridRect = gridModel.coordinateSystem.getRect();
  43411. var ticksCoords = axis.getTicksCoords({
  43412. tickModel: splitAreaModel,
  43413. clamp: true
  43414. });
  43415. if (!ticksCoords.length) {
  43416. return;
  43417. } // For Making appropriate splitArea animation, the color and anid
  43418. // should be corresponding to previous one if possible.
  43419. var areaColorsLen = areaColors.length;
  43420. var lastSplitAreaColors = inner$6(axisView).splitAreaColors;
  43421. var newSplitAreaColors = createHashMap();
  43422. var colorIndex = 0;
  43423. if (lastSplitAreaColors) {
  43424. for (var i = 0; i < ticksCoords.length; i++) {
  43425. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  43426. if (cIndex != null) {
  43427. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  43428. break;
  43429. }
  43430. }
  43431. }
  43432. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  43433. var areaStyle = areaStyleModel.getAreaStyle();
  43434. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  43435. for (var i = 1; i < ticksCoords.length; i++) {
  43436. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43437. var x = void 0;
  43438. var y = void 0;
  43439. var width = void 0;
  43440. var height = void 0;
  43441. if (axis.isHorizontal()) {
  43442. x = prev;
  43443. y = gridRect.y;
  43444. width = tickCoord - x;
  43445. height = gridRect.height;
  43446. prev = x + width;
  43447. } else {
  43448. x = gridRect.x;
  43449. y = prev;
  43450. width = gridRect.width;
  43451. height = tickCoord - y;
  43452. prev = y + height;
  43453. }
  43454. var tickValue = ticksCoords[i - 1].tickValue;
  43455. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  43456. axisGroup.add(new Rect({
  43457. anid: tickValue != null ? 'area_' + tickValue : null,
  43458. shape: {
  43459. x: x,
  43460. y: y,
  43461. width: width,
  43462. height: height
  43463. },
  43464. style: defaults({
  43465. fill: areaColors[colorIndex]
  43466. }, areaStyle),
  43467. autoBatch: true,
  43468. silent: true
  43469. }));
  43470. colorIndex = (colorIndex + 1) % areaColorsLen;
  43471. }
  43472. inner$6(axisView).splitAreaColors = newSplitAreaColors;
  43473. }
  43474. function rectCoordAxisHandleRemove(axisView) {
  43475. inner$6(axisView).splitAreaColors = null;
  43476. }
  43477. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  43478. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  43479. var CartesianAxisView =
  43480. /** @class */
  43481. function (_super) {
  43482. __extends(CartesianAxisView, _super);
  43483. function CartesianAxisView() {
  43484. var _this = _super !== null && _super.apply(this, arguments) || this;
  43485. _this.type = CartesianAxisView.type;
  43486. _this.axisPointerClass = 'CartesianAxisPointer';
  43487. return _this;
  43488. }
  43489. /**
  43490. * @override
  43491. */
  43492. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  43493. this.group.removeAll();
  43494. var oldAxisGroup = this._axisGroup;
  43495. this._axisGroup = new Group();
  43496. this.group.add(this._axisGroup);
  43497. if (!axisModel.get('show')) {
  43498. return;
  43499. }
  43500. var gridModel = axisModel.getCoordSysModel();
  43501. var layout = layout$1(gridModel, axisModel);
  43502. var axisBuilder = new AxisBuilder(axisModel, extend({
  43503. handleAutoShown: function (elementType) {
  43504. var cartesians = gridModel.coordinateSystem.getCartesians();
  43505. for (var i = 0; i < cartesians.length; i++) {
  43506. if (isIntervalOrLogScale(cartesians[i].getOtherAxis(axisModel.axis).scale)) {
  43507. // Still show axis tick or axisLine if other axis is value / log
  43508. return true;
  43509. }
  43510. } // Not show axisTick or axisLine if other axis is category / time
  43511. return false;
  43512. }
  43513. }, layout));
  43514. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  43515. this._axisGroup.add(axisBuilder.getGroup());
  43516. each(selfBuilderAttrs, function (name) {
  43517. if (axisModel.get([name, 'show'])) {
  43518. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  43519. }
  43520. }, this); // THIS is a special case for bar racing chart.
  43521. // Update the axis label from the natural initial layout to
  43522. // sorted layout should has no animation.
  43523. var isInitialSortFromBarRacing = payload && payload.type === 'changeAxisOrder' && payload.isInitSort;
  43524. if (!isInitialSortFromBarRacing) {
  43525. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  43526. }
  43527. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  43528. };
  43529. CartesianAxisView.prototype.remove = function () {
  43530. rectCoordAxisHandleRemove(this);
  43531. };
  43532. CartesianAxisView.type = 'cartesianAxis';
  43533. return CartesianAxisView;
  43534. }(AxisView);
  43535. var axisElementBuilders = {
  43536. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43537. var axis = axisModel.axis;
  43538. if (axis.scale.isBlank()) {
  43539. return;
  43540. }
  43541. var splitLineModel = axisModel.getModel('splitLine');
  43542. var lineStyleModel = splitLineModel.getModel('lineStyle');
  43543. var lineColors = lineStyleModel.get('color');
  43544. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  43545. var gridRect = gridModel.coordinateSystem.getRect();
  43546. var isHorizontal = axis.isHorizontal();
  43547. var lineCount = 0;
  43548. var ticksCoords = axis.getTicksCoords({
  43549. tickModel: splitLineModel
  43550. });
  43551. var p1 = [];
  43552. var p2 = [];
  43553. var lineStyle = lineStyleModel.getLineStyle();
  43554. for (var i = 0; i < ticksCoords.length; i++) {
  43555. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  43556. if (isHorizontal) {
  43557. p1[0] = tickCoord;
  43558. p1[1] = gridRect.y;
  43559. p2[0] = tickCoord;
  43560. p2[1] = gridRect.y + gridRect.height;
  43561. } else {
  43562. p1[0] = gridRect.x;
  43563. p1[1] = tickCoord;
  43564. p2[0] = gridRect.x + gridRect.width;
  43565. p2[1] = tickCoord;
  43566. }
  43567. var colorIndex = lineCount++ % lineColors.length;
  43568. var tickValue = ticksCoords[i].tickValue;
  43569. var line = new Line({
  43570. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  43571. autoBatch: true,
  43572. shape: {
  43573. x1: p1[0],
  43574. y1: p1[1],
  43575. x2: p2[0],
  43576. y2: p2[1]
  43577. },
  43578. style: defaults({
  43579. stroke: lineColors[colorIndex]
  43580. }, lineStyle),
  43581. silent: true
  43582. });
  43583. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43584. axisGroup.add(line);
  43585. }
  43586. },
  43587. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  43588. var axis = axisModel.axis;
  43589. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  43590. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  43591. var gridRect = gridModel.coordinateSystem.getRect();
  43592. var isHorizontal = axis.isHorizontal();
  43593. var minorTicksCoords = axis.getMinorTicksCoords();
  43594. if (!minorTicksCoords.length) {
  43595. return;
  43596. }
  43597. var p1 = [];
  43598. var p2 = [];
  43599. var lineStyle = lineStyleModel.getLineStyle();
  43600. for (var i = 0; i < minorTicksCoords.length; i++) {
  43601. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  43602. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  43603. if (isHorizontal) {
  43604. p1[0] = tickCoord;
  43605. p1[1] = gridRect.y;
  43606. p2[0] = tickCoord;
  43607. p2[1] = gridRect.y + gridRect.height;
  43608. } else {
  43609. p1[0] = gridRect.x;
  43610. p1[1] = tickCoord;
  43611. p2[0] = gridRect.x + gridRect.width;
  43612. p2[1] = tickCoord;
  43613. }
  43614. var line = new Line({
  43615. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  43616. autoBatch: true,
  43617. shape: {
  43618. x1: p1[0],
  43619. y1: p1[1],
  43620. x2: p2[0],
  43621. y2: p2[1]
  43622. },
  43623. style: lineStyle,
  43624. silent: true
  43625. });
  43626. subPixelOptimizeLine$1(line.shape, lineStyle.lineWidth);
  43627. axisGroup.add(line);
  43628. }
  43629. }
  43630. },
  43631. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  43632. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  43633. }
  43634. };
  43635. var CartesianXAxisView =
  43636. /** @class */
  43637. function (_super) {
  43638. __extends(CartesianXAxisView, _super);
  43639. function CartesianXAxisView() {
  43640. var _this = _super !== null && _super.apply(this, arguments) || this;
  43641. _this.type = CartesianXAxisView.type;
  43642. return _this;
  43643. }
  43644. CartesianXAxisView.type = 'xAxis';
  43645. return CartesianXAxisView;
  43646. }(CartesianAxisView);
  43647. var CartesianYAxisView =
  43648. /** @class */
  43649. function (_super) {
  43650. __extends(CartesianYAxisView, _super);
  43651. function CartesianYAxisView() {
  43652. var _this = _super !== null && _super.apply(this, arguments) || this;
  43653. _this.type = CartesianXAxisView.type;
  43654. return _this;
  43655. }
  43656. CartesianYAxisView.type = 'yAxis';
  43657. return CartesianYAxisView;
  43658. }(CartesianAxisView);
  43659. var GridView =
  43660. /** @class */
  43661. function (_super) {
  43662. __extends(GridView, _super);
  43663. function GridView() {
  43664. var _this = _super !== null && _super.apply(this, arguments) || this;
  43665. _this.type = 'grid';
  43666. return _this;
  43667. }
  43668. GridView.prototype.render = function (gridModel, ecModel) {
  43669. this.group.removeAll();
  43670. if (gridModel.get('show')) {
  43671. this.group.add(new Rect({
  43672. shape: gridModel.coordinateSystem.getRect(),
  43673. style: defaults({
  43674. fill: gridModel.get('backgroundColor')
  43675. }, gridModel.getItemStyle()),
  43676. silent: true,
  43677. z2: -1
  43678. }));
  43679. }
  43680. };
  43681. GridView.type = 'grid';
  43682. return GridView;
  43683. }(ComponentView);
  43684. var extraOption = {
  43685. // gridIndex: 0,
  43686. // gridId: '',
  43687. offset: 0
  43688. };
  43689. function install$5(registers) {
  43690. registers.registerComponentView(GridView);
  43691. registers.registerComponentModel(GridModel);
  43692. registers.registerCoordinateSystem('cartesian2d', Grid);
  43693. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  43694. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  43695. registers.registerComponentView(CartesianXAxisView);
  43696. registers.registerComponentView(CartesianYAxisView);
  43697. registers.registerPreprocessor(function (option) {
  43698. // Only create grid when need
  43699. if (option.xAxis && option.yAxis && !option.grid) {
  43700. option.grid = {};
  43701. }
  43702. });
  43703. }
  43704. function install$6(registers) {
  43705. // In case developer forget to include grid component
  43706. use(install$5);
  43707. registers.registerSeriesModel(ScatterSeriesModel);
  43708. registers.registerChartView(ScatterView);
  43709. registers.registerLayout(pointsLayout('scatter'));
  43710. }
  43711. function radarLayout(ecModel) {
  43712. ecModel.eachSeriesByType('radar', function (seriesModel) {
  43713. var data = seriesModel.getData();
  43714. var points = [];
  43715. var coordSys = seriesModel.coordinateSystem;
  43716. if (!coordSys) {
  43717. return;
  43718. }
  43719. var axes = coordSys.getIndicatorAxes();
  43720. each(axes, function (axis, axisIndex) {
  43721. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  43722. points[dataIndex] = points[dataIndex] || [];
  43723. var point = coordSys.dataToPoint(val, axisIndex);
  43724. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  43725. });
  43726. }); // Close polygon
  43727. data.each(function (idx) {
  43728. // TODO
  43729. // Is it appropriate to connect to the next data when some data is missing?
  43730. // Or, should trade it like `connectNull` in line chart?
  43731. var firstPoint = find(points[idx], function (point) {
  43732. return isValidPoint(point);
  43733. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  43734. points[idx].push(firstPoint.slice());
  43735. data.setItemLayout(idx, points[idx]);
  43736. });
  43737. });
  43738. }
  43739. function isValidPoint(point) {
  43740. return !isNaN(point[0]) && !isNaN(point[1]);
  43741. }
  43742. function getValueMissingPoint(coordSys) {
  43743. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  43744. // (probably cause problem when refreshing or animating)
  43745. return [coordSys.cx, coordSys.cy];
  43746. }
  43747. function radarBackwardCompat(option) {
  43748. var polarOptArr = option.polar;
  43749. if (polarOptArr) {
  43750. if (!isArray(polarOptArr)) {
  43751. polarOptArr = [polarOptArr];
  43752. }
  43753. var polarNotRadar_1 = [];
  43754. each(polarOptArr, function (polarOpt, idx) {
  43755. if (polarOpt.indicator) {
  43756. if (polarOpt.type && !polarOpt.shape) {
  43757. polarOpt.shape = polarOpt.type;
  43758. }
  43759. option.radar = option.radar || [];
  43760. if (!isArray(option.radar)) {
  43761. option.radar = [option.radar];
  43762. }
  43763. option.radar.push(polarOpt);
  43764. } else {
  43765. polarNotRadar_1.push(polarOpt);
  43766. }
  43767. });
  43768. option.polar = polarNotRadar_1;
  43769. }
  43770. each(option.series, function (seriesOpt) {
  43771. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  43772. seriesOpt.radarIndex = seriesOpt.polarIndex;
  43773. }
  43774. });
  43775. }
  43776. var RadarView =
  43777. /** @class */
  43778. function (_super) {
  43779. __extends(RadarView, _super);
  43780. function RadarView() {
  43781. var _this = _super !== null && _super.apply(this, arguments) || this;
  43782. _this.type = RadarView.type;
  43783. return _this;
  43784. }
  43785. RadarView.prototype.render = function (seriesModel, ecModel, api) {
  43786. var polar = seriesModel.coordinateSystem;
  43787. var group = this.group;
  43788. var data = seriesModel.getData();
  43789. var oldData = this._data;
  43790. function createSymbol$1(data, idx) {
  43791. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  43792. if (symbolType === 'none') {
  43793. return;
  43794. }
  43795. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  43796. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2);
  43797. var symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0;
  43798. symbolPath.attr({
  43799. style: {
  43800. strokeNoScale: true
  43801. },
  43802. z2: 100,
  43803. scaleX: symbolSize[0] / 2,
  43804. scaleY: symbolSize[1] / 2,
  43805. rotation: symbolRotate * Math.PI / 180 || 0
  43806. });
  43807. return symbolPath;
  43808. }
  43809. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  43810. // Simply rerender all
  43811. symbolGroup.removeAll();
  43812. for (var i = 0; i < newPoints.length - 1; i++) {
  43813. var symbolPath = createSymbol$1(data, idx);
  43814. if (symbolPath) {
  43815. symbolPath.__dimIdx = i;
  43816. if (oldPoints[i]) {
  43817. symbolPath.setPosition(oldPoints[i]);
  43818. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  43819. x: newPoints[i][0],
  43820. y: newPoints[i][1]
  43821. }, seriesModel, idx);
  43822. } else {
  43823. symbolPath.setPosition(newPoints[i]);
  43824. }
  43825. symbolGroup.add(symbolPath);
  43826. }
  43827. }
  43828. }
  43829. function getInitialPoints(points) {
  43830. return map(points, function (pt) {
  43831. return [polar.cx, polar.cy];
  43832. });
  43833. }
  43834. data.diff(oldData).add(function (idx) {
  43835. var points = data.getItemLayout(idx);
  43836. if (!points) {
  43837. return;
  43838. }
  43839. var polygon = new Polygon();
  43840. var polyline = new Polyline();
  43841. var target = {
  43842. shape: {
  43843. points: points
  43844. }
  43845. };
  43846. polygon.shape.points = getInitialPoints(points);
  43847. polyline.shape.points = getInitialPoints(points);
  43848. initProps(polygon, target, seriesModel, idx);
  43849. initProps(polyline, target, seriesModel, idx);
  43850. var itemGroup = new Group();
  43851. var symbolGroup = new Group();
  43852. itemGroup.add(polyline);
  43853. itemGroup.add(polygon);
  43854. itemGroup.add(symbolGroup);
  43855. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  43856. data.setItemGraphicEl(idx, itemGroup);
  43857. }).update(function (newIdx, oldIdx) {
  43858. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  43859. var polyline = itemGroup.childAt(0);
  43860. var polygon = itemGroup.childAt(1);
  43861. var symbolGroup = itemGroup.childAt(2);
  43862. var target = {
  43863. shape: {
  43864. points: data.getItemLayout(newIdx)
  43865. }
  43866. };
  43867. if (!target.shape.points) {
  43868. return;
  43869. }
  43870. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  43871. saveOldStyle(polygon);
  43872. saveOldStyle(polyline);
  43873. updateProps(polyline, target, seriesModel);
  43874. updateProps(polygon, target, seriesModel);
  43875. data.setItemGraphicEl(newIdx, itemGroup);
  43876. }).remove(function (idx) {
  43877. group.remove(oldData.getItemGraphicEl(idx));
  43878. }).execute();
  43879. data.eachItemGraphicEl(function (itemGroup, idx) {
  43880. var itemModel = data.getItemModel(idx);
  43881. var polyline = itemGroup.childAt(0);
  43882. var polygon = itemGroup.childAt(1);
  43883. var symbolGroup = itemGroup.childAt(2); // Radar uses the visual encoded from itemStyle.
  43884. var itemStyle = data.getItemVisual(idx, 'style');
  43885. var color = itemStyle.fill;
  43886. group.add(itemGroup);
  43887. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  43888. fill: 'none',
  43889. stroke: color
  43890. }));
  43891. setStatesStylesFromModel(polyline, itemModel, 'lineStyle');
  43892. setStatesStylesFromModel(polygon, itemModel, 'areaStyle');
  43893. var areaStyleModel = itemModel.getModel('areaStyle');
  43894. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  43895. polygon.ignore = polygonIgnore;
  43896. each(['emphasis', 'select', 'blur'], function (stateName) {
  43897. var stateModel = itemModel.getModel([stateName, 'areaStyle']);
  43898. var stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); // Won't be ignore if normal state is not ignore.
  43899. polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore;
  43900. });
  43901. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  43902. fill: color,
  43903. opacity: 0.7,
  43904. decal: itemStyle.decal
  43905. }));
  43906. var emphasisModel = itemModel.getModel('emphasis');
  43907. var itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  43908. symbolGroup.eachChild(function (symbolPath) {
  43909. if (symbolPath instanceof ZRImage) {
  43910. var pathStyle = symbolPath.style;
  43911. symbolPath.useStyle(extend({
  43912. // TODO other properties like x, y ?
  43913. image: pathStyle.image,
  43914. x: pathStyle.x,
  43915. y: pathStyle.y,
  43916. width: pathStyle.width,
  43917. height: pathStyle.height
  43918. }, itemStyle));
  43919. } else {
  43920. symbolPath.useStyle(itemStyle);
  43921. symbolPath.setColor(color);
  43922. symbolPath.style.strokeNoScale = true;
  43923. }
  43924. var pathEmphasisState = symbolPath.ensureState('emphasis');
  43925. pathEmphasisState.style = clone(itemHoverStyle);
  43926. var defaultText = data.getStore().get(data.getDimensionIndex(symbolPath.__dimIdx), idx);
  43927. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  43928. setLabelStyle(symbolPath, getLabelStatesModels(itemModel), {
  43929. labelFetcher: data.hostModel,
  43930. labelDataIndex: idx,
  43931. labelDimIndex: symbolPath.__dimIdx,
  43932. defaultText: defaultText,
  43933. inheritColor: color,
  43934. defaultOpacity: itemStyle.opacity
  43935. });
  43936. });
  43937. toggleHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  43938. });
  43939. this._data = data;
  43940. };
  43941. RadarView.prototype.remove = function () {
  43942. this.group.removeAll();
  43943. this._data = null;
  43944. };
  43945. RadarView.type = 'radar';
  43946. return RadarView;
  43947. }(ChartView);
  43948. var RadarSeriesModel =
  43949. /** @class */
  43950. function (_super) {
  43951. __extends(RadarSeriesModel, _super);
  43952. function RadarSeriesModel() {
  43953. var _this = _super !== null && _super.apply(this, arguments) || this;
  43954. _this.type = RadarSeriesModel.type;
  43955. _this.hasSymbolVisual = true;
  43956. return _this;
  43957. } // Overwrite
  43958. RadarSeriesModel.prototype.init = function (option) {
  43959. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  43960. // Use a function instead of direct access because data reference may changed
  43961. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  43962. };
  43963. RadarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  43964. return createSeriesDataSimply(this, {
  43965. generateCoord: 'indicator_',
  43966. generateCoordCount: Infinity
  43967. });
  43968. };
  43969. RadarSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  43970. var data = this.getData();
  43971. var coordSys = this.coordinateSystem;
  43972. var indicatorAxes = coordSys.getIndicatorAxes();
  43973. var name = this.getData().getName(dataIndex);
  43974. var nameToDisplay = name === '' ? this.name : name;
  43975. var markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex);
  43976. return createTooltipMarkup('section', {
  43977. header: nameToDisplay,
  43978. sortBlocks: true,
  43979. blocks: map(indicatorAxes, function (axis) {
  43980. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  43981. return createTooltipMarkup('nameValue', {
  43982. markerType: 'subItem',
  43983. markerColor: markerColor,
  43984. name: axis.name,
  43985. value: val,
  43986. sortParam: val
  43987. });
  43988. })
  43989. });
  43990. };
  43991. RadarSeriesModel.prototype.getTooltipPosition = function (dataIndex) {
  43992. if (dataIndex != null) {
  43993. var data_1 = this.getData();
  43994. var coordSys = this.coordinateSystem;
  43995. var values = data_1.getValues(map(coordSys.dimensions, function (dim) {
  43996. return data_1.mapDimension(dim);
  43997. }), dataIndex);
  43998. for (var i = 0, len = values.length; i < len; i++) {
  43999. if (!isNaN(values[i])) {
  44000. var indicatorAxes = coordSys.getIndicatorAxes();
  44001. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  44002. }
  44003. }
  44004. }
  44005. };
  44006. RadarSeriesModel.type = 'series.radar';
  44007. RadarSeriesModel.dependencies = ['radar'];
  44008. RadarSeriesModel.defaultOption = {
  44009. // zlevel: 0,
  44010. z: 2,
  44011. colorBy: 'data',
  44012. coordinateSystem: 'radar',
  44013. legendHoverLink: true,
  44014. radarIndex: 0,
  44015. lineStyle: {
  44016. width: 2,
  44017. type: 'solid',
  44018. join: 'round'
  44019. },
  44020. label: {
  44021. position: 'top'
  44022. },
  44023. // areaStyle: {
  44024. // },
  44025. // itemStyle: {}
  44026. symbolSize: 8 // symbolRotate: null
  44027. };
  44028. return RadarSeriesModel;
  44029. }(SeriesModel);
  44030. var valueAxisDefault = axisDefault.value;
  44031. function defaultsShow(opt, show) {
  44032. return defaults({
  44033. show: show
  44034. }, opt);
  44035. }
  44036. var RadarModel =
  44037. /** @class */
  44038. function (_super) {
  44039. __extends(RadarModel, _super);
  44040. function RadarModel() {
  44041. var _this = _super !== null && _super.apply(this, arguments) || this;
  44042. _this.type = RadarModel.type;
  44043. return _this;
  44044. }
  44045. RadarModel.prototype.optionUpdated = function () {
  44046. var boundaryGap = this.get('boundaryGap');
  44047. var splitNumber = this.get('splitNumber');
  44048. var scale = this.get('scale');
  44049. var axisLine = this.get('axisLine');
  44050. var axisTick = this.get('axisTick'); // let axisType = this.get('axisType');
  44051. var axisLabel = this.get('axisLabel');
  44052. var nameTextStyle = this.get('axisName');
  44053. var showName = this.get(['axisName', 'show']);
  44054. var nameFormatter = this.get(['axisName', 'formatter']);
  44055. var nameGap = this.get('axisNameGap');
  44056. var triggerEvent = this.get('triggerEvent');
  44057. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  44058. // PENDING
  44059. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  44060. indicatorOpt.min = 0;
  44061. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  44062. indicatorOpt.max = 0;
  44063. }
  44064. var iNameTextStyle = nameTextStyle;
  44065. if (indicatorOpt.color != null) {
  44066. iNameTextStyle = defaults({
  44067. color: indicatorOpt.color
  44068. }, nameTextStyle);
  44069. } // Use same configuration
  44070. var innerIndicatorOpt = merge(clone(indicatorOpt), {
  44071. boundaryGap: boundaryGap,
  44072. splitNumber: splitNumber,
  44073. scale: scale,
  44074. axisLine: axisLine,
  44075. axisTick: axisTick,
  44076. // axisType: axisType,
  44077. axisLabel: axisLabel,
  44078. // Compatible with 2 and use text
  44079. name: indicatorOpt.text,
  44080. showName: showName,
  44081. nameLocation: 'end',
  44082. nameGap: nameGap,
  44083. // min: 0,
  44084. nameTextStyle: iNameTextStyle,
  44085. triggerEvent: triggerEvent
  44086. }, false);
  44087. if (isString(nameFormatter)) {
  44088. var indName = innerIndicatorOpt.name;
  44089. innerIndicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  44090. } else if (isFunction(nameFormatter)) {
  44091. innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt);
  44092. }
  44093. var model = new Model(innerIndicatorOpt, null, this.ecModel);
  44094. mixin(model, AxisModelCommonMixin.prototype); // For triggerEvent.
  44095. model.mainType = 'radar';
  44096. model.componentIndex = this.componentIndex;
  44097. return model;
  44098. }, this);
  44099. this._indicatorModels = indicatorModels;
  44100. };
  44101. RadarModel.prototype.getIndicatorModels = function () {
  44102. return this._indicatorModels;
  44103. };
  44104. RadarModel.type = 'radar';
  44105. RadarModel.defaultOption = {
  44106. // zlevel: 0,
  44107. z: 0,
  44108. center: ['50%', '50%'],
  44109. radius: '75%',
  44110. startAngle: 90,
  44111. axisName: {
  44112. show: true // formatter: null
  44113. // textStyle: {}
  44114. },
  44115. boundaryGap: [0, 0],
  44116. splitNumber: 5,
  44117. axisNameGap: 15,
  44118. scale: false,
  44119. // Polygon or circle
  44120. shape: 'polygon',
  44121. axisLine: merge({
  44122. lineStyle: {
  44123. color: '#bbb'
  44124. }
  44125. }, valueAxisDefault.axisLine),
  44126. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  44127. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  44128. // axisType: 'value',
  44129. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  44130. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  44131. // {text, min, max}
  44132. indicator: []
  44133. };
  44134. return RadarModel;
  44135. }(ComponentModel);
  44136. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  44137. var RadarView$1 =
  44138. /** @class */
  44139. function (_super) {
  44140. __extends(RadarView, _super);
  44141. function RadarView() {
  44142. var _this = _super !== null && _super.apply(this, arguments) || this;
  44143. _this.type = RadarView.type;
  44144. return _this;
  44145. }
  44146. RadarView.prototype.render = function (radarModel, ecModel, api) {
  44147. var group = this.group;
  44148. group.removeAll();
  44149. this._buildAxes(radarModel);
  44150. this._buildSplitLineAndArea(radarModel);
  44151. };
  44152. RadarView.prototype._buildAxes = function (radarModel) {
  44153. var radar = radarModel.coordinateSystem;
  44154. var indicatorAxes = radar.getIndicatorAxes();
  44155. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  44156. var axisName = indicatorAxis.model.get('showName') ? indicatorAxis.name : ''; // hide name
  44157. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  44158. axisName: axisName,
  44159. position: [radar.cx, radar.cy],
  44160. rotation: indicatorAxis.angle,
  44161. labelDirection: -1,
  44162. tickDirection: -1,
  44163. nameDirection: 1
  44164. });
  44165. return axisBuilder;
  44166. });
  44167. each(axisBuilders, function (axisBuilder) {
  44168. each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  44169. this.group.add(axisBuilder.getGroup());
  44170. }, this);
  44171. };
  44172. RadarView.prototype._buildSplitLineAndArea = function (radarModel) {
  44173. var radar = radarModel.coordinateSystem;
  44174. var indicatorAxes = radar.getIndicatorAxes();
  44175. if (!indicatorAxes.length) {
  44176. return;
  44177. }
  44178. var shape = radarModel.get('shape');
  44179. var splitLineModel = radarModel.getModel('splitLine');
  44180. var splitAreaModel = radarModel.getModel('splitArea');
  44181. var lineStyleModel = splitLineModel.getModel('lineStyle');
  44182. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  44183. var showSplitLine = splitLineModel.get('show');
  44184. var showSplitArea = splitAreaModel.get('show');
  44185. var splitLineColors = lineStyleModel.get('color');
  44186. var splitAreaColors = areaStyleModel.get('color');
  44187. var splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  44188. var splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  44189. var splitLines = [];
  44190. var splitAreas = [];
  44191. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  44192. var colorIndex = idx % areaOrLineColorList.length;
  44193. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  44194. return colorIndex;
  44195. }
  44196. if (shape === 'circle') {
  44197. var ticksRadius = indicatorAxes[0].getTicksCoords();
  44198. var cx = radar.cx;
  44199. var cy = radar.cy;
  44200. for (var i = 0; i < ticksRadius.length; i++) {
  44201. if (showSplitLine) {
  44202. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44203. splitLines[colorIndex].push(new Circle({
  44204. shape: {
  44205. cx: cx,
  44206. cy: cy,
  44207. r: ticksRadius[i].coord
  44208. }
  44209. }));
  44210. }
  44211. if (showSplitArea && i < ticksRadius.length - 1) {
  44212. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i);
  44213. splitAreas[colorIndex].push(new Ring({
  44214. shape: {
  44215. cx: cx,
  44216. cy: cy,
  44217. r0: ticksRadius[i].coord,
  44218. r: ticksRadius[i + 1].coord
  44219. }
  44220. }));
  44221. }
  44222. }
  44223. } // Polyyon
  44224. else {
  44225. var realSplitNumber_1;
  44226. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  44227. var ticksCoords = indicatorAxis.getTicksCoords();
  44228. realSplitNumber_1 = realSplitNumber_1 == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1);
  44229. return map(ticksCoords, function (tickCoord) {
  44230. return radar.coordToPoint(tickCoord.coord, idx);
  44231. });
  44232. });
  44233. var prevPoints = [];
  44234. for (var i = 0; i <= realSplitNumber_1; i++) {
  44235. var points = [];
  44236. for (var j = 0; j < indicatorAxes.length; j++) {
  44237. points.push(axesTicksPoints[j][i]);
  44238. } // Close
  44239. if (points[0]) {
  44240. points.push(points[0].slice());
  44241. } else {
  44242. if ("development" !== 'production') {
  44243. console.error('Can\'t draw value axis ' + i);
  44244. }
  44245. }
  44246. if (showSplitLine) {
  44247. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  44248. splitLines[colorIndex].push(new Polyline({
  44249. shape: {
  44250. points: points
  44251. }
  44252. }));
  44253. }
  44254. if (showSplitArea && prevPoints) {
  44255. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1);
  44256. splitAreas[colorIndex].push(new Polygon({
  44257. shape: {
  44258. points: points.concat(prevPoints)
  44259. }
  44260. }));
  44261. }
  44262. prevPoints = points.slice().reverse();
  44263. }
  44264. }
  44265. var lineStyle = lineStyleModel.getLineStyle();
  44266. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  44267. each(splitAreas, function (splitAreas, idx) {
  44268. this.group.add(mergePath$1(splitAreas, {
  44269. style: defaults({
  44270. stroke: 'none',
  44271. fill: splitAreaColorsArr[idx % splitAreaColorsArr.length]
  44272. }, areaStyle),
  44273. silent: true
  44274. }));
  44275. }, this);
  44276. each(splitLines, function (splitLines, idx) {
  44277. this.group.add(mergePath$1(splitLines, {
  44278. style: defaults({
  44279. fill: 'none',
  44280. stroke: splitLineColorsArr[idx % splitLineColorsArr.length]
  44281. }, lineStyle),
  44282. silent: true
  44283. }));
  44284. }, this);
  44285. };
  44286. RadarView.type = 'radar';
  44287. return RadarView;
  44288. }(ComponentView);
  44289. var IndicatorAxis =
  44290. /** @class */
  44291. function (_super) {
  44292. __extends(IndicatorAxis, _super);
  44293. function IndicatorAxis(dim, scale, radiusExtent) {
  44294. var _this = _super.call(this, dim, scale, radiusExtent) || this;
  44295. _this.type = 'value';
  44296. _this.angle = 0;
  44297. _this.name = '';
  44298. return _this;
  44299. }
  44300. return IndicatorAxis;
  44301. }(Axis);
  44302. var Radar =
  44303. /** @class */
  44304. function () {
  44305. function Radar(radarModel, ecModel, api) {
  44306. /**
  44307. *
  44308. * Radar dimensions
  44309. */
  44310. this.dimensions = [];
  44311. this._model = radarModel;
  44312. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  44313. var dim = 'indicator_' + idx;
  44314. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale() // (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale()
  44315. );
  44316. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  44317. indicatorAxis.model = indicatorModel;
  44318. indicatorModel.axis = indicatorAxis;
  44319. this.dimensions.push(dim);
  44320. return indicatorAxis;
  44321. }, this);
  44322. this.resize(radarModel, api);
  44323. }
  44324. Radar.prototype.getIndicatorAxes = function () {
  44325. return this._indicatorAxes;
  44326. };
  44327. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  44328. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44329. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  44330. }; // TODO: API should be coordToPoint([coord, indicatorIndex])
  44331. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  44332. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  44333. var angle = indicatorAxis.angle;
  44334. var x = this.cx + coord * Math.cos(angle);
  44335. var y = this.cy - coord * Math.sin(angle);
  44336. return [x, y];
  44337. };
  44338. Radar.prototype.pointToData = function (pt) {
  44339. var dx = pt[0] - this.cx;
  44340. var dy = pt[1] - this.cy;
  44341. var radius = Math.sqrt(dx * dx + dy * dy);
  44342. dx /= radius;
  44343. dy /= radius;
  44344. var radian = Math.atan2(-dy, dx); // Find the closest angle
  44345. // FIXME index can calculated directly
  44346. var minRadianDiff = Infinity;
  44347. var closestAxis;
  44348. var closestAxisIdx = -1;
  44349. for (var i = 0; i < this._indicatorAxes.length; i++) {
  44350. var indicatorAxis = this._indicatorAxes[i];
  44351. var diff = Math.abs(radian - indicatorAxis.angle);
  44352. if (diff < minRadianDiff) {
  44353. closestAxis = indicatorAxis;
  44354. closestAxisIdx = i;
  44355. minRadianDiff = diff;
  44356. }
  44357. }
  44358. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  44359. };
  44360. Radar.prototype.resize = function (radarModel, api) {
  44361. var center = radarModel.get('center');
  44362. var viewWidth = api.getWidth();
  44363. var viewHeight = api.getHeight();
  44364. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  44365. this.cx = parsePercent$1(center[0], viewWidth);
  44366. this.cy = parsePercent$1(center[1], viewHeight);
  44367. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  44368. var radius = radarModel.get('radius');
  44369. if (isString(radius) || isNumber(radius)) {
  44370. radius = [0, radius];
  44371. }
  44372. this.r0 = parsePercent$1(radius[0], viewSize);
  44373. this.r = parsePercent$1(radius[1], viewSize);
  44374. each(this._indicatorAxes, function (indicatorAxis, idx) {
  44375. indicatorAxis.setExtent(this.r0, this.r);
  44376. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  44377. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  44378. indicatorAxis.angle = angle;
  44379. }, this);
  44380. };
  44381. Radar.prototype.update = function (ecModel, api) {
  44382. var indicatorAxes = this._indicatorAxes;
  44383. var radarModel = this._model;
  44384. each(indicatorAxes, function (indicatorAxis) {
  44385. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  44386. });
  44387. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  44388. if (radarSeries.get('coordinateSystem') !== 'radar' // @ts-ignore
  44389. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  44390. return;
  44391. }
  44392. var data = radarSeries.getData();
  44393. each(indicatorAxes, function (indicatorAxis) {
  44394. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  44395. });
  44396. }, this);
  44397. var splitNumber = radarModel.get('splitNumber');
  44398. var dummyScale = new IntervalScale();
  44399. dummyScale.setExtent(0, splitNumber);
  44400. dummyScale.setInterval(1); // Force all the axis fixing the maxSplitNumber.
  44401. each(indicatorAxes, function (indicatorAxis, idx) {
  44402. alignScaleTicks(indicatorAxis.scale, indicatorAxis.model, dummyScale);
  44403. });
  44404. };
  44405. Radar.prototype.convertToPixel = function (ecModel, finder, value) {
  44406. console.warn('Not implemented.');
  44407. return null;
  44408. };
  44409. Radar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44410. console.warn('Not implemented.');
  44411. return null;
  44412. };
  44413. Radar.prototype.containPoint = function (point) {
  44414. console.warn('Not implemented.');
  44415. return false;
  44416. };
  44417. Radar.create = function (ecModel, api) {
  44418. var radarList = [];
  44419. ecModel.eachComponent('radar', function (radarModel) {
  44420. var radar = new Radar(radarModel, ecModel, api);
  44421. radarList.push(radar);
  44422. radarModel.coordinateSystem = radar;
  44423. });
  44424. ecModel.eachSeriesByType('radar', function (radarSeries) {
  44425. if (radarSeries.get('coordinateSystem') === 'radar') {
  44426. // Inject coordinate system
  44427. // @ts-ignore
  44428. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  44429. }
  44430. });
  44431. return radarList;
  44432. };
  44433. /**
  44434. * Radar dimensions is based on the data
  44435. */
  44436. Radar.dimensions = [];
  44437. return Radar;
  44438. }();
  44439. function install$7(registers) {
  44440. registers.registerCoordinateSystem('radar', Radar);
  44441. registers.registerComponentModel(RadarModel);
  44442. registers.registerComponentView(RadarView$1);
  44443. registers.registerVisual({
  44444. seriesType: 'radar',
  44445. reset: function (seriesModel) {
  44446. var data = seriesModel.getData(); // itemVisual symbol is for selected data
  44447. data.each(function (idx) {
  44448. data.setItemVisual(idx, 'legendIcon', 'roundRect');
  44449. }); // visual is for unselected data
  44450. data.setVisual('legendIcon', 'roundRect');
  44451. }
  44452. });
  44453. }
  44454. function install$8(registers) {
  44455. use(install$7);
  44456. registers.registerChartView(RadarView);
  44457. registers.registerSeriesModel(RadarSeriesModel);
  44458. registers.registerLayout(radarLayout);
  44459. registers.registerProcessor(dataFilter('radar'));
  44460. registers.registerPreprocessor(radarBackwardCompat);
  44461. }
  44462. var ATTR = '\0_ec_interaction_mutex';
  44463. function take(zr, resourceKey, userKey) {
  44464. var store = getStore(zr);
  44465. store[resourceKey] = userKey;
  44466. }
  44467. function release(zr, resourceKey, userKey) {
  44468. var store = getStore(zr);
  44469. var uKey = store[resourceKey];
  44470. if (uKey === userKey) {
  44471. store[resourceKey] = null;
  44472. }
  44473. }
  44474. function isTaken(zr, resourceKey) {
  44475. return !!getStore(zr)[resourceKey];
  44476. }
  44477. function getStore(zr) {
  44478. return zr[ATTR] || (zr[ATTR] = {});
  44479. }
  44480. /**
  44481. * payload: {
  44482. * type: 'takeGlobalCursor',
  44483. * key: 'dataZoomSelect', or 'brush', or ...,
  44484. * If no userKey, release global cursor.
  44485. * }
  44486. */
  44487. // TODO: SELF REGISTERED.
  44488. registerAction({
  44489. type: 'takeGlobalCursor',
  44490. event: 'globalCursorTaken',
  44491. update: 'update'
  44492. }, noop);
  44493. var RoamController =
  44494. /** @class */
  44495. function (_super) {
  44496. __extends(RoamController, _super);
  44497. function RoamController(zr) {
  44498. var _this = _super.call(this) || this;
  44499. _this._zr = zr; // Avoid two roamController bind the same handler
  44500. var mousedownHandler = bind(_this._mousedownHandler, _this);
  44501. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  44502. var mouseupHandler = bind(_this._mouseupHandler, _this);
  44503. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  44504. var pinchHandler = bind(_this._pinchHandler, _this);
  44505. /**
  44506. * Notice: only enable needed types. For example, if 'zoom'
  44507. * is not needed, 'zoom' should not be enabled, otherwise
  44508. * default mousewheel behaviour (scroll page) will be disabled.
  44509. */
  44510. _this.enable = function (controlType, opt) {
  44511. // Disable previous first
  44512. this.disable();
  44513. this._opt = defaults(clone(opt) || {}, {
  44514. zoomOnMouseWheel: true,
  44515. moveOnMouseMove: true,
  44516. // By default, wheel do not trigger move.
  44517. moveOnMouseWheel: false,
  44518. preventDefaultMouseMove: true
  44519. });
  44520. if (controlType == null) {
  44521. controlType = true;
  44522. }
  44523. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  44524. zr.on('mousedown', mousedownHandler);
  44525. zr.on('mousemove', mousemoveHandler);
  44526. zr.on('mouseup', mouseupHandler);
  44527. }
  44528. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  44529. zr.on('mousewheel', mousewheelHandler);
  44530. zr.on('pinch', pinchHandler);
  44531. }
  44532. };
  44533. _this.disable = function () {
  44534. zr.off('mousedown', mousedownHandler);
  44535. zr.off('mousemove', mousemoveHandler);
  44536. zr.off('mouseup', mouseupHandler);
  44537. zr.off('mousewheel', mousewheelHandler);
  44538. zr.off('pinch', pinchHandler);
  44539. };
  44540. return _this;
  44541. }
  44542. RoamController.prototype.isDragging = function () {
  44543. return this._dragging;
  44544. };
  44545. RoamController.prototype.isPinching = function () {
  44546. return this._pinching;
  44547. };
  44548. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  44549. this.pointerChecker = pointerChecker;
  44550. };
  44551. RoamController.prototype.dispose = function () {
  44552. this.disable();
  44553. };
  44554. RoamController.prototype._mousedownHandler = function (e) {
  44555. if (isMiddleOrRightButtonOnMouseUpDown(e)) {
  44556. return;
  44557. }
  44558. var el = e.target;
  44559. while (el) {
  44560. if (el.draggable) {
  44561. return;
  44562. } // check if host is draggable
  44563. el = el.__hostTarget || el.parent;
  44564. }
  44565. var x = e.offsetX;
  44566. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  44567. // Mouse can be out of target when mouse moving.
  44568. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  44569. this._x = x;
  44570. this._y = y;
  44571. this._dragging = true;
  44572. }
  44573. };
  44574. RoamController.prototype._mousemoveHandler = function (e) {
  44575. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  44576. return;
  44577. }
  44578. var x = e.offsetX;
  44579. var y = e.offsetY;
  44580. var oldX = this._x;
  44581. var oldY = this._y;
  44582. var dx = x - oldX;
  44583. var dy = y - oldY;
  44584. this._x = x;
  44585. this._y = y;
  44586. this._opt.preventDefaultMouseMove && stop(e.event);
  44587. trigger(this, 'pan', 'moveOnMouseMove', e, {
  44588. dx: dx,
  44589. dy: dy,
  44590. oldX: oldX,
  44591. oldY: oldY,
  44592. newX: x,
  44593. newY: y,
  44594. isAvailableBehavior: null
  44595. });
  44596. };
  44597. RoamController.prototype._mouseupHandler = function (e) {
  44598. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  44599. this._dragging = false;
  44600. }
  44601. };
  44602. RoamController.prototype._mousewheelHandler = function (e) {
  44603. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  44604. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  44605. var wheelDelta = e.wheelDelta;
  44606. var absWheelDeltaDelta = Math.abs(wheelDelta);
  44607. var originX = e.offsetX;
  44608. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  44609. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  44610. return;
  44611. } // If both `shouldZoom` and `shouldMove` is true, trigger
  44612. // their event both, and the final behavior is determined
  44613. // by event listener themselves.
  44614. if (shouldZoom) {
  44615. // Convenience:
  44616. // Mac and VM Windows on Mac: scroll up: zoom out.
  44617. // Windows: scroll up: zoom in.
  44618. // FIXME: Should do more test in different environment.
  44619. // wheelDelta is too complicated in difference nvironment
  44620. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  44621. // although it has been normallized by zrender.
  44622. // wheelDelta of mouse wheel is bigger than touch pad.
  44623. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  44624. var scale = wheelDelta > 0 ? factor : 1 / factor;
  44625. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  44626. scale: scale,
  44627. originX: originX,
  44628. originY: originY,
  44629. isAvailableBehavior: null
  44630. });
  44631. }
  44632. if (shouldMove) {
  44633. // FIXME: Should do more test in different environment.
  44634. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  44635. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  44636. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  44637. scrollDelta: scrollDelta,
  44638. originX: originX,
  44639. originY: originY,
  44640. isAvailableBehavior: null
  44641. });
  44642. }
  44643. };
  44644. RoamController.prototype._pinchHandler = function (e) {
  44645. if (isTaken(this._zr, 'globalPan')) {
  44646. return;
  44647. }
  44648. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  44649. checkPointerAndTrigger(this, 'zoom', null, e, {
  44650. scale: scale,
  44651. originX: e.pinchX,
  44652. originY: e.pinchY,
  44653. isAvailableBehavior: null
  44654. });
  44655. };
  44656. return RoamController;
  44657. }(Eventful);
  44658. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44659. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  44660. // When mouse is out of roamController rect,
  44661. // default befavoius should not be be disabled, otherwise
  44662. // page sliding is disabled, contrary to expectation.
  44663. stop(e.event);
  44664. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  44665. }
  44666. }
  44667. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  44668. // Also provide behavior checker for event listener, for some case that
  44669. // multiple components share one listener.
  44670. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e); // TODO should not have type issue.
  44671. controller.trigger(eventName, contollerEvent);
  44672. } // settings: {
  44673. // zoomOnMouseWheel
  44674. // moveOnMouseMove
  44675. // moveOnMouseWheel
  44676. // }
  44677. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  44678. function isAvailableBehavior(behaviorToCheck, e, settings) {
  44679. var setting = settings[behaviorToCheck];
  44680. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  44681. }
  44682. /*
  44683. * Licensed to the Apache Software Foundation (ASF) under one
  44684. * or more contributor license agreements. See the NOTICE file
  44685. * distributed with this work for additional information
  44686. * regarding copyright ownership. The ASF licenses this file
  44687. * to you under the Apache License, Version 2.0 (the
  44688. * "License"); you may not use this file except in compliance
  44689. * with the License. You may obtain a copy of the License at
  44690. *
  44691. * http://www.apache.org/licenses/LICENSE-2.0
  44692. *
  44693. * Unless required by applicable law or agreed to in writing,
  44694. * software distributed under the License is distributed on an
  44695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44696. * KIND, either express or implied. See the License for the
  44697. * specific language governing permissions and limitations
  44698. * under the License.
  44699. */
  44700. /**
  44701. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44702. */
  44703. /*
  44704. * Licensed to the Apache Software Foundation (ASF) under one
  44705. * or more contributor license agreements. See the NOTICE file
  44706. * distributed with this work for additional information
  44707. * regarding copyright ownership. The ASF licenses this file
  44708. * to you under the Apache License, Version 2.0 (the
  44709. * "License"); you may not use this file except in compliance
  44710. * with the License. You may obtain a copy of the License at
  44711. *
  44712. * http://www.apache.org/licenses/LICENSE-2.0
  44713. *
  44714. * Unless required by applicable law or agreed to in writing,
  44715. * software distributed under the License is distributed on an
  44716. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44717. * KIND, either express or implied. See the License for the
  44718. * specific language governing permissions and limitations
  44719. * under the License.
  44720. */
  44721. /**
  44722. * For geo and graph.
  44723. */
  44724. function updateViewOnPan(controllerHost, dx, dy) {
  44725. var target = controllerHost.target;
  44726. target.x += dx;
  44727. target.y += dy;
  44728. target.dirty();
  44729. }
  44730. /**
  44731. * For geo and graph.
  44732. */
  44733. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  44734. var target = controllerHost.target;
  44735. var zoomLimit = controllerHost.zoomLimit;
  44736. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  44737. newZoom *= zoomDelta;
  44738. if (zoomLimit) {
  44739. var zoomMin = zoomLimit.min || 0;
  44740. var zoomMax = zoomLimit.max || Infinity;
  44741. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  44742. }
  44743. var zoomScale = newZoom / controllerHost.zoom;
  44744. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  44745. target.x -= (zoomX - target.x) * (zoomScale - 1);
  44746. target.y -= (zoomY - target.y) * (zoomScale - 1);
  44747. target.scaleX *= zoomScale;
  44748. target.scaleY *= zoomScale;
  44749. target.dirty();
  44750. }
  44751. /*
  44752. * Licensed to the Apache Software Foundation (ASF) under one
  44753. * or more contributor license agreements. See the NOTICE file
  44754. * distributed with this work for additional information
  44755. * regarding copyright ownership. The ASF licenses this file
  44756. * to you under the Apache License, Version 2.0 (the
  44757. * "License"); you may not use this file except in compliance
  44758. * with the License. You may obtain a copy of the License at
  44759. *
  44760. * http://www.apache.org/licenses/LICENSE-2.0
  44761. *
  44762. * Unless required by applicable law or agreed to in writing,
  44763. * software distributed under the License is distributed on an
  44764. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44765. * KIND, either express or implied. See the License for the
  44766. * specific language governing permissions and limitations
  44767. * under the License.
  44768. */
  44769. /**
  44770. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44771. */
  44772. /*
  44773. * Licensed to the Apache Software Foundation (ASF) under one
  44774. * or more contributor license agreements. See the NOTICE file
  44775. * distributed with this work for additional information
  44776. * regarding copyright ownership. The ASF licenses this file
  44777. * to you under the Apache License, Version 2.0 (the
  44778. * "License"); you may not use this file except in compliance
  44779. * with the License. You may obtain a copy of the License at
  44780. *
  44781. * http://www.apache.org/licenses/LICENSE-2.0
  44782. *
  44783. * Unless required by applicable law or agreed to in writing,
  44784. * software distributed under the License is distributed on an
  44785. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44786. * KIND, either express or implied. See the License for the
  44787. * specific language governing permissions and limitations
  44788. * under the License.
  44789. */
  44790. var IRRELEVANT_EXCLUDES = {
  44791. 'axisPointer': 1,
  44792. 'tooltip': 1,
  44793. 'brush': 1
  44794. };
  44795. /**
  44796. * Avoid that: mouse click on a elements that is over geo or graph,
  44797. * but roam is triggered.
  44798. */
  44799. function onIrrelevantElement(e, api, targetCoordSysModel) {
  44800. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  44801. var coordSys = model && model.coordinateSystem;
  44802. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  44803. }
  44804. function parseXML(svg) {
  44805. if (isString(svg)) {
  44806. var parser = new DOMParser();
  44807. svg = parser.parseFromString(svg, 'text/xml');
  44808. }
  44809. var svgNode = svg;
  44810. if (svgNode.nodeType === 9) {
  44811. svgNode = svgNode.firstChild;
  44812. }
  44813. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  44814. svgNode = svgNode.nextSibling;
  44815. }
  44816. return svgNode;
  44817. }
  44818. var nodeParsers;
  44819. var INHERITABLE_STYLE_ATTRIBUTES_MAP = {
  44820. 'fill': 'fill',
  44821. 'stroke': 'stroke',
  44822. 'stroke-width': 'lineWidth',
  44823. 'opacity': 'opacity',
  44824. 'fill-opacity': 'fillOpacity',
  44825. 'stroke-opacity': 'strokeOpacity',
  44826. 'stroke-dasharray': 'lineDash',
  44827. 'stroke-dashoffset': 'lineDashOffset',
  44828. 'stroke-linecap': 'lineCap',
  44829. 'stroke-linejoin': 'lineJoin',
  44830. 'stroke-miterlimit': 'miterLimit',
  44831. 'font-family': 'fontFamily',
  44832. 'font-size': 'fontSize',
  44833. 'font-style': 'fontStyle',
  44834. 'font-weight': 'fontWeight',
  44835. 'text-anchor': 'textAlign',
  44836. 'visibility': 'visibility',
  44837. 'display': 'display'
  44838. };
  44839. var INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS = keys(INHERITABLE_STYLE_ATTRIBUTES_MAP);
  44840. var SELF_STYLE_ATTRIBUTES_MAP = {
  44841. 'alignment-baseline': 'textBaseline',
  44842. 'stop-color': 'stopColor'
  44843. };
  44844. var SELF_STYLE_ATTRIBUTES_MAP_KEYS = keys(SELF_STYLE_ATTRIBUTES_MAP);
  44845. var SVGParser = (function () {
  44846. function SVGParser() {
  44847. this._defs = {};
  44848. this._root = null;
  44849. }
  44850. SVGParser.prototype.parse = function (xml, opt) {
  44851. opt = opt || {};
  44852. var svg = parseXML(xml);
  44853. if ("development" !== 'production') {
  44854. if (!svg) {
  44855. throw new Error('Illegal svg');
  44856. }
  44857. }
  44858. this._defsUsePending = [];
  44859. var root = new Group();
  44860. this._root = root;
  44861. var named = [];
  44862. var viewBox = svg.getAttribute('viewBox') || '';
  44863. var width = parseFloat((svg.getAttribute('width') || opt.width));
  44864. var height = parseFloat((svg.getAttribute('height') || opt.height));
  44865. isNaN(width) && (width = null);
  44866. isNaN(height) && (height = null);
  44867. parseAttributes(svg, root, null, true, false);
  44868. var child = svg.firstChild;
  44869. while (child) {
  44870. this._parseNode(child, root, named, null, false, false);
  44871. child = child.nextSibling;
  44872. }
  44873. applyDefs(this._defs, this._defsUsePending);
  44874. this._defsUsePending = [];
  44875. var viewBoxRect;
  44876. var viewBoxTransform;
  44877. if (viewBox) {
  44878. var viewBoxArr = splitNumberSequence(viewBox);
  44879. if (viewBoxArr.length >= 4) {
  44880. viewBoxRect = {
  44881. x: parseFloat((viewBoxArr[0] || 0)),
  44882. y: parseFloat((viewBoxArr[1] || 0)),
  44883. width: parseFloat(viewBoxArr[2]),
  44884. height: parseFloat(viewBoxArr[3])
  44885. };
  44886. }
  44887. }
  44888. if (viewBoxRect && width != null && height != null) {
  44889. viewBoxTransform = makeViewBoxTransform(viewBoxRect, { x: 0, y: 0, width: width, height: height });
  44890. if (!opt.ignoreViewBox) {
  44891. var elRoot = root;
  44892. root = new Group();
  44893. root.add(elRoot);
  44894. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  44895. elRoot.x = viewBoxTransform.x;
  44896. elRoot.y = viewBoxTransform.y;
  44897. }
  44898. }
  44899. if (!opt.ignoreRootClip && width != null && height != null) {
  44900. root.setClipPath(new Rect({
  44901. shape: { x: 0, y: 0, width: width, height: height }
  44902. }));
  44903. }
  44904. return {
  44905. root: root,
  44906. width: width,
  44907. height: height,
  44908. viewBoxRect: viewBoxRect,
  44909. viewBoxTransform: viewBoxTransform,
  44910. named: named
  44911. };
  44912. };
  44913. SVGParser.prototype._parseNode = function (xmlNode, parentGroup, named, namedFrom, isInDefs, isInText) {
  44914. var nodeName = xmlNode.nodeName.toLowerCase();
  44915. var el;
  44916. var namedFromForSub = namedFrom;
  44917. if (nodeName === 'defs') {
  44918. isInDefs = true;
  44919. }
  44920. if (nodeName === 'text') {
  44921. isInText = true;
  44922. }
  44923. if (nodeName === 'defs' || nodeName === 'switch') {
  44924. el = parentGroup;
  44925. }
  44926. else {
  44927. if (!isInDefs) {
  44928. var parser_1 = nodeParsers[nodeName];
  44929. if (parser_1 && hasOwn(nodeParsers, nodeName)) {
  44930. el = parser_1.call(this, xmlNode, parentGroup);
  44931. var nameAttr = xmlNode.getAttribute('name');
  44932. if (nameAttr) {
  44933. var newNamed = {
  44934. name: nameAttr,
  44935. namedFrom: null,
  44936. svgNodeTagLower: nodeName,
  44937. el: el
  44938. };
  44939. named.push(newNamed);
  44940. if (nodeName === 'g') {
  44941. namedFromForSub = newNamed;
  44942. }
  44943. }
  44944. else if (namedFrom) {
  44945. named.push({
  44946. name: namedFrom.name,
  44947. namedFrom: namedFrom,
  44948. svgNodeTagLower: nodeName,
  44949. el: el
  44950. });
  44951. }
  44952. parentGroup.add(el);
  44953. }
  44954. }
  44955. var parser = paintServerParsers[nodeName];
  44956. if (parser && hasOwn(paintServerParsers, nodeName)) {
  44957. var def = parser.call(this, xmlNode);
  44958. var id = xmlNode.getAttribute('id');
  44959. if (id) {
  44960. this._defs[id] = def;
  44961. }
  44962. }
  44963. }
  44964. if (el && el.isGroup) {
  44965. var child = xmlNode.firstChild;
  44966. while (child) {
  44967. if (child.nodeType === 1) {
  44968. this._parseNode(child, el, named, namedFromForSub, isInDefs, isInText);
  44969. }
  44970. else if (child.nodeType === 3 && isInText) {
  44971. this._parseText(child, el);
  44972. }
  44973. child = child.nextSibling;
  44974. }
  44975. }
  44976. };
  44977. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  44978. var text = new TSpan({
  44979. style: {
  44980. text: xmlNode.textContent
  44981. },
  44982. silent: true,
  44983. x: this._textX || 0,
  44984. y: this._textY || 0
  44985. });
  44986. inheritStyle(parentGroup, text);
  44987. parseAttributes(xmlNode, text, this._defsUsePending, false, false);
  44988. applyTextAlignment(text, parentGroup);
  44989. var textStyle = text.style;
  44990. var fontSize = textStyle.fontSize;
  44991. if (fontSize && fontSize < 9) {
  44992. textStyle.fontSize = 9;
  44993. text.scaleX *= fontSize / 9;
  44994. text.scaleY *= fontSize / 9;
  44995. }
  44996. var font = (textStyle.fontSize || textStyle.fontFamily) && [
  44997. textStyle.fontStyle,
  44998. textStyle.fontWeight,
  44999. (textStyle.fontSize || 12) + 'px',
  45000. textStyle.fontFamily || 'sans-serif'
  45001. ].join(' ');
  45002. textStyle.font = font;
  45003. var rect = text.getBoundingRect();
  45004. this._textX += rect.width;
  45005. parentGroup.add(text);
  45006. return text;
  45007. };
  45008. SVGParser.internalField = (function () {
  45009. nodeParsers = {
  45010. 'g': function (xmlNode, parentGroup) {
  45011. var g = new Group();
  45012. inheritStyle(parentGroup, g);
  45013. parseAttributes(xmlNode, g, this._defsUsePending, false, false);
  45014. return g;
  45015. },
  45016. 'rect': function (xmlNode, parentGroup) {
  45017. var rect = new Rect();
  45018. inheritStyle(parentGroup, rect);
  45019. parseAttributes(xmlNode, rect, this._defsUsePending, false, false);
  45020. rect.setShape({
  45021. x: parseFloat(xmlNode.getAttribute('x') || '0'),
  45022. y: parseFloat(xmlNode.getAttribute('y') || '0'),
  45023. width: parseFloat(xmlNode.getAttribute('width') || '0'),
  45024. height: parseFloat(xmlNode.getAttribute('height') || '0')
  45025. });
  45026. rect.silent = true;
  45027. return rect;
  45028. },
  45029. 'circle': function (xmlNode, parentGroup) {
  45030. var circle = new Circle();
  45031. inheritStyle(parentGroup, circle);
  45032. parseAttributes(xmlNode, circle, this._defsUsePending, false, false);
  45033. circle.setShape({
  45034. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45035. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45036. r: parseFloat(xmlNode.getAttribute('r') || '0')
  45037. });
  45038. circle.silent = true;
  45039. return circle;
  45040. },
  45041. 'line': function (xmlNode, parentGroup) {
  45042. var line = new Line();
  45043. inheritStyle(parentGroup, line);
  45044. parseAttributes(xmlNode, line, this._defsUsePending, false, false);
  45045. line.setShape({
  45046. x1: parseFloat(xmlNode.getAttribute('x1') || '0'),
  45047. y1: parseFloat(xmlNode.getAttribute('y1') || '0'),
  45048. x2: parseFloat(xmlNode.getAttribute('x2') || '0'),
  45049. y2: parseFloat(xmlNode.getAttribute('y2') || '0')
  45050. });
  45051. line.silent = true;
  45052. return line;
  45053. },
  45054. 'ellipse': function (xmlNode, parentGroup) {
  45055. var ellipse = new Ellipse();
  45056. inheritStyle(parentGroup, ellipse);
  45057. parseAttributes(xmlNode, ellipse, this._defsUsePending, false, false);
  45058. ellipse.setShape({
  45059. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  45060. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  45061. rx: parseFloat(xmlNode.getAttribute('rx') || '0'),
  45062. ry: parseFloat(xmlNode.getAttribute('ry') || '0')
  45063. });
  45064. ellipse.silent = true;
  45065. return ellipse;
  45066. },
  45067. 'polygon': function (xmlNode, parentGroup) {
  45068. var pointsStr = xmlNode.getAttribute('points');
  45069. var pointsArr;
  45070. if (pointsStr) {
  45071. pointsArr = parsePoints(pointsStr);
  45072. }
  45073. var polygon = new Polygon({
  45074. shape: {
  45075. points: pointsArr || []
  45076. },
  45077. silent: true
  45078. });
  45079. inheritStyle(parentGroup, polygon);
  45080. parseAttributes(xmlNode, polygon, this._defsUsePending, false, false);
  45081. return polygon;
  45082. },
  45083. 'polyline': function (xmlNode, parentGroup) {
  45084. var pointsStr = xmlNode.getAttribute('points');
  45085. var pointsArr;
  45086. if (pointsStr) {
  45087. pointsArr = parsePoints(pointsStr);
  45088. }
  45089. var polyline = new Polyline({
  45090. shape: {
  45091. points: pointsArr || []
  45092. },
  45093. silent: true
  45094. });
  45095. inheritStyle(parentGroup, polyline);
  45096. parseAttributes(xmlNode, polyline, this._defsUsePending, false, false);
  45097. return polyline;
  45098. },
  45099. 'image': function (xmlNode, parentGroup) {
  45100. var img = new ZRImage();
  45101. inheritStyle(parentGroup, img);
  45102. parseAttributes(xmlNode, img, this._defsUsePending, false, false);
  45103. img.setStyle({
  45104. image: xmlNode.getAttribute('xlink:href') || xmlNode.getAttribute('href'),
  45105. x: +xmlNode.getAttribute('x'),
  45106. y: +xmlNode.getAttribute('y'),
  45107. width: +xmlNode.getAttribute('width'),
  45108. height: +xmlNode.getAttribute('height')
  45109. });
  45110. img.silent = true;
  45111. return img;
  45112. },
  45113. 'text': function (xmlNode, parentGroup) {
  45114. var x = xmlNode.getAttribute('x') || '0';
  45115. var y = xmlNode.getAttribute('y') || '0';
  45116. var dx = xmlNode.getAttribute('dx') || '0';
  45117. var dy = xmlNode.getAttribute('dy') || '0';
  45118. this._textX = parseFloat(x) + parseFloat(dx);
  45119. this._textY = parseFloat(y) + parseFloat(dy);
  45120. var g = new Group();
  45121. inheritStyle(parentGroup, g);
  45122. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45123. return g;
  45124. },
  45125. 'tspan': function (xmlNode, parentGroup) {
  45126. var x = xmlNode.getAttribute('x');
  45127. var y = xmlNode.getAttribute('y');
  45128. if (x != null) {
  45129. this._textX = parseFloat(x);
  45130. }
  45131. if (y != null) {
  45132. this._textY = parseFloat(y);
  45133. }
  45134. var dx = xmlNode.getAttribute('dx') || '0';
  45135. var dy = xmlNode.getAttribute('dy') || '0';
  45136. var g = new Group();
  45137. inheritStyle(parentGroup, g);
  45138. parseAttributes(xmlNode, g, this._defsUsePending, false, true);
  45139. this._textX += parseFloat(dx);
  45140. this._textY += parseFloat(dy);
  45141. return g;
  45142. },
  45143. 'path': function (xmlNode, parentGroup) {
  45144. var d = xmlNode.getAttribute('d') || '';
  45145. var path = createFromString(d);
  45146. inheritStyle(parentGroup, path);
  45147. parseAttributes(xmlNode, path, this._defsUsePending, false, false);
  45148. path.silent = true;
  45149. return path;
  45150. }
  45151. };
  45152. })();
  45153. return SVGParser;
  45154. }());
  45155. var paintServerParsers = {
  45156. 'lineargradient': function (xmlNode) {
  45157. var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);
  45158. var y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);
  45159. var x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10);
  45160. var y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10);
  45161. var gradient = new LinearGradient(x1, y1, x2, y2);
  45162. parsePaintServerUnit(xmlNode, gradient);
  45163. parseGradientColorStops(xmlNode, gradient);
  45164. return gradient;
  45165. },
  45166. 'radialgradient': function (xmlNode) {
  45167. var cx = parseInt(xmlNode.getAttribute('cx') || '0', 10);
  45168. var cy = parseInt(xmlNode.getAttribute('cy') || '0', 10);
  45169. var r = parseInt(xmlNode.getAttribute('r') || '0', 10);
  45170. var gradient = new RadialGradient(cx, cy, r);
  45171. parsePaintServerUnit(xmlNode, gradient);
  45172. parseGradientColorStops(xmlNode, gradient);
  45173. return gradient;
  45174. }
  45175. };
  45176. function parsePaintServerUnit(xmlNode, gradient) {
  45177. var gradientUnits = xmlNode.getAttribute('gradientUnits');
  45178. if (gradientUnits === 'userSpaceOnUse') {
  45179. gradient.global = true;
  45180. }
  45181. }
  45182. function parseGradientColorStops(xmlNode, gradient) {
  45183. var stop = xmlNode.firstChild;
  45184. while (stop) {
  45185. if (stop.nodeType === 1
  45186. && stop.nodeName.toLocaleLowerCase() === 'stop') {
  45187. var offsetStr = stop.getAttribute('offset');
  45188. var offset = void 0;
  45189. if (offsetStr && offsetStr.indexOf('%') > 0) {
  45190. offset = parseInt(offsetStr, 10) / 100;
  45191. }
  45192. else if (offsetStr) {
  45193. offset = parseFloat(offsetStr);
  45194. }
  45195. else {
  45196. offset = 0;
  45197. }
  45198. var styleVals = {};
  45199. parseInlineStyle(stop, styleVals, styleVals);
  45200. var stopColor = styleVals.stopColor
  45201. || stop.getAttribute('stop-color')
  45202. || '#000000';
  45203. gradient.colorStops.push({
  45204. offset: offset,
  45205. color: stopColor
  45206. });
  45207. }
  45208. stop = stop.nextSibling;
  45209. }
  45210. }
  45211. function inheritStyle(parent, child) {
  45212. if (parent && parent.__inheritedStyle) {
  45213. if (!child.__inheritedStyle) {
  45214. child.__inheritedStyle = {};
  45215. }
  45216. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  45217. }
  45218. }
  45219. function parsePoints(pointsString) {
  45220. var list = splitNumberSequence(pointsString);
  45221. var points = [];
  45222. for (var i = 0; i < list.length; i += 2) {
  45223. var x = parseFloat(list[i]);
  45224. var y = parseFloat(list[i + 1]);
  45225. points.push([x, y]);
  45226. }
  45227. return points;
  45228. }
  45229. function parseAttributes(xmlNode, el, defsUsePending, onlyInlineStyle, isTextGroup) {
  45230. var disp = el;
  45231. var inheritedStyle = disp.__inheritedStyle = disp.__inheritedStyle || {};
  45232. var selfStyle = {};
  45233. if (xmlNode.nodeType === 1) {
  45234. parseTransformAttribute(xmlNode, el);
  45235. parseInlineStyle(xmlNode, inheritedStyle, selfStyle);
  45236. if (!onlyInlineStyle) {
  45237. parseAttributeStyle(xmlNode, inheritedStyle, selfStyle);
  45238. }
  45239. }
  45240. disp.style = disp.style || {};
  45241. if (inheritedStyle.fill != null) {
  45242. disp.style.fill = getFillStrokeStyle(disp, 'fill', inheritedStyle.fill, defsUsePending);
  45243. }
  45244. if (inheritedStyle.stroke != null) {
  45245. disp.style.stroke = getFillStrokeStyle(disp, 'stroke', inheritedStyle.stroke, defsUsePending);
  45246. }
  45247. each([
  45248. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  45249. ], function (propName) {
  45250. if (inheritedStyle[propName] != null) {
  45251. disp.style[propName] = parseFloat(inheritedStyle[propName]);
  45252. }
  45253. });
  45254. each([
  45255. 'lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign'
  45256. ], function (propName) {
  45257. if (inheritedStyle[propName] != null) {
  45258. disp.style[propName] = inheritedStyle[propName];
  45259. }
  45260. });
  45261. if (isTextGroup) {
  45262. disp.__selfStyle = selfStyle;
  45263. }
  45264. if (inheritedStyle.lineDash) {
  45265. disp.style.lineDash = map(splitNumberSequence(inheritedStyle.lineDash), function (str) {
  45266. return parseFloat(str);
  45267. });
  45268. }
  45269. if (inheritedStyle.visibility === 'hidden' || inheritedStyle.visibility === 'collapse') {
  45270. disp.invisible = true;
  45271. }
  45272. if (inheritedStyle.display === 'none') {
  45273. disp.ignore = true;
  45274. }
  45275. }
  45276. function applyTextAlignment(text, parentGroup) {
  45277. var parentSelfStyle = parentGroup.__selfStyle;
  45278. if (parentSelfStyle) {
  45279. var textBaseline = parentSelfStyle.textBaseline;
  45280. var zrTextBaseline = textBaseline;
  45281. if (!textBaseline || textBaseline === 'auto') {
  45282. zrTextBaseline = 'alphabetic';
  45283. }
  45284. else if (textBaseline === 'baseline') {
  45285. zrTextBaseline = 'alphabetic';
  45286. }
  45287. else if (textBaseline === 'before-edge' || textBaseline === 'text-before-edge') {
  45288. zrTextBaseline = 'top';
  45289. }
  45290. else if (textBaseline === 'after-edge' || textBaseline === 'text-after-edge') {
  45291. zrTextBaseline = 'bottom';
  45292. }
  45293. else if (textBaseline === 'central' || textBaseline === 'mathematical') {
  45294. zrTextBaseline = 'middle';
  45295. }
  45296. text.style.textBaseline = zrTextBaseline;
  45297. }
  45298. var parentInheritedStyle = parentGroup.__inheritedStyle;
  45299. if (parentInheritedStyle) {
  45300. var textAlign = parentInheritedStyle.textAlign;
  45301. var zrTextAlign = textAlign;
  45302. if (textAlign) {
  45303. if (textAlign === 'middle') {
  45304. zrTextAlign = 'center';
  45305. }
  45306. text.style.textAlign = zrTextAlign;
  45307. }
  45308. }
  45309. }
  45310. var urlRegex = /^url\(\s*#(.*?)\)/;
  45311. function getFillStrokeStyle(el, method, str, defsUsePending) {
  45312. var urlMatch = str && str.match(urlRegex);
  45313. if (urlMatch) {
  45314. var url = trim(urlMatch[1]);
  45315. defsUsePending.push([el, method, url]);
  45316. return;
  45317. }
  45318. if (str === 'none') {
  45319. str = null;
  45320. }
  45321. return str;
  45322. }
  45323. function applyDefs(defs, defsUsePending) {
  45324. for (var i = 0; i < defsUsePending.length; i++) {
  45325. var item = defsUsePending[i];
  45326. item[0].style[item[1]] = defs[item[2]];
  45327. }
  45328. }
  45329. var numberReg$1 = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  45330. function splitNumberSequence(rawStr) {
  45331. return rawStr.match(numberReg$1) || [];
  45332. }
  45333. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.eE,]*)\)/g;
  45334. var DEGREE_TO_ANGLE = Math.PI / 180;
  45335. function parseTransformAttribute(xmlNode, node) {
  45336. var transform = xmlNode.getAttribute('transform');
  45337. if (transform) {
  45338. transform = transform.replace(/,/g, ' ');
  45339. var transformOps_1 = [];
  45340. var mt = null;
  45341. transform.replace(transformRegex, function (str, type, value) {
  45342. transformOps_1.push(type, value);
  45343. return '';
  45344. });
  45345. for (var i = transformOps_1.length - 1; i > 0; i -= 2) {
  45346. var value = transformOps_1[i];
  45347. var type = transformOps_1[i - 1];
  45348. var valueArr = splitNumberSequence(value);
  45349. mt = mt || create$1();
  45350. switch (type) {
  45351. case 'translate':
  45352. translate(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
  45353. break;
  45354. case 'scale':
  45355. scale$1(mt, mt, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
  45356. break;
  45357. case 'rotate':
  45358. rotate(mt, mt, -parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45359. break;
  45360. case 'skewX':
  45361. var sx = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45362. mul$1(mt, [1, 0, sx, 1, 0, 0], mt);
  45363. break;
  45364. case 'skewY':
  45365. var sy = Math.tan(parseFloat(valueArr[0]) * DEGREE_TO_ANGLE);
  45366. mul$1(mt, [1, sy, 0, 1, 0, 0], mt);
  45367. break;
  45368. case 'matrix':
  45369. mt[0] = parseFloat(valueArr[0]);
  45370. mt[1] = parseFloat(valueArr[1]);
  45371. mt[2] = parseFloat(valueArr[2]);
  45372. mt[3] = parseFloat(valueArr[3]);
  45373. mt[4] = parseFloat(valueArr[4]);
  45374. mt[5] = parseFloat(valueArr[5]);
  45375. break;
  45376. }
  45377. }
  45378. node.setLocalTransform(mt);
  45379. }
  45380. }
  45381. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  45382. function parseInlineStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45383. var style = xmlNode.getAttribute('style');
  45384. if (!style) {
  45385. return;
  45386. }
  45387. styleRegex.lastIndex = 0;
  45388. var styleRegResult;
  45389. while ((styleRegResult = styleRegex.exec(style)) != null) {
  45390. var svgStlAttr = styleRegResult[1];
  45391. var zrInheritableStlAttr = hasOwn(INHERITABLE_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45392. ? INHERITABLE_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45393. : null;
  45394. if (zrInheritableStlAttr) {
  45395. inheritableStyleResult[zrInheritableStlAttr] = styleRegResult[2];
  45396. }
  45397. var zrSelfStlAttr = hasOwn(SELF_STYLE_ATTRIBUTES_MAP, svgStlAttr)
  45398. ? SELF_STYLE_ATTRIBUTES_MAP[svgStlAttr]
  45399. : null;
  45400. if (zrSelfStlAttr) {
  45401. selfStyleResult[zrSelfStlAttr] = styleRegResult[2];
  45402. }
  45403. }
  45404. }
  45405. function parseAttributeStyle(xmlNode, inheritableStyleResult, selfStyleResult) {
  45406. for (var i = 0; i < INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45407. var svgAttrName = INHERITABLE_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45408. var attrValue = xmlNode.getAttribute(svgAttrName);
  45409. if (attrValue != null) {
  45410. inheritableStyleResult[INHERITABLE_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45411. }
  45412. }
  45413. for (var i = 0; i < SELF_STYLE_ATTRIBUTES_MAP_KEYS.length; i++) {
  45414. var svgAttrName = SELF_STYLE_ATTRIBUTES_MAP_KEYS[i];
  45415. var attrValue = xmlNode.getAttribute(svgAttrName);
  45416. if (attrValue != null) {
  45417. selfStyleResult[SELF_STYLE_ATTRIBUTES_MAP[svgAttrName]] = attrValue;
  45418. }
  45419. }
  45420. }
  45421. function makeViewBoxTransform(viewBoxRect, boundingRect) {
  45422. var scaleX = boundingRect.width / viewBoxRect.width;
  45423. var scaleY = boundingRect.height / viewBoxRect.height;
  45424. var scale = Math.min(scaleX, scaleY);
  45425. return {
  45426. scale: scale,
  45427. x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + (boundingRect.x + boundingRect.width / 2),
  45428. y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + (boundingRect.y + boundingRect.height / 2)
  45429. };
  45430. }
  45431. function parseSVG(xml, opt) {
  45432. var parser = new SVGParser();
  45433. return parser.parse(xml, opt);
  45434. }
  45435. /**
  45436. * "region available" means that: enable users to set attribute `name="xxx"` on those tags
  45437. * to make it be a region.
  45438. * 1. region styles and its label styles can be defined in echarts opton:
  45439. * ```js
  45440. * geo: {
  45441. * regions: [{
  45442. * name: 'xxx',
  45443. * itemStyle: { ... },
  45444. * label: { ... }
  45445. * }, {
  45446. * ...
  45447. * },
  45448. * ...]
  45449. * };
  45450. * ```
  45451. * 2. name can be duplicated in different SVG tag. All of the tags with the same name share
  45452. * a region option. For exampel if there are two <path> representing two lung lobes. They have
  45453. * no common parents but both of them need to display label "lung" inside.
  45454. */
  45455. 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,
  45456. // but still need to trigger events or tooltip.
  45457. 'text', 'tspan', // <g> is also enabled because this case: if multiple tags share one name
  45458. // and need label displayed, every tags will display the name, which is not
  45459. // expected. So we can put them into a <g name="xxx">. Thereby only one label
  45460. // displayed and located based on the bounding rect of the <g>.
  45461. 'g']);
  45462. var GeoSVGResource =
  45463. /** @class */
  45464. function () {
  45465. function GeoSVGResource(mapName, svg) {
  45466. this.type = 'geoSVG'; // All used graphics. key: hostKey, value: root
  45467. this._usedGraphicMap = createHashMap(); // All unused graphics.
  45468. this._freedGraphics = [];
  45469. this._mapName = mapName; // Only perform parse to XML object here, which might be time
  45470. // consiming for large SVG.
  45471. // Although convert XML to zrender element is also time consiming,
  45472. // if we do it here, the clone of zrender elements has to be
  45473. // required. So we do it once for each geo instance, util real
  45474. // performance issues call for optimizing it.
  45475. this._parsedXML = parseXML(svg);
  45476. }
  45477. GeoSVGResource.prototype.load = function ()
  45478. /* nameMap: NameMap */
  45479. {
  45480. // In the "load" stage, graphic need to be built to
  45481. // get boundingRect for geo coordinate system.
  45482. var firstGraphic = this._firstGraphic; // Create the return data structure only when first graphic created.
  45483. // Because they will be used in geo coordinate system update stage,
  45484. // and `regions` will be mounted at `geo` coordinate system,
  45485. // in which there is no "view" info, so that it should better not to
  45486. // make references to graphic elements.
  45487. if (!firstGraphic) {
  45488. firstGraphic = this._firstGraphic = this._buildGraphic(this._parsedXML);
  45489. this._freedGraphics.push(firstGraphic);
  45490. this._boundingRect = this._firstGraphic.boundingRect.clone(); // PENDING: `nameMap` will not be supported until some real requirement come.
  45491. // if (nameMap) {
  45492. // named = applyNameMap(named, nameMap);
  45493. // }
  45494. var _a = createRegions(firstGraphic.named),
  45495. regions = _a.regions,
  45496. regionsMap = _a.regionsMap;
  45497. this._regions = regions;
  45498. this._regionsMap = regionsMap;
  45499. }
  45500. return {
  45501. boundingRect: this._boundingRect,
  45502. regions: this._regions,
  45503. regionsMap: this._regionsMap
  45504. };
  45505. };
  45506. GeoSVGResource.prototype._buildGraphic = function (svgXML) {
  45507. var result;
  45508. var rootFromParse;
  45509. try {
  45510. result = svgXML && parseSVG(svgXML, {
  45511. ignoreViewBox: true,
  45512. ignoreRootClip: true
  45513. }) || {};
  45514. rootFromParse = result.root;
  45515. assert(rootFromParse != null);
  45516. } catch (e) {
  45517. throw new Error('Invalid svg format\n' + e.message);
  45518. } // Note: we keep the covenant that the root has no transform. So always add an extra root.
  45519. var root = new Group();
  45520. root.add(rootFromParse);
  45521. root.isGeoSVGGraphicRoot = true; // [THE_RULE_OF_VIEWPORT_AND_VIEWBOX]
  45522. //
  45523. // Consider: `<svg width="..." height="..." viewBox="...">`
  45524. // - the `width/height` we call it `svgWidth/svgHeight` for short.
  45525. // - `(0, 0, svgWidth, svgHeight)` defines the viewport of the SVG, or say,
  45526. // "viewport boundingRect", or `boundingRect` for short.
  45527. // - `viewBox` defines the transform from the real content ot the viewport.
  45528. // `viewBox` has the same unit as the content of SVG.
  45529. // If `viewBox` exists, a transform is defined, so the unit of `svgWidth/svgHeight` become
  45530. // different from the content of SVG. Otherwise, they are the same.
  45531. //
  45532. // If both `svgWidth/svgHeight/viewBox` are specified in a SVG file, the transform rule will be:
  45533. // 0. `boundingRect` is `(0, 0, svgWidth, svgHeight)`. Set it to Geo['_rect'] (View['_rect']).
  45534. // 1. Make a transform from `viewBox` to `boundingRect`.
  45535. // Note: only support `preserveAspectRatio 'xMidYMid'` here. That is, this transform will preserve
  45536. // the aspect ratio.
  45537. // 2. Make a transform from boundingRect to Geo['_viewRect'] (View['_viewRect'])
  45538. // (`Geo`/`View` will do this job).
  45539. // Note: this transform might not preserve aspect radio, which depending on how users specify
  45540. // viewRect in echarts option (e.g., `geo.left/top/width/height` will not preserve aspect ratio,
  45541. // but `geo.layoutCenter/layoutSize` will preserve aspect ratio).
  45542. //
  45543. // If `svgWidth/svgHeight` not specified, we use `viewBox` as the `boundingRect` to make the SVG
  45544. // layout look good.
  45545. //
  45546. // If neither `svgWidth/svgHeight` nor `viewBox` are not specified, we calculate the boundingRect
  45547. // of the SVG content and use them to make SVG layout look good.
  45548. var svgWidth = result.width;
  45549. var svgHeight = result.height;
  45550. var viewBoxRect = result.viewBoxRect;
  45551. var boundingRect = this._boundingRect;
  45552. if (!boundingRect) {
  45553. var bRectX = void 0;
  45554. var bRectY = void 0;
  45555. var bRectWidth = void 0;
  45556. var bRectHeight = void 0;
  45557. if (svgWidth != null) {
  45558. bRectX = 0;
  45559. bRectWidth = svgWidth;
  45560. } else if (viewBoxRect) {
  45561. bRectX = viewBoxRect.x;
  45562. bRectWidth = viewBoxRect.width;
  45563. }
  45564. if (svgHeight != null) {
  45565. bRectY = 0;
  45566. bRectHeight = svgHeight;
  45567. } else if (viewBoxRect) {
  45568. bRectY = viewBoxRect.y;
  45569. bRectHeight = viewBoxRect.height;
  45570. } // If both viewBox and svgWidth/svgHeight not specified,
  45571. // we have to determine how to layout those element to make them look good.
  45572. if (bRectX == null || bRectY == null) {
  45573. var calculatedBoundingRect = rootFromParse.getBoundingRect();
  45574. if (bRectX == null) {
  45575. bRectX = calculatedBoundingRect.x;
  45576. bRectWidth = calculatedBoundingRect.width;
  45577. }
  45578. if (bRectY == null) {
  45579. bRectY = calculatedBoundingRect.y;
  45580. bRectHeight = calculatedBoundingRect.height;
  45581. }
  45582. }
  45583. boundingRect = this._boundingRect = new BoundingRect(bRectX, bRectY, bRectWidth, bRectHeight);
  45584. }
  45585. if (viewBoxRect) {
  45586. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect); // Only support `preserveAspectRatio 'xMidYMid'`
  45587. rootFromParse.scaleX = rootFromParse.scaleY = viewBoxTransform.scale;
  45588. rootFromParse.x = viewBoxTransform.x;
  45589. rootFromParse.y = viewBoxTransform.y;
  45590. } // SVG needs to clip based on `viewBox`. And some SVG files really rely on this feature.
  45591. // They do not strictly confine all of the content inside a display rect, but deliberately
  45592. // use a `viewBox` to define a displayable rect.
  45593. // PENDING:
  45594. // The drawback of the `setClipPath` here is: the region label (genereted by echarts) near the
  45595. // edge might also be clipped, because region labels are put as `textContent` of the SVG path.
  45596. root.setClipPath(new Rect({
  45597. shape: boundingRect.plain()
  45598. }));
  45599. var named = [];
  45600. each(result.named, function (namedItem) {
  45601. if (REGION_AVAILABLE_SVG_TAG_MAP.get(namedItem.svgNodeTagLower) != null) {
  45602. named.push(namedItem);
  45603. setSilent(namedItem.el);
  45604. }
  45605. });
  45606. return {
  45607. root: root,
  45608. boundingRect: boundingRect,
  45609. named: named
  45610. };
  45611. };
  45612. /**
  45613. * Consider:
  45614. * (1) One graphic element can not be shared by different `geoView` running simultaneously.
  45615. * Notice, also need to consider multiple echarts instances share a `mapRecord`.
  45616. * (2) Converting SVG to graphic elements is time consuming.
  45617. * (3) In the current architecture, `load` should be called frequently to get boundingRect,
  45618. * and it is called without view info.
  45619. * So we maintain graphic elements in this module, and enables `view` to use/return these
  45620. * graphics from/to the pool with it's uid.
  45621. */
  45622. GeoSVGResource.prototype.useGraphic = function (hostKey
  45623. /* , nameMap: NameMap */
  45624. ) {
  45625. var usedRootMap = this._usedGraphicMap;
  45626. var svgGraphic = usedRootMap.get(hostKey);
  45627. if (svgGraphic) {
  45628. return svgGraphic;
  45629. }
  45630. svgGraphic = this._freedGraphics.pop() // use the first boundingRect to avoid duplicated boundingRect calculation.
  45631. || this._buildGraphic(this._parsedXML);
  45632. usedRootMap.set(hostKey, svgGraphic); // PENDING: `nameMap` will not be supported until some real requirement come.
  45633. // `nameMap` can only be obtained from echarts option.
  45634. // The original `named` must not be modified.
  45635. // if (nameMap) {
  45636. // svgGraphic = extend({}, svgGraphic);
  45637. // svgGraphic.named = applyNameMap(svgGraphic.named, nameMap);
  45638. // }
  45639. return svgGraphic;
  45640. };
  45641. GeoSVGResource.prototype.freeGraphic = function (hostKey) {
  45642. var usedRootMap = this._usedGraphicMap;
  45643. var svgGraphic = usedRootMap.get(hostKey);
  45644. if (svgGraphic) {
  45645. usedRootMap.removeKey(hostKey);
  45646. this._freedGraphics.push(svgGraphic);
  45647. }
  45648. };
  45649. return GeoSVGResource;
  45650. }();
  45651. function setSilent(el) {
  45652. // Only named element has silent: false, other elements should
  45653. // act as background and has no user interaction.
  45654. el.silent = false; // text|tspan will be converted to group.
  45655. if (el.isGroup) {
  45656. el.traverse(function (child) {
  45657. child.silent = false;
  45658. });
  45659. }
  45660. }
  45661. function createRegions(named) {
  45662. var regions = [];
  45663. var regionsMap = createHashMap(); // Create resions only for the first graphic.
  45664. each(named, function (namedItem) {
  45665. // Region has feature to calculate center for tooltip or other features.
  45666. // If there is a <g name="xxx">, the center should be the center of the
  45667. // bounding rect of the g.
  45668. if (namedItem.namedFrom != null) {
  45669. return;
  45670. }
  45671. var region = new GeoSVGRegion(namedItem.name, namedItem.el); // PENDING: if `nameMap` supported, this region can not be mounted on
  45672. // `this`, but can only be created each time `load()` called.
  45673. regions.push(region); // PENDING: if multiple tag named with the same name, only one will be
  45674. // found by `_regionsMap`. `_regionsMap` is used to find a coordinate
  45675. // by name. We use `region.getCenter()` as the coordinate.
  45676. regionsMap.set(namedItem.name, region);
  45677. });
  45678. return {
  45679. regions: regions,
  45680. regionsMap: regionsMap
  45681. };
  45682. } // PENDING: `nameMap` will not be supported until some real requirement come.
  45683. // /**
  45684. // * Use the alias in geoNameMap.
  45685. // * The input `named` must not be modified.
  45686. // */
  45687. // function applyNameMap(
  45688. // named: GeoSVGGraphicRecord['named'],
  45689. // nameMap: NameMap
  45690. // ): GeoSVGGraphicRecord['named'] {
  45691. // const result = [] as GeoSVGGraphicRecord['named'];
  45692. // for (let i = 0; i < named.length; i++) {
  45693. // let regionGraphic = named[i];
  45694. // const name = regionGraphic.name;
  45695. // if (nameMap && nameMap.hasOwnProperty(name)) {
  45696. // regionGraphic = extend({}, regionGraphic);
  45697. // regionGraphic.name = name;
  45698. // }
  45699. // result.push(regionGraphic);
  45700. // }
  45701. // return result;
  45702. // }
  45703. var geoCoord = [126, 25];
  45704. var nanhaiName = '南海诸岛';
  45705. 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]]];
  45706. for (var i = 0; i < points$1.length; i++) {
  45707. for (var k = 0; k < points$1[i].length; k++) {
  45708. points$1[i][k][0] /= 10.5;
  45709. points$1[i][k][1] /= -10.5 / 0.75;
  45710. points$1[i][k][0] += geoCoord[0];
  45711. points$1[i][k][1] += geoCoord[1];
  45712. }
  45713. }
  45714. function fixNanhai(mapType, regions) {
  45715. if (mapType === 'china') {
  45716. for (var i = 0; i < regions.length; i++) {
  45717. // Already exists.
  45718. if (regions[i].name === nanhaiName) {
  45719. return;
  45720. }
  45721. }
  45722. regions.push(new GeoJSONRegion(nanhaiName, map(points$1, function (exterior) {
  45723. return {
  45724. type: 'polygon',
  45725. exterior: exterior
  45726. };
  45727. }), geoCoord));
  45728. }
  45729. }
  45730. /*
  45731. * Licensed to the Apache Software Foundation (ASF) under one
  45732. * or more contributor license agreements. See the NOTICE file
  45733. * distributed with this work for additional information
  45734. * regarding copyright ownership. The ASF licenses this file
  45735. * to you under the Apache License, Version 2.0 (the
  45736. * "License"); you may not use this file except in compliance
  45737. * with the License. You may obtain a copy of the License at
  45738. *
  45739. * http://www.apache.org/licenses/LICENSE-2.0
  45740. *
  45741. * Unless required by applicable law or agreed to in writing,
  45742. * software distributed under the License is distributed on an
  45743. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45744. * KIND, either express or implied. See the License for the
  45745. * specific language governing permissions and limitations
  45746. * under the License.
  45747. */
  45748. /**
  45749. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45750. */
  45751. /*
  45752. * Licensed to the Apache Software Foundation (ASF) under one
  45753. * or more contributor license agreements. See the NOTICE file
  45754. * distributed with this work for additional information
  45755. * regarding copyright ownership. The ASF licenses this file
  45756. * to you under the Apache License, Version 2.0 (the
  45757. * "License"); you may not use this file except in compliance
  45758. * with the License. You may obtain a copy of the License at
  45759. *
  45760. * http://www.apache.org/licenses/LICENSE-2.0
  45761. *
  45762. * Unless required by applicable law or agreed to in writing,
  45763. * software distributed under the License is distributed on an
  45764. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45765. * KIND, either express or implied. See the License for the
  45766. * specific language governing permissions and limitations
  45767. * under the License.
  45768. */
  45769. var coordsOffsetMap = {
  45770. '南海诸岛': [32, 80],
  45771. // 全国
  45772. '广东': [0, -10],
  45773. '香港': [10, 5],
  45774. '澳门': [-10, 10],
  45775. // '北京': [-10, 0],
  45776. '天津': [5, 5]
  45777. };
  45778. function fixTextCoords(mapType, region) {
  45779. if (mapType === 'china') {
  45780. var coordFix = coordsOffsetMap[region.name];
  45781. if (coordFix) {
  45782. var cp = region.getCenter();
  45783. cp[0] += coordFix[0] / 10.5;
  45784. cp[1] += -coordFix[1] / (10.5 / 0.75);
  45785. region.setCenter(cp);
  45786. }
  45787. }
  45788. }
  45789. /*
  45790. * Licensed to the Apache Software Foundation (ASF) under one
  45791. * or more contributor license agreements. See the NOTICE file
  45792. * distributed with this work for additional information
  45793. * regarding copyright ownership. The ASF licenses this file
  45794. * to you under the Apache License, Version 2.0 (the
  45795. * "License"); you may not use this file except in compliance
  45796. * with the License. You may obtain a copy of the License at
  45797. *
  45798. * http://www.apache.org/licenses/LICENSE-2.0
  45799. *
  45800. * Unless required by applicable law or agreed to in writing,
  45801. * software distributed under the License is distributed on an
  45802. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45803. * KIND, either express or implied. See the License for the
  45804. * specific language governing permissions and limitations
  45805. * under the License.
  45806. */
  45807. /**
  45808. * AUTO-GENERATED FILE. DO NOT MODIFY.
  45809. */
  45810. /*
  45811. * Licensed to the Apache Software Foundation (ASF) under one
  45812. * or more contributor license agreements. See the NOTICE file
  45813. * distributed with this work for additional information
  45814. * regarding copyright ownership. The ASF licenses this file
  45815. * to you under the Apache License, Version 2.0 (the
  45816. * "License"); you may not use this file except in compliance
  45817. * with the License. You may obtain a copy of the License at
  45818. *
  45819. * http://www.apache.org/licenses/LICENSE-2.0
  45820. *
  45821. * Unless required by applicable law or agreed to in writing,
  45822. * software distributed under the License is distributed on an
  45823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45824. * KIND, either express or implied. See the License for the
  45825. * specific language governing permissions and limitations
  45826. * under the License.
  45827. */
  45828. // Fix for 钓鱼岛
  45829. // let Region = require('../Region');
  45830. // let zrUtil = require('zrender/lib/core/util');
  45831. // let geoCoord = [126, 25];
  45832. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  45833. function fixDiaoyuIsland(mapType, region) {
  45834. if (mapType === 'china' && region.name === '台湾') {
  45835. region.geometries.push({
  45836. type: 'polygon',
  45837. exterior: points$2[0]
  45838. });
  45839. }
  45840. }
  45841. var DEFAULT_NAME_PROPERTY = 'name';
  45842. var GeoJSONResource =
  45843. /** @class */
  45844. function () {
  45845. function GeoJSONResource(mapName, geoJSON, specialAreas) {
  45846. this.type = 'geoJSON';
  45847. this._parsedMap = createHashMap();
  45848. this._mapName = mapName;
  45849. this._specialAreas = specialAreas; // PENDING: delay the parse to the first usage to rapid up the FMP?
  45850. this._geoJSON = parseInput(geoJSON);
  45851. }
  45852. /**
  45853. * @param nameMap can be null/undefined
  45854. * @param nameProperty can be null/undefined
  45855. */
  45856. GeoJSONResource.prototype.load = function (nameMap, nameProperty) {
  45857. nameProperty = nameProperty || DEFAULT_NAME_PROPERTY;
  45858. var parsed = this._parsedMap.get(nameProperty);
  45859. if (!parsed) {
  45860. var rawRegions = this._parseToRegions(nameProperty);
  45861. parsed = this._parsedMap.set(nameProperty, {
  45862. regions: rawRegions,
  45863. boundingRect: calculateBoundingRect(rawRegions)
  45864. });
  45865. }
  45866. var regionsMap = createHashMap();
  45867. var finalRegions = [];
  45868. each(parsed.regions, function (region) {
  45869. var regionName = region.name; // Try use the alias in geoNameMap
  45870. if (nameMap && hasOwn(nameMap, regionName)) {
  45871. region = region.cloneShallow(regionName = nameMap[regionName]);
  45872. }
  45873. finalRegions.push(region);
  45874. regionsMap.set(regionName, region);
  45875. });
  45876. return {
  45877. regions: finalRegions,
  45878. boundingRect: parsed.boundingRect || new BoundingRect(0, 0, 0, 0),
  45879. regionsMap: regionsMap
  45880. };
  45881. };
  45882. GeoJSONResource.prototype._parseToRegions = function (nameProperty) {
  45883. var mapName = this._mapName;
  45884. var geoJSON = this._geoJSON;
  45885. var rawRegions; // https://jsperf.com/try-catch-performance-overhead
  45886. try {
  45887. rawRegions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : [];
  45888. } catch (e) {
  45889. throw new Error('Invalid geoJson format\n' + e.message);
  45890. }
  45891. fixNanhai(mapName, rawRegions);
  45892. each(rawRegions, function (region) {
  45893. var regionName = region.name;
  45894. fixTextCoords(mapName, region);
  45895. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  45896. // to look better
  45897. var specialArea = this._specialAreas && this._specialAreas[regionName];
  45898. if (specialArea) {
  45899. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  45900. }
  45901. }, this);
  45902. return rawRegions;
  45903. };
  45904. /**
  45905. * Only for exporting to users.
  45906. * **MUST NOT** used internally.
  45907. */
  45908. GeoJSONResource.prototype.getMapForUser = function () {
  45909. return {
  45910. // For backward compatibility, use geoJson
  45911. // PENDING: it has been returning them without clone.
  45912. // do we need to avoid outsite modification?
  45913. geoJson: this._geoJSON,
  45914. geoJSON: this._geoJSON,
  45915. specialAreas: this._specialAreas
  45916. };
  45917. };
  45918. return GeoJSONResource;
  45919. }();
  45920. function calculateBoundingRect(regions) {
  45921. var rect;
  45922. for (var i = 0; i < regions.length; i++) {
  45923. var regionRect = regions[i].getBoundingRect();
  45924. rect = rect || regionRect.clone();
  45925. rect.union(regionRect);
  45926. }
  45927. return rect;
  45928. }
  45929. function parseInput(source) {
  45930. return !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  45931. }
  45932. var storage = createHashMap();
  45933. var geoSourceManager = {
  45934. /**
  45935. * Compatible with previous `echarts.registerMap`.
  45936. *
  45937. * @usage
  45938. * ```js
  45939. *
  45940. * echarts.registerMap('USA', geoJson, specialAreas);
  45941. *
  45942. * echarts.registerMap('USA', {
  45943. * geoJson: geoJson,
  45944. * specialAreas: {...}
  45945. * });
  45946. * echarts.registerMap('USA', {
  45947. * geoJSON: geoJson,
  45948. * specialAreas: {...}
  45949. * });
  45950. *
  45951. * echarts.registerMap('airport', {
  45952. * svg: svg
  45953. * }
  45954. * ```
  45955. *
  45956. * Note:
  45957. * Do not support that register multiple geoJSON or SVG
  45958. * one map name. Because different geoJSON and SVG have
  45959. * different unit. It's not easy to make sure how those
  45960. * units are mapping/normalize.
  45961. * If intending to use multiple geoJSON or SVG, we can
  45962. * use multiple geo coordinate system.
  45963. */
  45964. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  45965. if (rawDef.svg) {
  45966. var resource = new GeoSVGResource(mapName, rawDef.svg);
  45967. storage.set(mapName, resource);
  45968. } else {
  45969. // Recommend:
  45970. // echarts.registerMap('eu', { geoJSON: xxx, specialAreas: xxx });
  45971. // Backward compatibility:
  45972. // echarts.registerMap('eu', geoJSON, specialAreas);
  45973. // echarts.registerMap('eu', { geoJson: xxx, specialAreas: xxx });
  45974. var geoJSON = rawDef.geoJson || rawDef.geoJSON;
  45975. if (geoJSON && !rawDef.features) {
  45976. rawSpecialAreas = rawDef.specialAreas;
  45977. } else {
  45978. geoJSON = rawDef;
  45979. }
  45980. var resource = new GeoJSONResource(mapName, geoJSON, rawSpecialAreas);
  45981. storage.set(mapName, resource);
  45982. }
  45983. },
  45984. getGeoResource: function (mapName) {
  45985. return storage.get(mapName);
  45986. },
  45987. /**
  45988. * Only for exporting to users.
  45989. * **MUST NOT** used internally.
  45990. */
  45991. getMapForUser: function (mapName) {
  45992. var resource = storage.get(mapName); // Do not support return SVG until some real requirement come.
  45993. return resource && resource.type === 'geoJSON' && resource.getMapForUser();
  45994. },
  45995. load: function (mapName, nameMap, nameProperty) {
  45996. var resource = storage.get(mapName);
  45997. if (!resource) {
  45998. if ("development" !== 'production') {
  45999. console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.');
  46000. }
  46001. return;
  46002. }
  46003. return resource.load(nameMap, nameProperty);
  46004. }
  46005. };
  46006. /**
  46007. * Only these tags enable use `itemStyle` if they are named in SVG.
  46008. * Other tags like <text> <tspan> <image> might not suitable for `itemStyle`.
  46009. * They will not be considered to be styled until some requirements come.
  46010. */
  46011. var OPTION_STYLE_ENABLED_TAGS = ['rect', 'circle', 'line', 'ellipse', 'polygon', 'polyline', 'path'];
  46012. var OPTION_STYLE_ENABLED_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS);
  46013. var STATE_TRIGGER_TAG_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  46014. var LABEL_HOST_MAP = createHashMap(OPTION_STYLE_ENABLED_TAGS.concat(['g']));
  46015. var mapLabelRaw = makeInner();
  46016. function getFixedItemStyle(model) {
  46017. var itemStyle = model.getItemStyle();
  46018. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  46019. // they should both set areaColor and color to be null.
  46020. if (areaColor != null) {
  46021. itemStyle.fill = areaColor;
  46022. }
  46023. return itemStyle;
  46024. } // Only stroke can be used for line.
  46025. // Using fill in style if stroke not exits.
  46026. // TODO Not sure yet. Perhaps a separate `lineStyle`?
  46027. function fixLineStyle(styleHost) {
  46028. var style = styleHost.style;
  46029. if (style) {
  46030. style.stroke = style.stroke || style.fill;
  46031. style.fill = null;
  46032. }
  46033. }
  46034. var MapDraw =
  46035. /** @class */
  46036. function () {
  46037. function MapDraw(api) {
  46038. var group = new Group();
  46039. this.uid = getUID('ec_map_draw');
  46040. this._controller = new RoamController(api.getZr());
  46041. this._controllerHost = {
  46042. target: group
  46043. };
  46044. this.group = group;
  46045. group.add(this._regionsGroup = new Group());
  46046. group.add(this._svgGroup = new Group());
  46047. }
  46048. MapDraw.prototype.draw = function (mapOrGeoModel, ecModel, api, fromView, payload) {
  46049. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  46050. // will be assigned with map data. Other GEO model has no data.
  46051. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  46052. isGeo && ecModel.eachComponent({
  46053. mainType: 'series',
  46054. subType: 'map'
  46055. }, function (mapSeries) {
  46056. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  46057. data = mapSeries.getData();
  46058. }
  46059. });
  46060. var geo = mapOrGeoModel.coordinateSystem;
  46061. var regionsGroup = this._regionsGroup;
  46062. var group = this.group;
  46063. var transformInfo = geo.getTransformInfo();
  46064. var transformInfoRaw = transformInfo.raw;
  46065. var transformInfoRoam = transformInfo.roam; // No animation when first draw or in action
  46066. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  46067. if (isFirstDraw) {
  46068. group.x = transformInfoRoam.x;
  46069. group.y = transformInfoRoam.y;
  46070. group.scaleX = transformInfoRoam.scaleX;
  46071. group.scaleY = transformInfoRoam.scaleY;
  46072. group.dirty();
  46073. } else {
  46074. updateProps(group, transformInfoRoam, mapOrGeoModel);
  46075. }
  46076. var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0;
  46077. var viewBuildCtx = {
  46078. api: api,
  46079. geo: geo,
  46080. mapOrGeoModel: mapOrGeoModel,
  46081. data: data,
  46082. isVisualEncodedByVisualMap: isVisualEncodedByVisualMap,
  46083. isGeo: isGeo,
  46084. transformInfoRaw: transformInfoRaw
  46085. };
  46086. if (geo.resourceType === 'geoJSON') {
  46087. this._buildGeoJSON(viewBuildCtx);
  46088. } else if (geo.resourceType === 'geoSVG') {
  46089. this._buildSVG(viewBuildCtx);
  46090. }
  46091. this._updateController(mapOrGeoModel, ecModel, api);
  46092. this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
  46093. };
  46094. MapDraw.prototype._buildGeoJSON = function (viewBuildCtx) {
  46095. var regionsGroupByName = this._regionsGroupByName = createHashMap();
  46096. var regionsInfoByName = createHashMap();
  46097. var regionsGroup = this._regionsGroup;
  46098. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46099. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46100. var data = viewBuildCtx.data;
  46101. var projection = viewBuildCtx.geo.projection;
  46102. var projectionStream = projection && projection.stream;
  46103. function transformPoint(point, project) {
  46104. if (project) {
  46105. // projection may return null point.
  46106. point = project(point);
  46107. }
  46108. return point && [point[0] * transformInfoRaw.scaleX + transformInfoRaw.x, point[1] * transformInfoRaw.scaleY + transformInfoRaw.y];
  46109. }
  46110. function transformPolygonPoints(inPoints) {
  46111. var outPoints = []; // If projectionStream is provided. Use it instead of single point project.
  46112. var project = !projectionStream && projection && projection.project;
  46113. for (var i = 0; i < inPoints.length; ++i) {
  46114. var newPt = transformPoint(inPoints[i], project);
  46115. newPt && outPoints.push(newPt);
  46116. }
  46117. return outPoints;
  46118. }
  46119. function getPolyShape(points) {
  46120. return {
  46121. shape: {
  46122. points: transformPolygonPoints(points)
  46123. }
  46124. };
  46125. }
  46126. regionsGroup.removeAll(); // Only when the resource is GeoJSON, there is `geo.regions`.
  46127. each(viewBuildCtx.geo.regions, function (region) {
  46128. var regionName = region.name; // Consider in GeoJson properties.name may be duplicated, for example,
  46129. // there is multiple region named "United Kindom" or "France" (so many
  46130. // colonies). And it is not appropriate to merge them in geo, which
  46131. // will make them share the same label and bring trouble in label
  46132. // location calculation.
  46133. var regionGroup = regionsGroupByName.get(regionName);
  46134. var _a = regionsInfoByName.get(regionName) || {},
  46135. dataIdx = _a.dataIdx,
  46136. regionModel = _a.regionModel;
  46137. if (!regionGroup) {
  46138. regionGroup = regionsGroupByName.set(regionName, new Group());
  46139. regionsGroup.add(regionGroup);
  46140. dataIdx = data ? data.indexOfName(regionName) : null;
  46141. regionModel = viewBuildCtx.isGeo ? mapOrGeoModel.getRegionModel(regionName) : data ? data.getItemModel(dataIdx) : null;
  46142. regionsInfoByName.set(regionName, {
  46143. dataIdx: dataIdx,
  46144. regionModel: regionModel
  46145. });
  46146. }
  46147. var polygonSubpaths = [];
  46148. var polylineSubpaths = [];
  46149. each(region.geometries, function (geometry) {
  46150. // Polygon and MultiPolygon
  46151. if (geometry.type === 'polygon') {
  46152. var polys = [geometry.exterior].concat(geometry.interiors || []);
  46153. if (projectionStream) {
  46154. polys = projectPolys(polys, projectionStream);
  46155. }
  46156. each(polys, function (poly) {
  46157. polygonSubpaths.push(new Polygon(getPolyShape(poly)));
  46158. });
  46159. } // LineString and MultiLineString
  46160. else {
  46161. var points = geometry.points;
  46162. if (projectionStream) {
  46163. points = projectPolys(points, projectionStream, true);
  46164. }
  46165. each(points, function (points) {
  46166. polylineSubpaths.push(new Polyline(getPolyShape(points)));
  46167. });
  46168. }
  46169. });
  46170. var centerPt = transformPoint(region.getCenter(), projection && projection.project);
  46171. function createCompoundPath(subpaths, isLine) {
  46172. if (!subpaths.length) {
  46173. return;
  46174. }
  46175. var compoundPath = new CompoundPath({
  46176. culling: true,
  46177. segmentIgnoreThreshold: 1,
  46178. shape: {
  46179. paths: subpaths
  46180. }
  46181. });
  46182. regionGroup.add(compoundPath);
  46183. applyOptionStyleForRegion(viewBuildCtx, compoundPath, dataIdx, regionModel);
  46184. resetLabelForRegion(viewBuildCtx, compoundPath, regionName, regionModel, mapOrGeoModel, dataIdx, centerPt);
  46185. if (isLine) {
  46186. fixLineStyle(compoundPath);
  46187. each(compoundPath.states, fixLineStyle);
  46188. }
  46189. }
  46190. createCompoundPath(polygonSubpaths);
  46191. createCompoundPath(polylineSubpaths, true);
  46192. }); // Ensure children have been added to `regionGroup` before calling them.
  46193. regionsGroupByName.each(function (regionGroup, regionName) {
  46194. var _a = regionsInfoByName.get(regionName),
  46195. dataIdx = _a.dataIdx,
  46196. regionModel = _a.regionModel;
  46197. resetEventTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel, dataIdx);
  46198. resetTooltipForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46199. resetStateTriggerForRegion(viewBuildCtx, regionGroup, regionName, regionModel, mapOrGeoModel);
  46200. }, this);
  46201. };
  46202. MapDraw.prototype._buildSVG = function (viewBuildCtx) {
  46203. var mapName = viewBuildCtx.geo.map;
  46204. var transformInfoRaw = viewBuildCtx.transformInfoRaw;
  46205. this._svgGroup.x = transformInfoRaw.x;
  46206. this._svgGroup.y = transformInfoRaw.y;
  46207. this._svgGroup.scaleX = transformInfoRaw.scaleX;
  46208. this._svgGroup.scaleY = transformInfoRaw.scaleY;
  46209. if (this._svgResourceChanged(mapName)) {
  46210. this._freeSVG();
  46211. this._useSVG(mapName);
  46212. }
  46213. var svgDispatcherMap = this._svgDispatcherMap = createHashMap();
  46214. var focusSelf = false;
  46215. each(this._svgGraphicRecord.named, function (namedItem) {
  46216. // Note that we also allow different elements have the same name.
  46217. // For example, a glyph of a city and the label of the city have
  46218. // the same name and their tooltip info can be defined in a single
  46219. // region option.
  46220. var regionName = namedItem.name;
  46221. var mapOrGeoModel = viewBuildCtx.mapOrGeoModel;
  46222. var data = viewBuildCtx.data;
  46223. var svgNodeTagLower = namedItem.svgNodeTagLower;
  46224. var el = namedItem.el;
  46225. var dataIdx = data ? data.indexOfName(regionName) : null;
  46226. var regionModel = mapOrGeoModel.getRegionModel(regionName);
  46227. if (OPTION_STYLE_ENABLED_TAG_MAP.get(svgNodeTagLower) != null && el instanceof Displayable) {
  46228. applyOptionStyleForRegion(viewBuildCtx, el, dataIdx, regionModel);
  46229. }
  46230. if (el instanceof Displayable) {
  46231. el.culling = true;
  46232. } // We do not know how the SVG like so we'd better not to change z2.
  46233. // Otherwise it might bring some unexpected result. For example,
  46234. // an area hovered that make some inner city can not be clicked.
  46235. el.z2EmphasisLift = 0; // If self named:
  46236. if (!namedItem.namedFrom) {
  46237. // label should batter to be displayed based on the center of <g>
  46238. // if it is named rather than displayed on each child.
  46239. if (LABEL_HOST_MAP.get(svgNodeTagLower) != null) {
  46240. resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx, null);
  46241. }
  46242. resetEventTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, dataIdx);
  46243. resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46244. if (STATE_TRIGGER_TAG_MAP.get(svgNodeTagLower) != null) {
  46245. var focus_1 = resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel);
  46246. if (focus_1 === 'self') {
  46247. focusSelf = true;
  46248. }
  46249. var els = svgDispatcherMap.get(regionName) || svgDispatcherMap.set(regionName, []);
  46250. els.push(el);
  46251. }
  46252. }
  46253. }, this);
  46254. this._enableBlurEntireSVG(focusSelf, viewBuildCtx);
  46255. };
  46256. MapDraw.prototype._enableBlurEntireSVG = function (focusSelf, viewBuildCtx) {
  46257. // It's a little complicated to support blurring the entire geoSVG in series-map.
  46258. // So do not support it until some requirements come.
  46259. // At present, in series-map, only regions can be blurred.
  46260. if (focusSelf && viewBuildCtx.isGeo) {
  46261. var blurStyle = viewBuildCtx.mapOrGeoModel.getModel(['blur', 'itemStyle']).getItemStyle(); // Only support `opacity` here. Because not sure that other props are suitable for
  46262. // all of the elements generated by SVG (especially for Text/TSpan/Image/... ).
  46263. var opacity_1 = blurStyle.opacity;
  46264. this._svgGraphicRecord.root.traverse(function (el) {
  46265. if (!el.isGroup) {
  46266. // PENDING: clear those settings to SVG elements when `_freeSVG`.
  46267. // (Currently it happen not to be needed.)
  46268. setDefaultStateProxy(el);
  46269. var style = el.ensureState('blur').style || {}; // Do not overwrite the region style that already set from region option.
  46270. if (style.opacity == null && opacity_1 != null) {
  46271. style.opacity = opacity_1;
  46272. } // If `ensureState('blur').style = {}`, there will be default opacity.
  46273. // Enable `stateTransition` (animation).
  46274. el.ensureState('emphasis');
  46275. }
  46276. });
  46277. }
  46278. };
  46279. MapDraw.prototype.remove = function () {
  46280. this._regionsGroup.removeAll();
  46281. this._regionsGroupByName = null;
  46282. this._svgGroup.removeAll();
  46283. this._freeSVG();
  46284. this._controller.dispose();
  46285. this._controllerHost = null;
  46286. };
  46287. MapDraw.prototype.findHighDownDispatchers = function (name, geoModel) {
  46288. if (name == null) {
  46289. return [];
  46290. }
  46291. var geo = geoModel.coordinateSystem;
  46292. if (geo.resourceType === 'geoJSON') {
  46293. var regionsGroupByName = this._regionsGroupByName;
  46294. if (regionsGroupByName) {
  46295. var regionGroup = regionsGroupByName.get(name);
  46296. return regionGroup ? [regionGroup] : [];
  46297. }
  46298. } else if (geo.resourceType === 'geoSVG') {
  46299. return this._svgDispatcherMap && this._svgDispatcherMap.get(name) || [];
  46300. }
  46301. };
  46302. MapDraw.prototype._svgResourceChanged = function (mapName) {
  46303. return this._svgMapName !== mapName;
  46304. };
  46305. MapDraw.prototype._useSVG = function (mapName) {
  46306. var resource = geoSourceManager.getGeoResource(mapName);
  46307. if (resource && resource.type === 'geoSVG') {
  46308. var svgGraphic = resource.useGraphic(this.uid);
  46309. this._svgGroup.add(svgGraphic.root);
  46310. this._svgGraphicRecord = svgGraphic;
  46311. this._svgMapName = mapName;
  46312. }
  46313. };
  46314. MapDraw.prototype._freeSVG = function () {
  46315. var mapName = this._svgMapName;
  46316. if (mapName == null) {
  46317. return;
  46318. }
  46319. var resource = geoSourceManager.getGeoResource(mapName);
  46320. if (resource && resource.type === 'geoSVG') {
  46321. resource.freeGraphic(this.uid);
  46322. }
  46323. this._svgGraphicRecord = null;
  46324. this._svgDispatcherMap = null;
  46325. this._svgGroup.removeAll();
  46326. this._svgMapName = null;
  46327. };
  46328. MapDraw.prototype._updateController = function (mapOrGeoModel, ecModel, api) {
  46329. var geo = mapOrGeoModel.coordinateSystem;
  46330. var controller = this._controller;
  46331. var controllerHost = this._controllerHost; // @ts-ignore FIXME:TS
  46332. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  46333. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  46334. // @ts-ignore FIXME:TS
  46335. controller.enable(mapOrGeoModel.get('roam') || false);
  46336. var mainType = mapOrGeoModel.mainType;
  46337. function makeActionBase() {
  46338. var action = {
  46339. type: 'geoRoam',
  46340. componentType: mainType
  46341. };
  46342. action[mainType + 'Id'] = mapOrGeoModel.id;
  46343. return action;
  46344. }
  46345. controller.off('pan').on('pan', function (e) {
  46346. this._mouseDownFlag = false;
  46347. updateViewOnPan(controllerHost, e.dx, e.dy);
  46348. api.dispatchAction(extend(makeActionBase(), {
  46349. dx: e.dx,
  46350. dy: e.dy,
  46351. animation: {
  46352. duration: 0
  46353. }
  46354. }));
  46355. }, this);
  46356. controller.off('zoom').on('zoom', function (e) {
  46357. this._mouseDownFlag = false;
  46358. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  46359. api.dispatchAction(extend(makeActionBase(), {
  46360. zoom: e.scale,
  46361. originX: e.originX,
  46362. originY: e.originY,
  46363. animation: {
  46364. duration: 0
  46365. }
  46366. }));
  46367. }, this);
  46368. controller.setPointerChecker(function (e, x, y) {
  46369. return geo.containPoint([x, y]) && !onIrrelevantElement(e, api, mapOrGeoModel);
  46370. });
  46371. };
  46372. /**
  46373. * FIXME: this is a temporarily workaround.
  46374. * When `geoRoam` the elements need to be reset in `MapView['render']`, because the props like
  46375. * `ignore` might have been modified by `LabelManager`, and `LabelManager#addLabelsOfSeries`
  46376. * will subsequently cache `defaultAttr` like `ignore`. If do not do this reset, the modified
  46377. * props will have no chance to be restored.
  46378. * Note: This reset should be after `clearStates` in `renderSeries` because `useStates` in
  46379. * `renderSeries` will cache the modified `ignore` to `el._normalState`.
  46380. * TODO:
  46381. * Use clone/immutable in `LabelManager`?
  46382. */
  46383. MapDraw.prototype.resetForLabelLayout = function () {
  46384. this.group.traverse(function (el) {
  46385. var label = el.getTextContent();
  46386. if (label) {
  46387. label.ignore = mapLabelRaw(label).ignore;
  46388. }
  46389. });
  46390. };
  46391. MapDraw.prototype._updateMapSelectHandler = function (mapOrGeoModel, regionsGroup, api, fromView) {
  46392. var mapDraw = this;
  46393. regionsGroup.off('mousedown');
  46394. regionsGroup.off('click'); // @ts-ignore FIXME:TS resolve type conflict
  46395. if (mapOrGeoModel.get('selectedMode')) {
  46396. regionsGroup.on('mousedown', function () {
  46397. mapDraw._mouseDownFlag = true;
  46398. });
  46399. regionsGroup.on('click', function (e) {
  46400. if (!mapDraw._mouseDownFlag) {
  46401. return;
  46402. }
  46403. mapDraw._mouseDownFlag = false;
  46404. });
  46405. }
  46406. };
  46407. return MapDraw;
  46408. }();
  46409. function applyOptionStyleForRegion(viewBuildCtx, el, dataIndex, regionModel) {
  46410. // All of the path are using `itemStyle`, because
  46411. // (1) Some SVG also use fill on polyline (The different between
  46412. // polyline and polygon is "open" or "close" but not fill or not).
  46413. // (2) For the common props like opacity, if some use itemStyle
  46414. // and some use `lineStyle`, it might confuse users.
  46415. // (3) Most SVG use <path>, where can not detect whether to draw a "line"
  46416. // or a filled shape, so use `itemStyle` for <path>.
  46417. var normalStyleModel = regionModel.getModel('itemStyle');
  46418. var emphasisStyleModel = regionModel.getModel(['emphasis', 'itemStyle']);
  46419. var blurStyleModel = regionModel.getModel(['blur', 'itemStyle']);
  46420. var selectStyleModel = regionModel.getModel(['select', 'itemStyle']); // NOTE: DON'T use 'style' in visual when drawing map.
  46421. // This component is used for drawing underlying map for both geo component and map series.
  46422. var normalStyle = getFixedItemStyle(normalStyleModel);
  46423. var emphasisStyle = getFixedItemStyle(emphasisStyleModel);
  46424. var selectStyle = getFixedItemStyle(selectStyleModel);
  46425. var blurStyle = getFixedItemStyle(blurStyleModel); // Update the itemStyle if has data visual
  46426. var data = viewBuildCtx.data;
  46427. if (data) {
  46428. // Only visual color of each item will be used. It can be encoded by visualMap
  46429. // But visual color of series is used in symbol drawing
  46430. // Visual color for each series is for the symbol draw
  46431. var style = data.getItemVisual(dataIndex, 'style');
  46432. var decal = data.getItemVisual(dataIndex, 'decal');
  46433. if (viewBuildCtx.isVisualEncodedByVisualMap && style.fill) {
  46434. normalStyle.fill = style.fill;
  46435. }
  46436. if (decal) {
  46437. normalStyle.decal = createOrUpdatePatternFromDecal(decal, viewBuildCtx.api);
  46438. }
  46439. } // SVG text, tspan and image can be named but not supporeted
  46440. // to be styled by region option yet.
  46441. el.setStyle(normalStyle);
  46442. el.style.strokeNoScale = true;
  46443. el.ensureState('emphasis').style = emphasisStyle;
  46444. el.ensureState('select').style = selectStyle;
  46445. el.ensureState('blur').style = blurStyle; // Enable blur
  46446. setDefaultStateProxy(el);
  46447. }
  46448. function resetLabelForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46449. dataIdx, // If labelXY not provided, use `textConfig.position: 'inside'`
  46450. labelXY) {
  46451. var data = viewBuildCtx.data;
  46452. var isGeo = viewBuildCtx.isGeo;
  46453. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  46454. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  46455. // 1. In map series and data value is NaN
  46456. // 2. In geo component
  46457. // 3. Region has no series legendIcon, which will be add a showLabel flag in mapSymbolLayout
  46458. if (isGeo || isDataNaN || itemLayout && itemLayout.showLabel) {
  46459. var query = !isGeo ? dataIdx : regionName;
  46460. var labelFetcher = void 0; // Consider dataIdx not found.
  46461. if (!data || dataIdx >= 0) {
  46462. labelFetcher = mapOrGeoModel;
  46463. }
  46464. var specifiedTextOpt = labelXY ? {
  46465. normal: {
  46466. align: 'center',
  46467. verticalAlign: 'middle'
  46468. }
  46469. } : null; // Caveat: must be called after `setDefaultStateProxy(el);` called.
  46470. // because textContent will be assign with `el.stateProxy` inside.
  46471. setLabelStyle(el, getLabelStatesModels(regionModel), {
  46472. labelFetcher: labelFetcher,
  46473. labelDataIndex: query,
  46474. defaultText: regionName
  46475. }, specifiedTextOpt);
  46476. var textEl = el.getTextContent();
  46477. if (textEl) {
  46478. mapLabelRaw(textEl).ignore = textEl.ignore;
  46479. if (el.textConfig && labelXY) {
  46480. // Compute a relative offset based on the el bounding rect.
  46481. var rect = el.getBoundingRect().clone(); // Need to make sure the percent position base on the same rect in normal and
  46482. // emphasis state. Otherwise if using boundingRect of el, but the emphasis state
  46483. // has borderWidth (even 0.5px), the text position will be changed obviously
  46484. // if the position is very big like ['1234%', '1345%'].
  46485. el.textConfig.layoutRect = rect;
  46486. el.textConfig.position = [(labelXY[0] - rect.x) / rect.width * 100 + '%', (labelXY[1] - rect.y) / rect.height * 100 + '%'];
  46487. }
  46488. } // PENDING:
  46489. // If labelLayout is enabled (test/label-layout.html), el.dataIndex should be specified.
  46490. // But el.dataIndex is also used to determine whether user event should be triggered,
  46491. // where el.seriesIndex or el.dataModel must be specified. At present for a single el
  46492. // there is not case that "only label layout enabled but user event disabled", so here
  46493. // we depends `resetEventTriggerForRegion` to do the job of setting `el.dataIndex`.
  46494. el.disableLabelAnimation = true;
  46495. } else {
  46496. el.removeTextContent();
  46497. el.removeTextConfig();
  46498. el.disableLabelAnimation = null;
  46499. }
  46500. }
  46501. function resetEventTriggerForRegion(viewBuildCtx, eventTrigger, regionName, regionModel, mapOrGeoModel, // Exist only if `viewBuildCtx.data` exists.
  46502. dataIdx) {
  46503. // setItemGraphicEl, setHoverStyle after all polygons and labels
  46504. // are added to the regionGroup
  46505. if (viewBuildCtx.data) {
  46506. // FIXME: when series-map use a SVG map, and there are duplicated name specified
  46507. // on different SVG elements, after `data.setItemGraphicEl(...)`:
  46508. // (1) all of them will be mounted with `dataIndex`, `seriesIndex`, so that tooltip
  46509. // can be triggered only mouse hover. That's correct.
  46510. // (2) only the last element will be kept in `data`, so that if trigger tooltip
  46511. // by `dispatchAction`, only the last one can be found and triggered. That might be
  46512. // not correct. We will fix it in future if anyone demanding that.
  46513. viewBuildCtx.data.setItemGraphicEl(dataIdx, eventTrigger);
  46514. } // series-map will not trigger "geoselectchange" no matter it is
  46515. // based on a declared geo component. Because series-map will
  46516. // trigger "selectchange". If it trigger both the two events,
  46517. // If users call `chart.dispatchAction({type: 'toggleSelect'})`,
  46518. // it not easy to also fire event "geoselectchanged".
  46519. else {
  46520. // Package custom mouse event for geo component
  46521. getECData(eventTrigger).eventData = {
  46522. componentType: 'geo',
  46523. componentIndex: mapOrGeoModel.componentIndex,
  46524. geoIndex: mapOrGeoModel.componentIndex,
  46525. name: regionName,
  46526. region: regionModel && regionModel.option || {}
  46527. };
  46528. }
  46529. }
  46530. function resetTooltipForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46531. if (!viewBuildCtx.data) {
  46532. setTooltipConfig({
  46533. el: el,
  46534. componentModel: mapOrGeoModel,
  46535. itemName: regionName,
  46536. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46537. itemTooltipOption: regionModel.get('tooltip')
  46538. });
  46539. }
  46540. }
  46541. function resetStateTriggerForRegion(viewBuildCtx, el, regionName, regionModel, mapOrGeoModel) {
  46542. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46543. el.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46544. var emphasisModel = regionModel.getModel('emphasis');
  46545. var focus = emphasisModel.get('focus');
  46546. toggleHoverEmphasis(el, focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  46547. if (viewBuildCtx.isGeo) {
  46548. enableComponentHighDownFeatures(el, mapOrGeoModel, regionName);
  46549. }
  46550. return focus;
  46551. }
  46552. function projectPolys(rings, // Polygons include exterior and interiors. Or polylines.
  46553. createStream, isLine) {
  46554. var polygons = [];
  46555. var curPoly;
  46556. function startPolygon() {
  46557. curPoly = [];
  46558. }
  46559. function endPolygon() {
  46560. if (curPoly.length) {
  46561. polygons.push(curPoly);
  46562. curPoly = [];
  46563. }
  46564. }
  46565. var stream = createStream({
  46566. polygonStart: startPolygon,
  46567. polygonEnd: endPolygon,
  46568. lineStart: startPolygon,
  46569. lineEnd: endPolygon,
  46570. point: function (x, y) {
  46571. // May have NaN values from stream.
  46572. if (isFinite(x) && isFinite(y)) {
  46573. curPoly.push([x, y]);
  46574. }
  46575. },
  46576. sphere: function () {}
  46577. });
  46578. !isLine && stream.polygonStart();
  46579. each(rings, function (ring) {
  46580. stream.lineStart();
  46581. for (var i = 0; i < ring.length; i++) {
  46582. stream.point(ring[i][0], ring[i][1]);
  46583. }
  46584. stream.lineEnd();
  46585. });
  46586. !isLine && stream.polygonEnd();
  46587. return polygons;
  46588. }
  46589. // @ts-ignore FIXME:TS fix the "compatible with each other"?
  46590. var MapView =
  46591. /** @class */
  46592. function (_super) {
  46593. __extends(MapView, _super);
  46594. function MapView() {
  46595. var _this = _super !== null && _super.apply(this, arguments) || this;
  46596. _this.type = MapView.type;
  46597. return _this;
  46598. }
  46599. MapView.prototype.render = function (mapModel, ecModel, api, payload) {
  46600. // Not render if it is an toggleSelect action from self
  46601. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  46602. return;
  46603. }
  46604. var group = this.group;
  46605. group.removeAll();
  46606. if (mapModel.getHostGeoModel()) {
  46607. return;
  46608. }
  46609. if (this._mapDraw && payload && payload.type === 'geoRoam') {
  46610. this._mapDraw.resetForLabelLayout();
  46611. } // Not update map if it is an roam action from self
  46612. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  46613. if (mapModel.needsDrawMap) {
  46614. var mapDraw = this._mapDraw || new MapDraw(api);
  46615. group.add(mapDraw.group);
  46616. mapDraw.draw(mapModel, ecModel, api, this, payload);
  46617. this._mapDraw = mapDraw;
  46618. } else {
  46619. // Remove drawn map
  46620. this._mapDraw && this._mapDraw.remove();
  46621. this._mapDraw = null;
  46622. }
  46623. } else {
  46624. var mapDraw = this._mapDraw;
  46625. mapDraw && group.add(mapDraw.group);
  46626. }
  46627. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  46628. };
  46629. MapView.prototype.remove = function () {
  46630. this._mapDraw && this._mapDraw.remove();
  46631. this._mapDraw = null;
  46632. this.group.removeAll();
  46633. };
  46634. MapView.prototype.dispose = function () {
  46635. this._mapDraw && this._mapDraw.remove();
  46636. this._mapDraw = null;
  46637. };
  46638. MapView.prototype._renderSymbols = function (mapModel, ecModel, api) {
  46639. var originalData = mapModel.originalData;
  46640. var group = this.group;
  46641. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  46642. if (isNaN(value)) {
  46643. return;
  46644. }
  46645. var layout = originalData.getItemLayout(originalDataIndex);
  46646. if (!layout || !layout.point) {
  46647. // Not exists in map
  46648. return;
  46649. }
  46650. var point = layout.point;
  46651. var offset = layout.offset;
  46652. var circle = new Circle({
  46653. style: {
  46654. // Because the special of map draw.
  46655. // Which needs statistic of multiple series and draw on one map.
  46656. // And each series also need a symbol with legend color
  46657. //
  46658. // Layout and visual are put one the different data
  46659. // TODO
  46660. fill: mapModel.getData().getVisual('style').fill
  46661. },
  46662. shape: {
  46663. cx: point[0] + offset * 9,
  46664. cy: point[1],
  46665. r: 3
  46666. },
  46667. silent: true,
  46668. // Do not overlap the first series, on which labels are displayed.
  46669. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  46670. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  46671. // But consider the case:
  46672. // series: [
  46673. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  46674. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  46675. // ]
  46676. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  46677. // For backward compatibility, we follow the rule that render label `A` by the
  46678. // settings on series `X` but render label `C` by the settings on series `Y`.
  46679. if (!offset) {
  46680. var fullData = mapModel.mainSeries.getData();
  46681. var name_1 = originalData.getName(originalDataIndex);
  46682. var fullIndex_1 = fullData.indexOfName(name_1);
  46683. var itemModel = originalData.getItemModel(originalDataIndex);
  46684. var labelModel = itemModel.getModel('label');
  46685. var regionGroup = fullData.getItemGraphicEl(fullIndex_1); // `getFormattedLabel` needs to use `getData` inside. Here
  46686. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  46687. // FIXME
  46688. // If this is not the `mainSeries`, the item model (like label formatter)
  46689. // set on original data item will never get. But it has been working
  46690. // like that from the beginning, and this scenario is rarely encountered.
  46691. // So it won't be fixed until we have to.
  46692. setLabelStyle(circle, getLabelStatesModels(itemModel), {
  46693. labelFetcher: {
  46694. getFormattedLabel: function (idx, state) {
  46695. return mapModel.getFormattedLabel(fullIndex_1, state);
  46696. }
  46697. },
  46698. defaultText: name_1
  46699. });
  46700. circle.disableLabelAnimation = true;
  46701. if (!labelModel.get('position')) {
  46702. circle.setTextConfig({
  46703. position: 'bottom'
  46704. });
  46705. }
  46706. regionGroup.onHoverStateChange = function (toState) {
  46707. setStatesFlag(circle, toState);
  46708. };
  46709. }
  46710. group.add(circle);
  46711. });
  46712. };
  46713. MapView.type = 'map';
  46714. return MapView;
  46715. }(ChartView);
  46716. var MapSeries =
  46717. /** @class */
  46718. function (_super) {
  46719. __extends(MapSeries, _super);
  46720. function MapSeries() {
  46721. var _this = _super !== null && _super.apply(this, arguments) || this;
  46722. _this.type = MapSeries.type; // Only first map series of same mapType will drawMap.
  46723. _this.needsDrawMap = false; // Group of all map series with same mapType
  46724. _this.seriesGroup = [];
  46725. _this.getTooltipPosition = function (dataIndex) {
  46726. if (dataIndex != null) {
  46727. var name_1 = this.getData().getName(dataIndex);
  46728. var geo = this.coordinateSystem;
  46729. var region = geo.getRegion(name_1);
  46730. return region && geo.dataToPoint(region.getCenter());
  46731. }
  46732. };
  46733. return _this;
  46734. }
  46735. MapSeries.prototype.getInitialData = function (option) {
  46736. var data = createSeriesDataSimply(this, {
  46737. coordDimensions: ['value'],
  46738. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  46739. });
  46740. var dataNameMap = createHashMap();
  46741. var toAppendNames = [];
  46742. for (var i = 0, len = data.count(); i < len; i++) {
  46743. var name_2 = data.getName(i);
  46744. dataNameMap.set(name_2, true);
  46745. }
  46746. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  46747. each(geoSource.regions, function (region) {
  46748. var name = region.name;
  46749. if (!dataNameMap.get(name)) {
  46750. toAppendNames.push(name);
  46751. }
  46752. }); // Complete data with missing regions. The consequent processes (like visual
  46753. // map and render) can not be performed without a "full data". For example,
  46754. // find `dataIndex` by name.
  46755. data.appendValues([], toAppendNames);
  46756. return data;
  46757. };
  46758. /**
  46759. * If no host geo model, return null, which means using a
  46760. * inner exclusive geo model.
  46761. */
  46762. MapSeries.prototype.getHostGeoModel = function () {
  46763. var geoIndex = this.option.geoIndex;
  46764. return geoIndex != null ? this.ecModel.getComponent('geo', geoIndex) : null;
  46765. };
  46766. MapSeries.prototype.getMapType = function () {
  46767. return (this.getHostGeoModel() || this).option.map;
  46768. }; // _fillOption(option, mapName) {
  46769. // Shallow clone
  46770. // option = zrUtil.extend({}, option);
  46771. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  46772. // return option;
  46773. // }
  46774. MapSeries.prototype.getRawValue = function (dataIndex) {
  46775. // Use value stored in data instead because it is calculated from multiple series
  46776. // FIXME Provide all value of multiple series ?
  46777. var data = this.getData();
  46778. return data.get(data.mapDimension('value'), dataIndex);
  46779. };
  46780. /**
  46781. * Get model of region
  46782. */
  46783. MapSeries.prototype.getRegionModel = function (regionName) {
  46784. var data = this.getData();
  46785. return data.getItemModel(data.indexOfName(regionName));
  46786. };
  46787. /**
  46788. * Map tooltip formatter
  46789. */
  46790. MapSeries.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  46791. // FIXME orignalData and data is a bit confusing
  46792. var data = this.getData();
  46793. var value = this.getRawValue(dataIndex);
  46794. var name = data.getName(dataIndex);
  46795. var seriesGroup = this.seriesGroup;
  46796. var seriesNames = [];
  46797. for (var i = 0; i < seriesGroup.length; i++) {
  46798. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  46799. var valueDim = data.mapDimension('value');
  46800. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  46801. seriesNames.push(seriesGroup[i].name);
  46802. }
  46803. }
  46804. return createTooltipMarkup('section', {
  46805. header: seriesNames.join(', '),
  46806. noHeader: !seriesNames.length,
  46807. blocks: [createTooltipMarkup('nameValue', {
  46808. name: name,
  46809. value: value
  46810. })]
  46811. });
  46812. };
  46813. MapSeries.prototype.setZoom = function (zoom) {
  46814. this.option.zoom = zoom;
  46815. };
  46816. MapSeries.prototype.setCenter = function (center) {
  46817. this.option.center = center;
  46818. };
  46819. MapSeries.prototype.getLegendIcon = function (opt) {
  46820. var iconType = opt.icon || 'roundRect';
  46821. var icon = createSymbol(iconType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill);
  46822. icon.setStyle(opt.itemStyle); // Map do not use itemStyle.borderWidth as border width
  46823. icon.style.stroke = 'none'; // No rotation because no series visual symbol for map
  46824. if (iconType.indexOf('empty') > -1) {
  46825. icon.style.stroke = icon.style.fill;
  46826. icon.style.fill = '#fff';
  46827. icon.style.lineWidth = 2;
  46828. }
  46829. return icon;
  46830. };
  46831. MapSeries.type = 'series.map';
  46832. MapSeries.dependencies = ['geo'];
  46833. MapSeries.layoutMode = 'box';
  46834. MapSeries.defaultOption = {
  46835. // 一级层叠
  46836. // zlevel: 0,
  46837. // 二级层叠
  46838. z: 2,
  46839. coordinateSystem: 'geo',
  46840. // map should be explicitly specified since ec3.
  46841. map: '',
  46842. // If `geoIndex` is not specified, a exclusive geo will be
  46843. // created. Otherwise use the specified geo component, and
  46844. // `map` and `mapType` are ignored.
  46845. // geoIndex: 0,
  46846. // 'center' | 'left' | 'right' | 'x%' | {number}
  46847. left: 'center',
  46848. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  46849. top: 'center',
  46850. // right
  46851. // bottom
  46852. // width:
  46853. // height
  46854. // Aspect is width / height. Inited to be geoJson bbox aspect
  46855. // This parameter is used for scale this aspect
  46856. // Default value:
  46857. // for geoSVG source: 1,
  46858. // for geoJSON source: 0.75.
  46859. aspectScale: null,
  46860. // Layout with center and size
  46861. // If you want to put map in a fixed size box with right aspect ratio
  46862. // This two properties may be more convenient.
  46863. // layoutCenter: [50%, 50%]
  46864. // layoutSize: 100
  46865. showLegendSymbol: true,
  46866. // Define left-top, right-bottom coords to control view
  46867. // For example, [ [180, 90], [-180, -90] ],
  46868. // higher priority than center and zoom
  46869. boundingCoords: null,
  46870. // Default on center of map
  46871. center: null,
  46872. zoom: 1,
  46873. scaleLimit: null,
  46874. selectedMode: true,
  46875. label: {
  46876. show: false,
  46877. color: '#000'
  46878. },
  46879. // scaleLimit: null,
  46880. itemStyle: {
  46881. borderWidth: 0.5,
  46882. borderColor: '#444',
  46883. areaColor: '#eee'
  46884. },
  46885. emphasis: {
  46886. label: {
  46887. show: true,
  46888. color: 'rgb(100,0,0)'
  46889. },
  46890. itemStyle: {
  46891. areaColor: 'rgba(255,215,0,0.8)'
  46892. }
  46893. },
  46894. select: {
  46895. label: {
  46896. show: true,
  46897. color: 'rgb(100,0,0)'
  46898. },
  46899. itemStyle: {
  46900. color: 'rgba(255,215,0,0.8)'
  46901. }
  46902. },
  46903. nameProperty: 'name'
  46904. };
  46905. return MapSeries;
  46906. }(SeriesModel);
  46907. function dataStatistics(datas, statisticType) {
  46908. var dataNameMap = {};
  46909. each(datas, function (data) {
  46910. data.each(data.mapDimension('value'), function (value, idx) {
  46911. // Add prefix to avoid conflict with Object.prototype.
  46912. var mapKey = 'ec-' + data.getName(idx);
  46913. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  46914. if (!isNaN(value)) {
  46915. dataNameMap[mapKey].push(value);
  46916. }
  46917. });
  46918. });
  46919. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  46920. var mapKey = 'ec-' + datas[0].getName(idx);
  46921. var sum = 0;
  46922. var min = Infinity;
  46923. var max = -Infinity;
  46924. var len = dataNameMap[mapKey].length;
  46925. for (var i = 0; i < len; i++) {
  46926. min = Math.min(min, dataNameMap[mapKey][i]);
  46927. max = Math.max(max, dataNameMap[mapKey][i]);
  46928. sum += dataNameMap[mapKey][i];
  46929. }
  46930. var result;
  46931. if (statisticType === 'min') {
  46932. result = min;
  46933. } else if (statisticType === 'max') {
  46934. result = max;
  46935. } else if (statisticType === 'average') {
  46936. result = sum / len;
  46937. } else {
  46938. result = sum;
  46939. }
  46940. return len === 0 ? NaN : result;
  46941. });
  46942. }
  46943. function mapDataStatistic(ecModel) {
  46944. var seriesGroups = {};
  46945. ecModel.eachSeriesByType('map', function (seriesModel) {
  46946. var hostGeoModel = seriesModel.getHostGeoModel();
  46947. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  46948. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  46949. });
  46950. each(seriesGroups, function (seriesList, key) {
  46951. var data = dataStatistics(map(seriesList, function (seriesModel) {
  46952. return seriesModel.getData();
  46953. }), seriesList[0].get('mapValueCalculation'));
  46954. for (var i = 0; i < seriesList.length; i++) {
  46955. seriesList[i].originalData = seriesList[i].getData();
  46956. } // FIXME Put where?
  46957. for (var i = 0; i < seriesList.length; i++) {
  46958. seriesList[i].seriesGroup = seriesList;
  46959. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  46960. seriesList[i].setData(data.cloneShallow());
  46961. seriesList[i].mainSeries = seriesList[0];
  46962. }
  46963. });
  46964. }
  46965. function mapSymbolLayout(ecModel) {
  46966. var processedMapType = {};
  46967. ecModel.eachSeriesByType('map', function (mapSeries) {
  46968. var mapType = mapSeries.getMapType();
  46969. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  46970. return;
  46971. }
  46972. var mapSymbolOffsets = {};
  46973. each(mapSeries.seriesGroup, function (subMapSeries) {
  46974. var geo = subMapSeries.coordinateSystem;
  46975. var data = subMapSeries.originalData;
  46976. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  46977. data.each(data.mapDimension('value'), function (value, idx) {
  46978. var name = data.getName(idx);
  46979. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  46980. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  46981. // not be drawn. So here must validate if value is NaN.
  46982. if (!region || isNaN(value)) {
  46983. return;
  46984. }
  46985. var offset = mapSymbolOffsets[name] || 0;
  46986. var point = geo.dataToPoint(region.getCenter());
  46987. mapSymbolOffsets[name] = offset + 1;
  46988. data.setItemLayout(idx, {
  46989. point: point,
  46990. offset: offset
  46991. });
  46992. });
  46993. }
  46994. }); // Show label of those region not has legendIcon (which is offset 0)
  46995. var data = mapSeries.getData();
  46996. data.each(function (idx) {
  46997. var name = data.getName(idx);
  46998. var layout = data.getItemLayout(idx) || {};
  46999. layout.showLabel = !mapSymbolOffsets[name];
  47000. data.setItemLayout(idx, layout);
  47001. });
  47002. processedMapType[mapType] = true;
  47003. });
  47004. }
  47005. var v2ApplyTransform = applyTransform;
  47006. var View =
  47007. /** @class */
  47008. function (_super) {
  47009. __extends(View, _super);
  47010. function View(name) {
  47011. var _this = _super.call(this) || this;
  47012. _this.type = 'view';
  47013. _this.dimensions = ['x', 'y'];
  47014. /**
  47015. * Represents the transform brought by roam/zoom.
  47016. * If `View['_viewRect']` applies roam transform,
  47017. * we can get the final displayed rect.
  47018. */
  47019. _this._roamTransformable = new Transformable();
  47020. /**
  47021. * Represents the transform from `View['_rect']` to `View['_viewRect']`.
  47022. */
  47023. _this._rawTransformable = new Transformable();
  47024. _this.name = name;
  47025. return _this;
  47026. }
  47027. View.prototype.setBoundingRect = function (x, y, width, height) {
  47028. this._rect = new BoundingRect(x, y, width, height);
  47029. return this._rect;
  47030. };
  47031. /**
  47032. * @return {module:zrender/core/BoundingRect}
  47033. */
  47034. View.prototype.getBoundingRect = function () {
  47035. return this._rect;
  47036. };
  47037. View.prototype.setViewRect = function (x, y, width, height) {
  47038. this._transformTo(x, y, width, height);
  47039. this._viewRect = new BoundingRect(x, y, width, height);
  47040. };
  47041. /**
  47042. * Transformed to particular position and size
  47043. */
  47044. View.prototype._transformTo = function (x, y, width, height) {
  47045. var rect = this.getBoundingRect();
  47046. var rawTransform = this._rawTransformable;
  47047. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47048. var rawParent = rawTransform.parent;
  47049. rawTransform.parent = null;
  47050. rawTransform.decomposeTransform();
  47051. rawTransform.parent = rawParent;
  47052. this._updateTransform();
  47053. };
  47054. /**
  47055. * Set center of view
  47056. */
  47057. View.prototype.setCenter = function (centerCoord, api) {
  47058. if (!centerCoord) {
  47059. return;
  47060. }
  47061. this._center = [parsePercent$1(centerCoord[0], api.getWidth()), parsePercent$1(centerCoord[1], api.getHeight())];
  47062. this._updateCenterAndZoom();
  47063. };
  47064. View.prototype.setZoom = function (zoom) {
  47065. zoom = zoom || 1;
  47066. var zoomLimit = this.zoomLimit;
  47067. if (zoomLimit) {
  47068. if (zoomLimit.max != null) {
  47069. zoom = Math.min(zoomLimit.max, zoom);
  47070. }
  47071. if (zoomLimit.min != null) {
  47072. zoom = Math.max(zoomLimit.min, zoom);
  47073. }
  47074. }
  47075. this._zoom = zoom;
  47076. this._updateCenterAndZoom();
  47077. };
  47078. /**
  47079. * Get default center without roam
  47080. */
  47081. View.prototype.getDefaultCenter = function () {
  47082. // Rect before any transform
  47083. var rawRect = this.getBoundingRect();
  47084. var cx = rawRect.x + rawRect.width / 2;
  47085. var cy = rawRect.y + rawRect.height / 2;
  47086. return [cx, cy];
  47087. };
  47088. View.prototype.getCenter = function () {
  47089. return this._center || this.getDefaultCenter();
  47090. };
  47091. View.prototype.getZoom = function () {
  47092. return this._zoom || 1;
  47093. };
  47094. View.prototype.getRoamTransform = function () {
  47095. return this._roamTransformable.getLocalTransform();
  47096. };
  47097. /**
  47098. * Remove roam
  47099. */
  47100. View.prototype._updateCenterAndZoom = function () {
  47101. // Must update after view transform updated
  47102. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  47103. var roamTransform = this._roamTransformable;
  47104. var defaultCenter = this.getDefaultCenter();
  47105. var center = this.getCenter();
  47106. var zoom = this.getZoom();
  47107. center = applyTransform([], center, rawTransformMatrix);
  47108. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  47109. roamTransform.originX = center[0];
  47110. roamTransform.originY = center[1];
  47111. roamTransform.x = defaultCenter[0] - center[0];
  47112. roamTransform.y = defaultCenter[1] - center[1];
  47113. roamTransform.scaleX = roamTransform.scaleY = zoom;
  47114. this._updateTransform();
  47115. };
  47116. /**
  47117. * Update transform props on `this` based on the current
  47118. * `this._roamTransformable` and `this._rawTransformable`.
  47119. */
  47120. View.prototype._updateTransform = function () {
  47121. var roamTransformable = this._roamTransformable;
  47122. var rawTransformable = this._rawTransformable;
  47123. rawTransformable.parent = roamTransformable;
  47124. roamTransformable.updateTransform();
  47125. rawTransformable.updateTransform();
  47126. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  47127. this._rawTransform = rawTransformable.getLocalTransform();
  47128. this.invTransform = this.invTransform || [];
  47129. invert(this.invTransform, this.transform);
  47130. this.decomposeTransform();
  47131. };
  47132. View.prototype.getTransformInfo = function () {
  47133. var rawTransformable = this._rawTransformable;
  47134. var roamTransformable = this._roamTransformable; // Because roamTransformabel has `originX/originY` modified,
  47135. // but the caller of `getTransformInfo` can not handle `originX/originY`,
  47136. // so need to recalculate them.
  47137. var dummyTransformable = new Transformable();
  47138. dummyTransformable.transform = roamTransformable.transform;
  47139. dummyTransformable.decomposeTransform();
  47140. return {
  47141. roam: {
  47142. x: dummyTransformable.x,
  47143. y: dummyTransformable.y,
  47144. scaleX: dummyTransformable.scaleX,
  47145. scaleY: dummyTransformable.scaleY
  47146. },
  47147. raw: {
  47148. x: rawTransformable.x,
  47149. y: rawTransformable.y,
  47150. scaleX: rawTransformable.scaleX,
  47151. scaleY: rawTransformable.scaleY
  47152. }
  47153. };
  47154. };
  47155. View.prototype.getViewRect = function () {
  47156. return this._viewRect;
  47157. };
  47158. /**
  47159. * Get view rect after roam transform
  47160. */
  47161. View.prototype.getViewRectAfterRoam = function () {
  47162. var rect = this.getBoundingRect().clone();
  47163. rect.applyTransform(this.transform);
  47164. return rect;
  47165. };
  47166. /**
  47167. * Convert a single (lon, lat) data item to (x, y) point.
  47168. */
  47169. View.prototype.dataToPoint = function (data, noRoam, out) {
  47170. var transform = noRoam ? this._rawTransform : this.transform;
  47171. out = out || [];
  47172. return transform ? v2ApplyTransform(out, data, transform) : copy(out, data);
  47173. };
  47174. /**
  47175. * Convert a (x, y) point to (lon, lat) data
  47176. */
  47177. View.prototype.pointToData = function (point) {
  47178. var invTransform = this.invTransform;
  47179. return invTransform ? v2ApplyTransform([], point, invTransform) : [point[0], point[1]];
  47180. };
  47181. View.prototype.convertToPixel = function (ecModel, finder, value) {
  47182. var coordSys = getCoordSys(finder);
  47183. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47184. };
  47185. View.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47186. var coordSys = getCoordSys(finder);
  47187. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47188. };
  47189. /**
  47190. * @implements
  47191. */
  47192. View.prototype.containPoint = function (point) {
  47193. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  47194. };
  47195. View.dimensions = ['x', 'y'];
  47196. return View;
  47197. }(Transformable);
  47198. function getCoordSys(finder) {
  47199. var seriesModel = finder.seriesModel;
  47200. return seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  47201. }
  47202. var GEO_DEFAULT_PARAMS = {
  47203. 'geoJSON': {
  47204. aspectScale: 0.75,
  47205. invertLongitute: true
  47206. },
  47207. 'geoSVG': {
  47208. aspectScale: 1,
  47209. invertLongitute: false
  47210. }
  47211. };
  47212. var geo2DDimensions = ['lng', 'lat'];
  47213. var Geo =
  47214. /** @class */
  47215. function (_super) {
  47216. __extends(Geo, _super);
  47217. function Geo(name, map, opt) {
  47218. var _this = _super.call(this, name) || this;
  47219. _this.dimensions = geo2DDimensions;
  47220. _this.type = 'geo'; // Only store specified name coord via `addGeoCoord`.
  47221. _this._nameCoordMap = createHashMap();
  47222. _this.map = map;
  47223. var projection = opt.projection;
  47224. var source = geoSourceManager.load(map, opt.nameMap, opt.nameProperty);
  47225. var resource = geoSourceManager.getGeoResource(map);
  47226. var resourceType = _this.resourceType = resource ? resource.type : null;
  47227. var regions = _this.regions = source.regions;
  47228. var defaultParams = GEO_DEFAULT_PARAMS[resource.type];
  47229. _this._regionsMap = source.regionsMap;
  47230. _this.regions = source.regions;
  47231. if ("development" !== 'production' && projection) {
  47232. // Do some check
  47233. if (resourceType === 'geoSVG') {
  47234. if ("development" !== 'production') {
  47235. warn("Map " + map + " with SVG source can't use projection. Only GeoJSON source supports projection.");
  47236. }
  47237. projection = null;
  47238. }
  47239. if (!(projection.project && projection.unproject)) {
  47240. if ("development" !== 'production') {
  47241. warn('project and unproject must be both provided in the projeciton.');
  47242. }
  47243. projection = null;
  47244. }
  47245. }
  47246. _this.projection = projection;
  47247. var boundingRect;
  47248. if (projection) {
  47249. // Can't reuse the raw bounding rect
  47250. for (var i = 0; i < regions.length; i++) {
  47251. var regionRect = regions[i].getBoundingRect(projection);
  47252. boundingRect = boundingRect || regionRect.clone();
  47253. boundingRect.union(regionRect);
  47254. }
  47255. } else {
  47256. boundingRect = source.boundingRect;
  47257. }
  47258. _this.setBoundingRect(boundingRect.x, boundingRect.y, boundingRect.width, boundingRect.height); // aspectScale and invertLongitute actually is the parameters default raw projection.
  47259. // So we ignore them if projection is given.
  47260. // Ignore default aspect scale if projection exits.
  47261. _this.aspectScale = projection ? 1 : retrieve2(opt.aspectScale, defaultParams.aspectScale); // Not invert longitude if projection exits.
  47262. _this._invertLongitute = projection ? false : defaultParams.invertLongitute;
  47263. return _this;
  47264. }
  47265. Geo.prototype._transformTo = function (x, y, width, height) {
  47266. var rect = this.getBoundingRect();
  47267. var invertLongitute = this._invertLongitute;
  47268. rect = rect.clone();
  47269. if (invertLongitute) {
  47270. // Longitude is inverted.
  47271. rect.y = -rect.y - rect.height;
  47272. }
  47273. var rawTransformable = this._rawTransformable;
  47274. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  47275. var rawParent = rawTransformable.parent;
  47276. rawTransformable.parent = null;
  47277. rawTransformable.decomposeTransform();
  47278. rawTransformable.parent = rawParent;
  47279. if (invertLongitute) {
  47280. rawTransformable.scaleY = -rawTransformable.scaleY;
  47281. }
  47282. this._updateTransform();
  47283. };
  47284. Geo.prototype.getRegion = function (name) {
  47285. return this._regionsMap.get(name);
  47286. };
  47287. Geo.prototype.getRegionByCoord = function (coord) {
  47288. var regions = this.regions;
  47289. for (var i = 0; i < regions.length; i++) {
  47290. var region = regions[i];
  47291. if (region.type === 'geoJSON' && region.contain(coord)) {
  47292. return regions[i];
  47293. }
  47294. }
  47295. };
  47296. /**
  47297. * Add geoCoord for indexing by name
  47298. */
  47299. Geo.prototype.addGeoCoord = function (name, geoCoord) {
  47300. this._nameCoordMap.set(name, geoCoord);
  47301. };
  47302. /**
  47303. * Get geoCoord by name
  47304. */
  47305. Geo.prototype.getGeoCoord = function (name) {
  47306. var region = this._regionsMap.get(name); // Calculate center only on demand.
  47307. return this._nameCoordMap.get(name) || region && region.getCenter();
  47308. };
  47309. Geo.prototype.dataToPoint = function (data, noRoam, out) {
  47310. if (isString(data)) {
  47311. // Map area name to geoCoord
  47312. data = this.getGeoCoord(data);
  47313. }
  47314. if (data) {
  47315. var projection = this.projection;
  47316. if (projection) {
  47317. // projection may return null point.
  47318. data = projection.project(data);
  47319. }
  47320. return data && this.projectedToPoint(data, noRoam, out);
  47321. }
  47322. };
  47323. Geo.prototype.pointToData = function (point) {
  47324. var projection = this.projection;
  47325. if (projection) {
  47326. // projection may return null point.
  47327. point = projection.unproject(point);
  47328. }
  47329. return point && this.pointToProjected(point);
  47330. };
  47331. /**
  47332. * Point to projected data. Same with pointToData when projection is used.
  47333. */
  47334. Geo.prototype.pointToProjected = function (point) {
  47335. return _super.prototype.pointToData.call(this, point);
  47336. };
  47337. Geo.prototype.projectedToPoint = function (projected, noRoam, out) {
  47338. return _super.prototype.dataToPoint.call(this, projected, noRoam, out);
  47339. };
  47340. Geo.prototype.convertToPixel = function (ecModel, finder, value) {
  47341. var coordSys = getCoordSys$1(finder);
  47342. return coordSys === this ? coordSys.dataToPoint(value) : null;
  47343. };
  47344. Geo.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  47345. var coordSys = getCoordSys$1(finder);
  47346. return coordSys === this ? coordSys.pointToData(pixel) : null;
  47347. };
  47348. return Geo;
  47349. }(View);
  47350. mixin(Geo, View);
  47351. function getCoordSys$1(finder) {
  47352. var geoModel = finder.geoModel;
  47353. var seriesModel = finder.seriesModel;
  47354. return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map series.
  47355. || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null;
  47356. }
  47357. /**
  47358. * Resize method bound to the geo
  47359. */
  47360. function resizeGeo(geoModel, api) {
  47361. var boundingCoords = geoModel.get('boundingCoords');
  47362. if (boundingCoords != null) {
  47363. var leftTop_1 = boundingCoords[0];
  47364. var rightBottom_1 = boundingCoords[1];
  47365. if (!(isFinite(leftTop_1[0]) && isFinite(leftTop_1[1]) && isFinite(rightBottom_1[0]) && isFinite(rightBottom_1[1]))) {
  47366. if ("development" !== 'production') {
  47367. console.error('Invalid boundingCoords');
  47368. }
  47369. } else {
  47370. // Sample around the lng/lat rect and use projection to calculate actual bounding rect.
  47371. var projection_1 = this.projection;
  47372. if (projection_1) {
  47373. var xMin = leftTop_1[0];
  47374. var yMin = leftTop_1[1];
  47375. var xMax = rightBottom_1[0];
  47376. var yMax = rightBottom_1[1];
  47377. leftTop_1 = [Infinity, Infinity];
  47378. rightBottom_1 = [-Infinity, -Infinity]; // TODO better way?
  47379. var sampleLine = function (x0, y0, x1, y1) {
  47380. var dx = x1 - x0;
  47381. var dy = y1 - y0;
  47382. for (var i = 0; i <= 100; i++) {
  47383. var p = i / 100;
  47384. var pt = projection_1.project([x0 + dx * p, y0 + dy * p]);
  47385. min(leftTop_1, leftTop_1, pt);
  47386. max(rightBottom_1, rightBottom_1, pt);
  47387. }
  47388. }; // Top
  47389. sampleLine(xMin, yMin, xMax, yMin); // Right
  47390. sampleLine(xMax, yMin, xMax, yMax); // Bottom
  47391. sampleLine(xMax, yMax, xMin, yMax); // Left
  47392. sampleLine(xMin, yMax, xMax, yMin);
  47393. }
  47394. this.setBoundingRect(leftTop_1[0], leftTop_1[1], rightBottom_1[0] - leftTop_1[0], rightBottom_1[1] - leftTop_1[1]);
  47395. }
  47396. }
  47397. var rect = this.getBoundingRect();
  47398. var centerOption = geoModel.get('layoutCenter');
  47399. var sizeOption = geoModel.get('layoutSize');
  47400. var viewWidth = api.getWidth();
  47401. var viewHeight = api.getHeight();
  47402. var aspect = rect.width / rect.height * this.aspectScale;
  47403. var useCenterAndSize = false;
  47404. var center;
  47405. var size;
  47406. if (centerOption && sizeOption) {
  47407. center = [parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight)];
  47408. size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight));
  47409. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  47410. useCenterAndSize = true;
  47411. } else {
  47412. if ("development" !== 'production') {
  47413. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  47414. }
  47415. }
  47416. }
  47417. var viewRect;
  47418. if (useCenterAndSize) {
  47419. viewRect = {};
  47420. if (aspect > 1) {
  47421. // Width is same with size
  47422. viewRect.width = size;
  47423. viewRect.height = size / aspect;
  47424. } else {
  47425. viewRect.height = size;
  47426. viewRect.width = size * aspect;
  47427. }
  47428. viewRect.y = center[1] - viewRect.height / 2;
  47429. viewRect.x = center[0] - viewRect.width / 2;
  47430. } else {
  47431. // Use left/top/width/height
  47432. var boxLayoutOption = geoModel.getBoxLayoutParams();
  47433. boxLayoutOption.aspect = aspect;
  47434. viewRect = getLayoutRect(boxLayoutOption, {
  47435. width: viewWidth,
  47436. height: viewHeight
  47437. });
  47438. }
  47439. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  47440. this.setCenter(geoModel.get('center'), api);
  47441. this.setZoom(geoModel.get('zoom'));
  47442. } // Back compat for ECharts2, where the coord map is set on map series:
  47443. // {type: 'map', geoCoord: {'cityA': [116.46,39.92], 'cityA': [119.12,24.61]}},
  47444. function setGeoCoords(geo, model) {
  47445. each(model.get('geoCoord'), function (geoCoord, name) {
  47446. geo.addGeoCoord(name, geoCoord);
  47447. });
  47448. }
  47449. var GeoCreator =
  47450. /** @class */
  47451. function () {
  47452. function GeoCreator() {
  47453. // For deciding which dimensions to use when creating list data
  47454. this.dimensions = geo2DDimensions;
  47455. }
  47456. GeoCreator.prototype.create = function (ecModel, api) {
  47457. var geoList = [];
  47458. function getCommonGeoProperties(model) {
  47459. return {
  47460. nameProperty: model.get('nameProperty'),
  47461. aspectScale: model.get('aspectScale'),
  47462. projection: model.get('projection')
  47463. };
  47464. } // FIXME Create each time may be slow
  47465. ecModel.eachComponent('geo', function (geoModel, idx) {
  47466. var mapName = geoModel.get('map');
  47467. var geo = new Geo(mapName + idx, mapName, extend({
  47468. nameMap: geoModel.get('nameMap')
  47469. }, getCommonGeoProperties(geoModel)));
  47470. geo.zoomLimit = geoModel.get('scaleLimit');
  47471. geoList.push(geo); // setGeoCoords(geo, geoModel);
  47472. geoModel.coordinateSystem = geo;
  47473. geo.model = geoModel; // Inject resize method
  47474. geo.resize = resizeGeo;
  47475. geo.resize(geoModel, api);
  47476. });
  47477. ecModel.eachSeries(function (seriesModel) {
  47478. var coordSys = seriesModel.get('coordinateSystem');
  47479. if (coordSys === 'geo') {
  47480. var geoIndex = seriesModel.get('geoIndex') || 0;
  47481. seriesModel.coordinateSystem = geoList[geoIndex];
  47482. }
  47483. }); // If has map series
  47484. var mapModelGroupBySeries = {};
  47485. ecModel.eachSeriesByType('map', function (seriesModel) {
  47486. if (!seriesModel.getHostGeoModel()) {
  47487. var mapType = seriesModel.getMapType();
  47488. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  47489. mapModelGroupBySeries[mapType].push(seriesModel);
  47490. }
  47491. });
  47492. each(mapModelGroupBySeries, function (mapSeries, mapType) {
  47493. var nameMapList = map(mapSeries, function (singleMapSeries) {
  47494. return singleMapSeries.get('nameMap');
  47495. });
  47496. var geo = new Geo(mapType, mapType, extend({
  47497. nameMap: mergeAll(nameMapList)
  47498. }, getCommonGeoProperties(mapSeries[0])));
  47499. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  47500. return singleMapSeries.get('scaleLimit');
  47501. }));
  47502. geoList.push(geo); // Inject resize method
  47503. geo.resize = resizeGeo;
  47504. geo.resize(mapSeries[0], api);
  47505. each(mapSeries, function (singleMapSeries) {
  47506. singleMapSeries.coordinateSystem = geo;
  47507. setGeoCoords(geo, singleMapSeries);
  47508. });
  47509. });
  47510. return geoList;
  47511. };
  47512. /**
  47513. * Fill given regions array
  47514. */
  47515. GeoCreator.prototype.getFilledRegions = function (originRegionArr, mapName, nameMap, nameProperty) {
  47516. // Not use the original
  47517. var regionsArr = (originRegionArr || []).slice();
  47518. var dataNameMap = createHashMap();
  47519. for (var i = 0; i < regionsArr.length; i++) {
  47520. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  47521. }
  47522. var source = geoSourceManager.load(mapName, nameMap, nameProperty);
  47523. each(source.regions, function (region) {
  47524. var name = region.name;
  47525. !dataNameMap.get(name) && regionsArr.push({
  47526. name: name
  47527. });
  47528. });
  47529. return regionsArr;
  47530. };
  47531. return GeoCreator;
  47532. }();
  47533. var geoCreator = new GeoCreator();
  47534. var GeoModel =
  47535. /** @class */
  47536. function (_super) {
  47537. __extends(GeoModel, _super);
  47538. function GeoModel() {
  47539. var _this = _super !== null && _super.apply(this, arguments) || this;
  47540. _this.type = GeoModel.type;
  47541. return _this;
  47542. }
  47543. GeoModel.prototype.init = function (option, parentModel, ecModel) {
  47544. var source = geoSourceManager.getGeoResource(option.map);
  47545. if (source && source.type === 'geoJSON') {
  47546. var itemStyle = option.itemStyle = option.itemStyle || {};
  47547. if (!('color' in itemStyle)) {
  47548. itemStyle.color = '#eee';
  47549. }
  47550. }
  47551. this.mergeDefaultAndTheme(option, ecModel); // Default label emphasis `show`
  47552. defaultEmphasis(option, 'label', ['show']);
  47553. };
  47554. GeoModel.prototype.optionUpdated = function () {
  47555. var _this = this;
  47556. var option = this.option;
  47557. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap, option.nameProperty);
  47558. var selectedMap = {};
  47559. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  47560. var regionName = regionOpt.name;
  47561. if (regionName) {
  47562. optionModelMap.set(regionName, new Model(regionOpt, _this, _this.ecModel));
  47563. if (regionOpt.selected) {
  47564. selectedMap[regionName] = true;
  47565. }
  47566. }
  47567. return optionModelMap;
  47568. }, createHashMap());
  47569. if (!option.selectedMap) {
  47570. option.selectedMap = selectedMap;
  47571. }
  47572. };
  47573. /**
  47574. * Get model of region.
  47575. */
  47576. GeoModel.prototype.getRegionModel = function (name) {
  47577. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  47578. };
  47579. /**
  47580. * Format label
  47581. * @param name Region name
  47582. */
  47583. GeoModel.prototype.getFormattedLabel = function (name, status) {
  47584. var regionModel = this.getRegionModel(name);
  47585. var formatter = status === 'normal' ? regionModel.get(['label', 'formatter']) : regionModel.get(['emphasis', 'label', 'formatter']);
  47586. var params = {
  47587. name: name
  47588. };
  47589. if (isFunction(formatter)) {
  47590. params.status = status;
  47591. return formatter(params);
  47592. } else if (isString(formatter)) {
  47593. return formatter.replace('{a}', name != null ? name : '');
  47594. }
  47595. };
  47596. GeoModel.prototype.setZoom = function (zoom) {
  47597. this.option.zoom = zoom;
  47598. };
  47599. GeoModel.prototype.setCenter = function (center) {
  47600. this.option.center = center;
  47601. }; // PENGING If selectedMode is null ?
  47602. GeoModel.prototype.select = function (name) {
  47603. var option = this.option;
  47604. var selectedMode = option.selectedMode;
  47605. if (!selectedMode) {
  47606. return;
  47607. }
  47608. if (selectedMode !== 'multiple') {
  47609. option.selectedMap = null;
  47610. }
  47611. var selectedMap = option.selectedMap || (option.selectedMap = {});
  47612. selectedMap[name] = true;
  47613. };
  47614. GeoModel.prototype.unSelect = function (name) {
  47615. var selectedMap = this.option.selectedMap;
  47616. if (selectedMap) {
  47617. selectedMap[name] = false;
  47618. }
  47619. };
  47620. GeoModel.prototype.toggleSelected = function (name) {
  47621. this[this.isSelected(name) ? 'unSelect' : 'select'](name);
  47622. };
  47623. GeoModel.prototype.isSelected = function (name) {
  47624. var selectedMap = this.option.selectedMap;
  47625. return !!(selectedMap && selectedMap[name]);
  47626. };
  47627. GeoModel.type = 'geo';
  47628. GeoModel.layoutMode = 'box';
  47629. GeoModel.defaultOption = {
  47630. // zlevel: 0,
  47631. z: 0,
  47632. show: true,
  47633. left: 'center',
  47634. top: 'center',
  47635. // Default value:
  47636. // for geoSVG source: 1,
  47637. // for geoJSON source: 0.75.
  47638. aspectScale: null,
  47639. // /// Layout with center and size
  47640. // If you want to put map in a fixed size box with right aspect ratio
  47641. // This two properties may be more convenient
  47642. // layoutCenter: [50%, 50%]
  47643. // layoutSize: 100
  47644. silent: false,
  47645. // Map type
  47646. map: '',
  47647. // Define left-top, right-bottom coords to control view
  47648. // For example, [ [180, 90], [-180, -90] ]
  47649. boundingCoords: null,
  47650. // Default on center of map
  47651. center: null,
  47652. zoom: 1,
  47653. scaleLimit: null,
  47654. // selectedMode: false
  47655. label: {
  47656. show: false,
  47657. color: '#000'
  47658. },
  47659. itemStyle: {
  47660. borderWidth: 0.5,
  47661. borderColor: '#444' // Default color:
  47662. // + geoJSON: #eee
  47663. // + geoSVG: null (use SVG original `fill`)
  47664. // color: '#eee'
  47665. },
  47666. emphasis: {
  47667. label: {
  47668. show: true,
  47669. color: 'rgb(100,0,0)'
  47670. },
  47671. itemStyle: {
  47672. color: 'rgba(255,215,0,0.8)'
  47673. }
  47674. },
  47675. select: {
  47676. label: {
  47677. show: true,
  47678. color: 'rgb(100,0,0)'
  47679. },
  47680. itemStyle: {
  47681. color: 'rgba(255,215,0,0.8)'
  47682. }
  47683. },
  47684. regions: [] // tooltip: {
  47685. // show: false
  47686. // }
  47687. };
  47688. return GeoModel;
  47689. }(ComponentModel);
  47690. /*
  47691. * Licensed to the Apache Software Foundation (ASF) under one
  47692. * or more contributor license agreements. See the NOTICE file
  47693. * distributed with this work for additional information
  47694. * regarding copyright ownership. The ASF licenses this file
  47695. * to you under the Apache License, Version 2.0 (the
  47696. * "License"); you may not use this file except in compliance
  47697. * with the License. You may obtain a copy of the License at
  47698. *
  47699. * http://www.apache.org/licenses/LICENSE-2.0
  47700. *
  47701. * Unless required by applicable law or agreed to in writing,
  47702. * software distributed under the License is distributed on an
  47703. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47704. * KIND, either express or implied. See the License for the
  47705. * specific language governing permissions and limitations
  47706. * under the License.
  47707. */
  47708. /**
  47709. * AUTO-GENERATED FILE. DO NOT MODIFY.
  47710. */
  47711. /*
  47712. * Licensed to the Apache Software Foundation (ASF) under one
  47713. * or more contributor license agreements. See the NOTICE file
  47714. * distributed with this work for additional information
  47715. * regarding copyright ownership. The ASF licenses this file
  47716. * to you under the Apache License, Version 2.0 (the
  47717. * "License"); you may not use this file except in compliance
  47718. * with the License. You may obtain a copy of the License at
  47719. *
  47720. * http://www.apache.org/licenses/LICENSE-2.0
  47721. *
  47722. * Unless required by applicable law or agreed to in writing,
  47723. * software distributed under the License is distributed on an
  47724. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47725. * KIND, either express or implied. See the License for the
  47726. * specific language governing permissions and limitations
  47727. * under the License.
  47728. */
  47729. function getCenterCoord(view, point) {
  47730. // Use projected coord as center because it's linear.
  47731. return view.pointToProjected ? view.pointToProjected(point) : view.pointToData(point);
  47732. }
  47733. function updateCenterAndZoom(view, payload, zoomLimit, api) {
  47734. var previousZoom = view.getZoom();
  47735. var center = view.getCenter();
  47736. var zoom = payload.zoom;
  47737. var point = view.projectedToPoint ? view.projectedToPoint(center) : view.dataToPoint(center);
  47738. if (payload.dx != null && payload.dy != null) {
  47739. point[0] -= payload.dx;
  47740. point[1] -= payload.dy;
  47741. view.setCenter(getCenterCoord(view, point), api);
  47742. }
  47743. if (zoom != null) {
  47744. if (zoomLimit) {
  47745. var zoomMin = zoomLimit.min || 0;
  47746. var zoomMax = zoomLimit.max || Infinity;
  47747. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  47748. } // Zoom on given point(originX, originY)
  47749. view.scaleX *= zoom;
  47750. view.scaleY *= zoom;
  47751. var fixX = (payload.originX - view.x) * (zoom - 1);
  47752. var fixY = (payload.originY - view.y) * (zoom - 1);
  47753. view.x -= fixX;
  47754. view.y -= fixY;
  47755. view.updateTransform(); // Get the new center
  47756. view.setCenter(getCenterCoord(view, point), api);
  47757. view.setZoom(zoom * previousZoom);
  47758. }
  47759. return {
  47760. center: view.getCenter(),
  47761. zoom: view.getZoom()
  47762. };
  47763. }
  47764. var GeoView =
  47765. /** @class */
  47766. function (_super) {
  47767. __extends(GeoView, _super);
  47768. function GeoView() {
  47769. var _this = _super !== null && _super.apply(this, arguments) || this;
  47770. _this.type = GeoView.type;
  47771. _this.focusBlurEnabled = true;
  47772. return _this;
  47773. }
  47774. GeoView.prototype.init = function (ecModel, api) {
  47775. this._api = api;
  47776. };
  47777. GeoView.prototype.render = function (geoModel, ecModel, api, payload) {
  47778. this._model = geoModel;
  47779. if (!geoModel.get('show')) {
  47780. this._mapDraw && this._mapDraw.remove();
  47781. this._mapDraw = null;
  47782. return;
  47783. }
  47784. if (!this._mapDraw) {
  47785. this._mapDraw = new MapDraw(api);
  47786. }
  47787. var mapDraw = this._mapDraw;
  47788. mapDraw.draw(geoModel, ecModel, api, this, payload);
  47789. mapDraw.group.on('click', this._handleRegionClick, this);
  47790. mapDraw.group.silent = geoModel.get('silent');
  47791. this.group.add(mapDraw.group);
  47792. this.updateSelectStatus(geoModel, ecModel, api);
  47793. };
  47794. GeoView.prototype._handleRegionClick = function (e) {
  47795. var eventData;
  47796. findEventDispatcher(e.target, function (current) {
  47797. return (eventData = getECData(current).eventData) != null;
  47798. }, true);
  47799. if (eventData) {
  47800. this._api.dispatchAction({
  47801. type: 'geoToggleSelect',
  47802. geoId: this._model.id,
  47803. name: eventData.name
  47804. });
  47805. }
  47806. };
  47807. GeoView.prototype.updateSelectStatus = function (model, ecModel, api) {
  47808. var _this = this;
  47809. this._mapDraw.group.traverse(function (node) {
  47810. var eventData = getECData(node).eventData;
  47811. if (eventData) {
  47812. _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node); // No need to traverse children.
  47813. return true;
  47814. }
  47815. });
  47816. };
  47817. GeoView.prototype.findHighDownDispatchers = function (name) {
  47818. return this._mapDraw && this._mapDraw.findHighDownDispatchers(name, this._model);
  47819. };
  47820. GeoView.prototype.dispose = function () {
  47821. this._mapDraw && this._mapDraw.remove();
  47822. };
  47823. GeoView.type = 'geo';
  47824. return GeoView;
  47825. }(ComponentView);
  47826. function registerMap$1(mapName, geoJson, specialAreas) {
  47827. geoSourceManager.registerMap(mapName, geoJson, specialAreas);
  47828. }
  47829. function install$9(registers) {
  47830. registers.registerCoordinateSystem('geo', geoCreator);
  47831. registers.registerComponentModel(GeoModel);
  47832. registers.registerComponentView(GeoView);
  47833. registers.registerImpl('registerMap', registerMap$1);
  47834. registers.registerImpl('getMap', function (mapName) {
  47835. return geoSourceManager.getMapForUser(mapName);
  47836. });
  47837. function makeAction(method, actionInfo) {
  47838. actionInfo.update = 'geo:updateSelectStatus';
  47839. registers.registerAction(actionInfo, function (payload, ecModel) {
  47840. var selected = {};
  47841. var allSelected = [];
  47842. ecModel.eachComponent({
  47843. mainType: 'geo',
  47844. query: payload
  47845. }, function (geoModel) {
  47846. geoModel[method](payload.name);
  47847. var geo = geoModel.coordinateSystem;
  47848. each(geo.regions, function (region) {
  47849. selected[region.name] = geoModel.isSelected(region.name) || false;
  47850. }); // Notice: there might be duplicated name in different regions.
  47851. var names = [];
  47852. each(selected, function (v, name) {
  47853. selected[name] && names.push(name);
  47854. });
  47855. allSelected.push({
  47856. geoIndex: geoModel.componentIndex,
  47857. // Use singular, the same naming convention as the event `selectchanged`.
  47858. name: names
  47859. });
  47860. });
  47861. return {
  47862. selected: selected,
  47863. allSelected: allSelected,
  47864. name: payload.name
  47865. };
  47866. });
  47867. }
  47868. makeAction('toggleSelected', {
  47869. type: 'geoToggleSelect',
  47870. event: 'geoselectchanged'
  47871. });
  47872. makeAction('select', {
  47873. type: 'geoSelect',
  47874. event: 'geoselected'
  47875. });
  47876. makeAction('unSelect', {
  47877. type: 'geoUnSelect',
  47878. event: 'geounselected'
  47879. });
  47880. /**
  47881. * @payload
  47882. * @property {string} [componentType=series]
  47883. * @property {number} [dx]
  47884. * @property {number} [dy]
  47885. * @property {number} [zoom]
  47886. * @property {number} [originX]
  47887. * @property {number} [originY]
  47888. */
  47889. registers.registerAction({
  47890. type: 'geoRoam',
  47891. event: 'geoRoam',
  47892. update: 'updateTransform'
  47893. }, function (payload, ecModel, api) {
  47894. var componentType = payload.componentType || 'series';
  47895. ecModel.eachComponent({
  47896. mainType: componentType,
  47897. query: payload
  47898. }, function (componentModel) {
  47899. var geo = componentModel.coordinateSystem;
  47900. if (geo.type !== 'geo') {
  47901. return;
  47902. }
  47903. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'), api);
  47904. componentModel.setCenter && componentModel.setCenter(res.center);
  47905. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  47906. // So the center and zoom must be in sync. Include the series not selected by legend
  47907. if (componentType === 'series') {
  47908. each(componentModel.seriesGroup, function (seriesModel) {
  47909. seriesModel.setCenter(res.center);
  47910. seriesModel.setZoom(res.zoom);
  47911. });
  47912. }
  47913. });
  47914. });
  47915. }
  47916. function install$a(registers) {
  47917. use(install$9);
  47918. registers.registerChartView(MapView);
  47919. registers.registerSeriesModel(MapSeries);
  47920. registers.registerLayout(mapSymbolLayout);
  47921. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  47922. createLegacyDataSelectAction('map', registers.registerAction);
  47923. }
  47924. /**
  47925. * Initialize all computational message for following algorithm.
  47926. */
  47927. function init$2(inRoot) {
  47928. var root = inRoot;
  47929. root.hierNode = {
  47930. defaultAncestor: null,
  47931. ancestor: root,
  47932. prelim: 0,
  47933. modifier: 0,
  47934. change: 0,
  47935. shift: 0,
  47936. i: 0,
  47937. thread: null
  47938. };
  47939. var nodes = [root];
  47940. var node;
  47941. var children;
  47942. while (node = nodes.pop()) {
  47943. // jshint ignore:line
  47944. children = node.children;
  47945. if (node.isExpand && children.length) {
  47946. var n = children.length;
  47947. for (var i = n - 1; i >= 0; i--) {
  47948. var child = children[i];
  47949. child.hierNode = {
  47950. defaultAncestor: null,
  47951. ancestor: child,
  47952. prelim: 0,
  47953. modifier: 0,
  47954. change: 0,
  47955. shift: 0,
  47956. i: i,
  47957. thread: null
  47958. };
  47959. nodes.push(child);
  47960. }
  47961. }
  47962. }
  47963. }
  47964. /**
  47965. * The implementation of this function was originally copied from "d3.js"
  47966. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47967. * with some modifications made for this program.
  47968. * See the license statement at the head of this file.
  47969. *
  47970. * Computes a preliminary x coordinate for node. Before that, this function is
  47971. * applied recursively to the children of node, as well as the function
  47972. * apportion(). After spacing out the children by calling executeShifts(), the
  47973. * node is placed to the midpoint of its outermost children.
  47974. */
  47975. function firstWalk(node, separation) {
  47976. var children = node.isExpand ? node.children : [];
  47977. var siblings = node.parentNode.children;
  47978. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  47979. if (children.length) {
  47980. executeShifts(node);
  47981. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  47982. if (subtreeW) {
  47983. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47984. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  47985. } else {
  47986. node.hierNode.prelim = midPoint;
  47987. }
  47988. } else if (subtreeW) {
  47989. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  47990. }
  47991. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  47992. }
  47993. /**
  47994. * The implementation of this function was originally copied from "d3.js"
  47995. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  47996. * with some modifications made for this program.
  47997. * See the license statement at the head of this file.
  47998. *
  47999. * Computes all real x-coordinates by summing up the modifiers recursively.
  48000. */
  48001. function secondWalk(node) {
  48002. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  48003. node.setLayout({
  48004. x: nodeX
  48005. }, true);
  48006. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  48007. }
  48008. function separation(cb) {
  48009. return arguments.length ? cb : defaultSeparation;
  48010. }
  48011. /**
  48012. * Transform the common coordinate to radial coordinate.
  48013. */
  48014. function radialCoordinate(rad, r) {
  48015. rad -= Math.PI / 2;
  48016. return {
  48017. x: r * Math.cos(rad),
  48018. y: r * Math.sin(rad)
  48019. };
  48020. }
  48021. /**
  48022. * Get the layout position of the whole view.
  48023. */
  48024. function getViewRect$1(seriesModel, api) {
  48025. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  48026. width: api.getWidth(),
  48027. height: api.getHeight()
  48028. });
  48029. }
  48030. /**
  48031. * All other shifts, applied to the smaller subtrees between w- and w+, are
  48032. * performed by this function.
  48033. *
  48034. * The implementation of this function was originally copied from "d3.js"
  48035. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48036. * with some modifications made for this program.
  48037. * See the license statement at the head of this file.
  48038. */
  48039. function executeShifts(node) {
  48040. var children = node.children;
  48041. var n = children.length;
  48042. var shift = 0;
  48043. var change = 0;
  48044. while (--n >= 0) {
  48045. var child = children[n];
  48046. child.hierNode.prelim += shift;
  48047. child.hierNode.modifier += shift;
  48048. change += child.hierNode.change;
  48049. shift += child.hierNode.shift + change;
  48050. }
  48051. }
  48052. /**
  48053. * The implementation of this function was originally copied from "d3.js"
  48054. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48055. * with some modifications made for this program.
  48056. * See the license statement at the head of this file.
  48057. *
  48058. * The core of the algorithm. Here, a new subtree is combined with the
  48059. * previous subtrees. Threads are used to traverse the inside and outside
  48060. * contours of the left and right subtree up to the highest common level.
  48061. * Whenever two nodes of the inside contours conflict, we compute the left
  48062. * one of the greatest uncommon ancestors using the function nextAncestor()
  48063. * and call moveSubtree() to shift the subtree and prepare the shifts of
  48064. * smaller subtrees. Finally, we add a new thread (if necessary).
  48065. */
  48066. function apportion(subtreeV, subtreeW, ancestor, separation) {
  48067. if (subtreeW) {
  48068. var nodeOutRight = subtreeV;
  48069. var nodeInRight = subtreeV;
  48070. var nodeOutLeft = nodeInRight.parentNode.children[0];
  48071. var nodeInLeft = subtreeW;
  48072. var sumOutRight = nodeOutRight.hierNode.modifier;
  48073. var sumInRight = nodeInRight.hierNode.modifier;
  48074. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  48075. var sumInLeft = nodeInLeft.hierNode.modifier;
  48076. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  48077. nodeOutRight = nextRight(nodeOutRight);
  48078. nodeOutLeft = nextLeft(nodeOutLeft);
  48079. nodeOutRight.hierNode.ancestor = subtreeV;
  48080. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  48081. if (shift > 0) {
  48082. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  48083. sumInRight += shift;
  48084. sumOutRight += shift;
  48085. }
  48086. sumInLeft += nodeInLeft.hierNode.modifier;
  48087. sumInRight += nodeInRight.hierNode.modifier;
  48088. sumOutRight += nodeOutRight.hierNode.modifier;
  48089. sumOutLeft += nodeOutLeft.hierNode.modifier;
  48090. }
  48091. if (nodeInLeft && !nextRight(nodeOutRight)) {
  48092. nodeOutRight.hierNode.thread = nodeInLeft;
  48093. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  48094. }
  48095. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  48096. nodeOutLeft.hierNode.thread = nodeInRight;
  48097. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  48098. ancestor = subtreeV;
  48099. }
  48100. }
  48101. return ancestor;
  48102. }
  48103. /**
  48104. * This function is used to traverse the right contour of a subtree.
  48105. * It returns the rightmost child of node or the thread of node. The function
  48106. * returns null if and only if node is on the highest depth of its subtree.
  48107. */
  48108. function nextRight(node) {
  48109. var children = node.children;
  48110. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  48111. }
  48112. /**
  48113. * This function is used to traverse the left contour of a subtree (or a subforest).
  48114. * It returns the leftmost child of node or the thread of node. The function
  48115. * returns null if and only if node is on the highest depth of its subtree.
  48116. */
  48117. function nextLeft(node) {
  48118. var children = node.children;
  48119. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  48120. }
  48121. /**
  48122. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  48123. * Otherwise, returns the specified ancestor.
  48124. */
  48125. function nextAncestor(nodeInLeft, node, ancestor) {
  48126. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  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. * Shifts the current subtree rooted at wr.
  48135. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  48136. */
  48137. function moveSubtree(wl, wr, shift) {
  48138. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  48139. wr.hierNode.change -= change;
  48140. wr.hierNode.shift += shift;
  48141. wr.hierNode.modifier += shift;
  48142. wr.hierNode.prelim += shift;
  48143. wl.hierNode.change += change;
  48144. }
  48145. /**
  48146. * The implementation of this function was originally copied from "d3.js"
  48147. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  48148. * with some modifications made for this program.
  48149. * See the license statement at the head of this file.
  48150. */
  48151. function defaultSeparation(node1, node2) {
  48152. return node1.parentNode === node2.parentNode ? 1 : 2;
  48153. }
  48154. var TreeEdgeShape =
  48155. /** @class */
  48156. function () {
  48157. function TreeEdgeShape() {
  48158. this.parentPoint = [];
  48159. this.childPoints = [];
  48160. }
  48161. return TreeEdgeShape;
  48162. }();
  48163. var TreePath =
  48164. /** @class */
  48165. function (_super) {
  48166. __extends(TreePath, _super);
  48167. function TreePath(opts) {
  48168. return _super.call(this, opts) || this;
  48169. }
  48170. TreePath.prototype.getDefaultStyle = function () {
  48171. return {
  48172. stroke: '#000',
  48173. fill: null
  48174. };
  48175. };
  48176. TreePath.prototype.getDefaultShape = function () {
  48177. return new TreeEdgeShape();
  48178. };
  48179. TreePath.prototype.buildPath = function (ctx, shape) {
  48180. var childPoints = shape.childPoints;
  48181. var childLen = childPoints.length;
  48182. var parentPoint = shape.parentPoint;
  48183. var firstChildPos = childPoints[0];
  48184. var lastChildPos = childPoints[childLen - 1];
  48185. if (childLen === 1) {
  48186. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48187. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  48188. return;
  48189. }
  48190. var orient = shape.orient;
  48191. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  48192. var otherDim = 1 - forkDim;
  48193. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  48194. var tmpPoint = [];
  48195. tmpPoint[forkDim] = parentPoint[forkDim];
  48196. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  48197. ctx.moveTo(parentPoint[0], parentPoint[1]);
  48198. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48199. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  48200. tmpPoint[forkDim] = firstChildPos[forkDim];
  48201. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48202. tmpPoint[forkDim] = lastChildPos[forkDim];
  48203. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48204. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  48205. for (var i = 1; i < childLen - 1; i++) {
  48206. var point = childPoints[i];
  48207. ctx.moveTo(point[0], point[1]);
  48208. tmpPoint[forkDim] = point[forkDim];
  48209. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  48210. }
  48211. };
  48212. return TreePath;
  48213. }(Path);
  48214. var TreeView =
  48215. /** @class */
  48216. function (_super) {
  48217. __extends(TreeView, _super);
  48218. function TreeView() {
  48219. var _this = _super !== null && _super.apply(this, arguments) || this;
  48220. _this.type = TreeView.type;
  48221. _this._mainGroup = new Group();
  48222. return _this;
  48223. }
  48224. TreeView.prototype.init = function (ecModel, api) {
  48225. this._controller = new RoamController(api.getZr());
  48226. this._controllerHost = {
  48227. target: this.group
  48228. };
  48229. this.group.add(this._mainGroup);
  48230. };
  48231. TreeView.prototype.render = function (seriesModel, ecModel, api) {
  48232. var data = seriesModel.getData();
  48233. var layoutInfo = seriesModel.layoutInfo;
  48234. var group = this._mainGroup;
  48235. var layout = seriesModel.get('layout');
  48236. if (layout === 'radial') {
  48237. group.x = layoutInfo.x + layoutInfo.width / 2;
  48238. group.y = layoutInfo.y + layoutInfo.height / 2;
  48239. } else {
  48240. group.x = layoutInfo.x;
  48241. group.y = layoutInfo.y;
  48242. }
  48243. this._updateViewCoordSys(seriesModel, api);
  48244. this._updateController(seriesModel, ecModel, api);
  48245. var oldData = this._data;
  48246. data.diff(oldData).add(function (newIdx) {
  48247. if (symbolNeedsDraw$1(data, newIdx)) {
  48248. // Create node and edge
  48249. updateNode(data, newIdx, null, group, seriesModel);
  48250. }
  48251. }).update(function (newIdx, oldIdx) {
  48252. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  48253. if (!symbolNeedsDraw$1(data, newIdx)) {
  48254. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48255. return;
  48256. } // Update node and edge
  48257. updateNode(data, newIdx, symbolEl, group, seriesModel);
  48258. }).remove(function (oldIdx) {
  48259. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  48260. // node haven't been initialized with a symbol element,
  48261. // you can't found it's symbol element through index.
  48262. // so if we want to remove the symbol element we should insure
  48263. // that the symbol element is not null.
  48264. if (symbolEl) {
  48265. removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  48266. }
  48267. }).execute();
  48268. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  48269. this._updateNodeAndLinkScale(seriesModel);
  48270. if (seriesModel.get('expandAndCollapse') === true) {
  48271. data.eachItemGraphicEl(function (el, dataIndex) {
  48272. el.off('click').on('click', function () {
  48273. api.dispatchAction({
  48274. type: 'treeExpandAndCollapse',
  48275. seriesId: seriesModel.id,
  48276. dataIndex: dataIndex
  48277. });
  48278. });
  48279. });
  48280. }
  48281. this._data = data;
  48282. };
  48283. TreeView.prototype._updateViewCoordSys = function (seriesModel, api) {
  48284. var data = seriesModel.getData();
  48285. var points = [];
  48286. data.each(function (idx) {
  48287. var layout = data.getItemLayout(idx);
  48288. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  48289. points.push([+layout.x, +layout.y]);
  48290. }
  48291. });
  48292. var min = [];
  48293. var max = [];
  48294. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  48295. // the root node will disappear.
  48296. var oldMin = this._min;
  48297. var oldMax = this._max; // If width or height is 0
  48298. if (max[0] - min[0] === 0) {
  48299. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  48300. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  48301. }
  48302. if (max[1] - min[1] === 0) {
  48303. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  48304. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  48305. }
  48306. var viewCoordSys = seriesModel.coordinateSystem = new View();
  48307. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  48308. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  48309. viewCoordSys.setCenter(seriesModel.get('center'), api);
  48310. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  48311. this.group.attr({
  48312. x: viewCoordSys.x,
  48313. y: viewCoordSys.y,
  48314. scaleX: viewCoordSys.scaleX,
  48315. scaleY: viewCoordSys.scaleY
  48316. });
  48317. this._min = min;
  48318. this._max = max;
  48319. };
  48320. TreeView.prototype._updateController = function (seriesModel, ecModel, api) {
  48321. var _this = this;
  48322. var controller = this._controller;
  48323. var controllerHost = this._controllerHost;
  48324. var group = this.group;
  48325. controller.setPointerChecker(function (e, x, y) {
  48326. var rect = group.getBoundingRect();
  48327. rect.applyTransform(group.transform);
  48328. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  48329. });
  48330. controller.enable(seriesModel.get('roam'));
  48331. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  48332. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  48333. controller.off('pan').off('zoom').on('pan', function (e) {
  48334. updateViewOnPan(controllerHost, e.dx, e.dy);
  48335. api.dispatchAction({
  48336. seriesId: seriesModel.id,
  48337. type: 'treeRoam',
  48338. dx: e.dx,
  48339. dy: e.dy
  48340. });
  48341. }).on('zoom', function (e) {
  48342. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  48343. api.dispatchAction({
  48344. seriesId: seriesModel.id,
  48345. type: 'treeRoam',
  48346. zoom: e.scale,
  48347. originX: e.originX,
  48348. originY: e.originY
  48349. });
  48350. _this._updateNodeAndLinkScale(seriesModel); // Only update label layout on zoom
  48351. api.updateLabelLayout();
  48352. });
  48353. };
  48354. TreeView.prototype._updateNodeAndLinkScale = function (seriesModel) {
  48355. var data = seriesModel.getData();
  48356. var nodeScale = this._getNodeGlobalScale(seriesModel);
  48357. data.eachItemGraphicEl(function (el, idx) {
  48358. el.setSymbolScale(nodeScale);
  48359. });
  48360. };
  48361. TreeView.prototype._getNodeGlobalScale = function (seriesModel) {
  48362. var coordSys = seriesModel.coordinateSystem;
  48363. if (coordSys.type !== 'view') {
  48364. return 1;
  48365. }
  48366. var nodeScaleRatio = this._nodeScaleRatio;
  48367. var groupZoom = coordSys.scaleX || 1; // Scale node when zoom changes
  48368. var roamZoom = coordSys.getZoom();
  48369. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  48370. return nodeScale / groupZoom;
  48371. };
  48372. TreeView.prototype.dispose = function () {
  48373. this._controller && this._controller.dispose();
  48374. this._controllerHost = null;
  48375. };
  48376. TreeView.prototype.remove = function () {
  48377. this._mainGroup.removeAll();
  48378. this._data = null;
  48379. };
  48380. TreeView.type = 'tree';
  48381. return TreeView;
  48382. }(ChartView);
  48383. function symbolNeedsDraw$1(data, dataIndex) {
  48384. var layout = data.getItemLayout(dataIndex);
  48385. return layout && !isNaN(layout.x) && !isNaN(layout.y);
  48386. }
  48387. function updateNode(data, dataIndex, symbolEl, group, seriesModel) {
  48388. var isInit = !symbolEl;
  48389. var node = data.tree.getNodeByDataIndex(dataIndex);
  48390. var itemModel = node.getModel();
  48391. var visualColor = node.getVisual('style').fill;
  48392. var symbolInnerColor = node.isExpand === false && node.children.length !== 0 ? visualColor : '#fff';
  48393. var virtualRoot = data.tree.root;
  48394. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48395. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48396. var sourceLayout = source.getLayout();
  48397. var sourceOldLayout = sourceSymbolEl ? {
  48398. x: sourceSymbolEl.__oldX,
  48399. y: sourceSymbolEl.__oldY,
  48400. rawX: sourceSymbolEl.__radialOldRawX,
  48401. rawY: sourceSymbolEl.__radialOldRawY
  48402. } : sourceLayout;
  48403. var targetLayout = node.getLayout();
  48404. if (isInit) {
  48405. symbolEl = new Symbol(data, dataIndex, null, {
  48406. symbolInnerColor: symbolInnerColor,
  48407. useNameLabel: true
  48408. });
  48409. symbolEl.x = sourceOldLayout.x;
  48410. symbolEl.y = sourceOldLayout.y;
  48411. } else {
  48412. symbolEl.updateData(data, dataIndex, null, {
  48413. symbolInnerColor: symbolInnerColor,
  48414. useNameLabel: true
  48415. });
  48416. }
  48417. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  48418. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  48419. symbolEl.__radialRawX = targetLayout.rawX;
  48420. symbolEl.__radialRawY = targetLayout.rawY;
  48421. group.add(symbolEl);
  48422. data.setItemGraphicEl(dataIndex, symbolEl);
  48423. symbolEl.__oldX = symbolEl.x;
  48424. symbolEl.__oldY = symbolEl.y;
  48425. updateProps(symbolEl, {
  48426. x: targetLayout.x,
  48427. y: targetLayout.y
  48428. }, seriesModel);
  48429. var symbolPath = symbolEl.getSymbolPath();
  48430. if (seriesModel.get('layout') === 'radial') {
  48431. var realRoot = virtualRoot.children[0];
  48432. var rootLayout = realRoot.getLayout();
  48433. var length_1 = realRoot.children.length;
  48434. var rad = void 0;
  48435. var isLeft = void 0;
  48436. if (targetLayout.x === rootLayout.x && node.isExpand === true && realRoot.children.length) {
  48437. var center = {
  48438. x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2,
  48439. y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2
  48440. };
  48441. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  48442. if (rad < 0) {
  48443. rad = Math.PI * 2 + rad;
  48444. }
  48445. isLeft = center.x < rootLayout.x;
  48446. if (isLeft) {
  48447. rad = rad - Math.PI;
  48448. }
  48449. } else {
  48450. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  48451. if (rad < 0) {
  48452. rad = Math.PI * 2 + rad;
  48453. }
  48454. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  48455. isLeft = targetLayout.x < rootLayout.x;
  48456. if (isLeft) {
  48457. rad = rad - Math.PI;
  48458. }
  48459. } else {
  48460. isLeft = targetLayout.x > rootLayout.x;
  48461. if (!isLeft) {
  48462. rad = rad - Math.PI;
  48463. }
  48464. }
  48465. }
  48466. var textPosition = isLeft ? 'left' : 'right';
  48467. var normalLabelModel = itemModel.getModel('label');
  48468. var rotate = normalLabelModel.get('rotate');
  48469. var labelRotateRadian = rotate * (Math.PI / 180);
  48470. var textContent = symbolPath.getTextContent();
  48471. if (textContent) {
  48472. symbolPath.setTextConfig({
  48473. position: normalLabelModel.get('position') || textPosition,
  48474. rotation: rotate == null ? -rad : labelRotateRadian,
  48475. origin: 'center'
  48476. });
  48477. textContent.setStyle('verticalAlign', 'middle');
  48478. }
  48479. } // Handle status
  48480. var focus = itemModel.get(['emphasis', 'focus']);
  48481. var focusDataIndices = focus === 'relative' ? concatArray(node.getAncestorsIndices(), node.getDescendantIndices()) : focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  48482. if (focusDataIndices) {
  48483. // Modify the focus to data indices.
  48484. getECData(symbolEl).focus = focusDataIndices;
  48485. }
  48486. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group);
  48487. if (symbolEl.__edge) {
  48488. symbolEl.onHoverStateChange = function (toState) {
  48489. if (toState !== 'blur') {
  48490. // NOTE: Ensure the parent elements will been blurred firstly.
  48491. // According to the return of getAncestorsIndices and getDescendantIndices
  48492. // TODO: A bit tricky.
  48493. var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex);
  48494. if (!(parentEl && parentEl.hoverState === HOVER_STATE_BLUR)) {
  48495. setStatesFlag(symbolEl.__edge, toState);
  48496. }
  48497. }
  48498. };
  48499. }
  48500. }
  48501. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) {
  48502. var itemModel = node.getModel();
  48503. var edgeShape = seriesModel.get('edgeShape');
  48504. var layout = seriesModel.get('layout');
  48505. var orient = seriesModel.getOrient();
  48506. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48507. var edgeForkPosition = seriesModel.get('edgeForkPosition');
  48508. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  48509. var edge = symbolEl.__edge; // curve edge from node -> parent
  48510. // polyline edge from node -> children
  48511. if (edgeShape === 'curve') {
  48512. if (node.parentNode && node.parentNode !== virtualRoot) {
  48513. if (!edge) {
  48514. edge = symbolEl.__edge = new BezierCurve({
  48515. shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout)
  48516. });
  48517. }
  48518. updateProps(edge, {
  48519. shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout)
  48520. }, seriesModel);
  48521. }
  48522. } else if (edgeShape === 'polyline') {
  48523. if (layout === 'orthogonal') {
  48524. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  48525. var children = node.children;
  48526. var childPoints = [];
  48527. for (var i = 0; i < children.length; i++) {
  48528. var childLayout = children[i].getLayout();
  48529. childPoints.push([childLayout.x, childLayout.y]);
  48530. }
  48531. if (!edge) {
  48532. edge = symbolEl.__edge = new TreePath({
  48533. shape: {
  48534. parentPoint: [targetLayout.x, targetLayout.y],
  48535. childPoints: [[targetLayout.x, targetLayout.y]],
  48536. orient: orient,
  48537. forkPosition: edgeForkPosition
  48538. }
  48539. });
  48540. }
  48541. updateProps(edge, {
  48542. shape: {
  48543. parentPoint: [targetLayout.x, targetLayout.y],
  48544. childPoints: childPoints
  48545. }
  48546. }, seriesModel);
  48547. }
  48548. } else {
  48549. if ("development" !== 'production') {
  48550. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  48551. }
  48552. }
  48553. } // show all edge when edgeShape is 'curve', filter node `isExpand` is false when edgeShape is 'polyline'
  48554. if (edge && !(edgeShape === 'polyline' && !node.isExpand)) {
  48555. edge.useStyle(defaults({
  48556. strokeNoScale: true,
  48557. fill: null
  48558. }, lineStyle));
  48559. setStatesStylesFromModel(edge, itemModel, 'lineStyle');
  48560. setDefaultStateProxy(edge);
  48561. group.add(edge);
  48562. }
  48563. }
  48564. function removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt) {
  48565. var virtualRoot = data.tree.root;
  48566. var _a = getSourceNode(virtualRoot, node),
  48567. source = _a.source,
  48568. sourceLayout = _a.sourceLayout;
  48569. var symbolEl = data.getItemGraphicEl(node.dataIndex);
  48570. if (!symbolEl) {
  48571. return;
  48572. }
  48573. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  48574. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  48575. // the source at the same time. because the polyline edge shape is only owned by the source.
  48576. // 2.when the node is the only children of the source, delete the node should delete the edge of
  48577. // the source at the same time. the same reason as above.
  48578. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  48579. var edgeShape = seriesModel.get('edgeShape');
  48580. var layoutOpt = seriesModel.get('layout');
  48581. var orient = seriesModel.get('orient');
  48582. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  48583. if (edge) {
  48584. if (edgeShape === 'curve') {
  48585. removeElement(edge, {
  48586. shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout),
  48587. style: {
  48588. opacity: 0
  48589. }
  48590. }, seriesModel, {
  48591. cb: function () {
  48592. group.remove(edge);
  48593. },
  48594. removeOpt: removeAnimationOpt
  48595. });
  48596. } else if (edgeShape === 'polyline' && seriesModel.get('layout') === 'orthogonal') {
  48597. removeElement(edge, {
  48598. shape: {
  48599. parentPoint: [sourceLayout.x, sourceLayout.y],
  48600. childPoints: [[sourceLayout.x, sourceLayout.y]]
  48601. },
  48602. style: {
  48603. opacity: 0
  48604. }
  48605. }, seriesModel, {
  48606. cb: function () {
  48607. group.remove(edge);
  48608. },
  48609. removeOpt: removeAnimationOpt
  48610. });
  48611. }
  48612. }
  48613. }
  48614. function getSourceNode(virtualRoot, node) {
  48615. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  48616. var sourceLayout;
  48617. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  48618. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  48619. }
  48620. return {
  48621. source: source,
  48622. sourceLayout: sourceLayout
  48623. };
  48624. }
  48625. function removeNode(data, dataIndex, symbolEl, group, seriesModel) {
  48626. var node = data.tree.getNodeByDataIndex(dataIndex);
  48627. var virtualRoot = data.tree.root;
  48628. var sourceLayout = getSourceNode(virtualRoot, node).sourceLayout; // Use same duration and easing with update to have more consistent animation.
  48629. var removeAnimationOpt = {
  48630. duration: seriesModel.get('animationDurationUpdate'),
  48631. easing: seriesModel.get('animationEasingUpdate')
  48632. };
  48633. removeElement(symbolEl, {
  48634. x: sourceLayout.x + 1,
  48635. y: sourceLayout.y + 1
  48636. }, seriesModel, {
  48637. cb: function () {
  48638. group.remove(symbolEl);
  48639. data.setItemGraphicEl(dataIndex, null);
  48640. },
  48641. removeOpt: removeAnimationOpt
  48642. });
  48643. symbolEl.fadeOut(null, data.hostModel, {
  48644. fadeLabel: true,
  48645. animation: removeAnimationOpt
  48646. }); // remove edge as parent node
  48647. node.children.forEach(function (childNode) {
  48648. removeNodeEdge(childNode, data, group, seriesModel, removeAnimationOpt);
  48649. }); // remove edge as child node
  48650. removeNodeEdge(node, data, group, seriesModel, removeAnimationOpt);
  48651. }
  48652. function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
  48653. var cpx1;
  48654. var cpy1;
  48655. var cpx2;
  48656. var cpy2;
  48657. var x1;
  48658. var x2;
  48659. var y1;
  48660. var y2;
  48661. if (layoutOpt === 'radial') {
  48662. x1 = sourceLayout.rawX;
  48663. y1 = sourceLayout.rawY;
  48664. x2 = targetLayout.rawX;
  48665. y2 = targetLayout.rawY;
  48666. var radialCoor1 = radialCoordinate(x1, y1);
  48667. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature);
  48668. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature);
  48669. var radialCoor4 = radialCoordinate(x2, y2);
  48670. return {
  48671. x1: radialCoor1.x || 0,
  48672. y1: radialCoor1.y || 0,
  48673. x2: radialCoor4.x || 0,
  48674. y2: radialCoor4.y || 0,
  48675. cpx1: radialCoor2.x || 0,
  48676. cpy1: radialCoor2.y || 0,
  48677. cpx2: radialCoor3.x || 0,
  48678. cpy2: radialCoor3.y || 0
  48679. };
  48680. } else {
  48681. x1 = sourceLayout.x;
  48682. y1 = sourceLayout.y;
  48683. x2 = targetLayout.x;
  48684. y2 = targetLayout.y;
  48685. if (orient === 'LR' || orient === 'RL') {
  48686. cpx1 = x1 + (x2 - x1) * curvature;
  48687. cpy1 = y1;
  48688. cpx2 = x2 + (x1 - x2) * curvature;
  48689. cpy2 = y2;
  48690. }
  48691. if (orient === 'TB' || orient === 'BT') {
  48692. cpx1 = x1;
  48693. cpy1 = y1 + (y2 - y1) * curvature;
  48694. cpx2 = x2;
  48695. cpy2 = y2 + (y1 - y2) * curvature;
  48696. }
  48697. }
  48698. return {
  48699. x1: x1,
  48700. y1: y1,
  48701. x2: x2,
  48702. y2: y2,
  48703. cpx1: cpx1,
  48704. cpy1: cpy1,
  48705. cpx2: cpx2,
  48706. cpy2: cpy2
  48707. };
  48708. }
  48709. var inner$7 = makeInner();
  48710. function linkSeriesData(opt) {
  48711. var mainData = opt.mainData;
  48712. var datas = opt.datas;
  48713. if (!datas) {
  48714. datas = {
  48715. main: mainData
  48716. };
  48717. opt.datasAttr = {
  48718. main: 'data'
  48719. };
  48720. }
  48721. opt.datas = opt.mainData = null;
  48722. linkAll(mainData, datas, opt); // Porxy data original methods.
  48723. each(datas, function (data) {
  48724. each(mainData.TRANSFERABLE_METHODS, function (methodName) {
  48725. data.wrapMethod(methodName, curry(transferInjection, opt));
  48726. });
  48727. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  48728. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  48729. // another changable methods, which may bring about dead lock.
  48730. each(mainData.CHANGABLE_METHODS, function (methodName) {
  48731. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  48732. }); // Make sure datas contains mainData.
  48733. assert(datas[mainData.dataType] === mainData);
  48734. }
  48735. function transferInjection(opt, res) {
  48736. if (isMainData(this)) {
  48737. // Transfer datas to new main data.
  48738. var datas = extend({}, inner$7(this).datas);
  48739. datas[this.dataType] = res;
  48740. linkAll(res, datas, opt);
  48741. } else {
  48742. // Modify the reference in main data to point newData.
  48743. linkSingle(res, this.dataType, inner$7(this).mainData, opt);
  48744. }
  48745. return res;
  48746. }
  48747. function changeInjection(opt, res) {
  48748. opt.struct && opt.struct.update();
  48749. return res;
  48750. }
  48751. function cloneShallowInjection(opt, res) {
  48752. // cloneShallow, which brings about some fragilities, may be inappropriate
  48753. // to be exposed as an API. So for implementation simplicity we can make
  48754. // the restriction that cloneShallow of not-mainData should not be invoked
  48755. // outside, but only be invoked here.
  48756. each(inner$7(res).datas, function (data, dataType) {
  48757. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  48758. });
  48759. return res;
  48760. }
  48761. /**
  48762. * Supplement method to List.
  48763. *
  48764. * @public
  48765. * @param [dataType] If not specified, return mainData.
  48766. */
  48767. function getLinkedData(dataType) {
  48768. var mainData = inner$7(this).mainData;
  48769. return dataType == null || mainData == null ? mainData : inner$7(mainData).datas[dataType];
  48770. }
  48771. /**
  48772. * Get list of all linked data
  48773. */
  48774. function getLinkedDataAll() {
  48775. var mainData = inner$7(this).mainData;
  48776. return mainData == null ? [{
  48777. data: mainData
  48778. }] : map(keys(inner$7(mainData).datas), function (type) {
  48779. return {
  48780. type: type,
  48781. data: inner$7(mainData).datas[type]
  48782. };
  48783. });
  48784. }
  48785. function isMainData(data) {
  48786. return inner$7(data).mainData === data;
  48787. }
  48788. function linkAll(mainData, datas, opt) {
  48789. inner$7(mainData).datas = {};
  48790. each(datas, function (data, dataType) {
  48791. linkSingle(data, dataType, mainData, opt);
  48792. });
  48793. }
  48794. function linkSingle(data, dataType, mainData, opt) {
  48795. inner$7(mainData).datas[dataType] = data;
  48796. inner$7(data).mainData = mainData;
  48797. data.dataType = dataType;
  48798. if (opt.struct) {
  48799. data[opt.structAttr] = opt.struct;
  48800. opt.struct[opt.datasAttr[dataType]] = data;
  48801. } // Supplement method.
  48802. data.getLinkedData = getLinkedData;
  48803. data.getLinkedDataAll = getLinkedDataAll;
  48804. }
  48805. var TreeNode =
  48806. /** @class */
  48807. function () {
  48808. function TreeNode(name, hostTree) {
  48809. this.depth = 0;
  48810. this.height = 0;
  48811. /**
  48812. * Reference to list item.
  48813. * Do not persistent dataIndex outside,
  48814. * besause it may be changed by list.
  48815. * If dataIndex -1,
  48816. * this node is logical deleted (filtered) in list.
  48817. */
  48818. this.dataIndex = -1;
  48819. this.children = [];
  48820. this.viewChildren = [];
  48821. this.isExpand = false;
  48822. this.name = name || '';
  48823. this.hostTree = hostTree;
  48824. }
  48825. /**
  48826. * The node is removed.
  48827. */
  48828. TreeNode.prototype.isRemoved = function () {
  48829. return this.dataIndex < 0;
  48830. };
  48831. TreeNode.prototype.eachNode = function (options, cb, context) {
  48832. if (isFunction(options)) {
  48833. context = cb;
  48834. cb = options;
  48835. options = null;
  48836. }
  48837. options = options || {};
  48838. if (isString(options)) {
  48839. options = {
  48840. order: options
  48841. };
  48842. }
  48843. var order = options.order || 'preorder';
  48844. var children = this[options.attr || 'children'];
  48845. var suppressVisitSub;
  48846. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  48847. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  48848. children[i].eachNode(options, cb, context);
  48849. }
  48850. order === 'postorder' && cb.call(context, this);
  48851. };
  48852. /**
  48853. * Update depth and height of this subtree.
  48854. */
  48855. TreeNode.prototype.updateDepthAndHeight = function (depth) {
  48856. var height = 0;
  48857. this.depth = depth;
  48858. for (var i = 0; i < this.children.length; i++) {
  48859. var child = this.children[i];
  48860. child.updateDepthAndHeight(depth + 1);
  48861. if (child.height > height) {
  48862. height = child.height;
  48863. }
  48864. }
  48865. this.height = height + 1;
  48866. };
  48867. TreeNode.prototype.getNodeById = function (id) {
  48868. if (this.getId() === id) {
  48869. return this;
  48870. }
  48871. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48872. var res = children[i].getNodeById(id);
  48873. if (res) {
  48874. return res;
  48875. }
  48876. }
  48877. };
  48878. TreeNode.prototype.contains = function (node) {
  48879. if (node === this) {
  48880. return true;
  48881. }
  48882. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  48883. var res = children[i].contains(node);
  48884. if (res) {
  48885. return res;
  48886. }
  48887. }
  48888. };
  48889. /**
  48890. * @param includeSelf Default false.
  48891. * @return order: [root, child, grandchild, ...]
  48892. */
  48893. TreeNode.prototype.getAncestors = function (includeSelf) {
  48894. var ancestors = [];
  48895. var node = includeSelf ? this : this.parentNode;
  48896. while (node) {
  48897. ancestors.push(node);
  48898. node = node.parentNode;
  48899. }
  48900. ancestors.reverse();
  48901. return ancestors;
  48902. };
  48903. TreeNode.prototype.getAncestorsIndices = function () {
  48904. var indices = [];
  48905. var currNode = this;
  48906. while (currNode) {
  48907. indices.push(currNode.dataIndex);
  48908. currNode = currNode.parentNode;
  48909. }
  48910. indices.reverse();
  48911. return indices;
  48912. };
  48913. TreeNode.prototype.getDescendantIndices = function () {
  48914. var indices = [];
  48915. this.eachNode(function (childNode) {
  48916. indices.push(childNode.dataIndex);
  48917. });
  48918. return indices;
  48919. };
  48920. TreeNode.prototype.getValue = function (dimension) {
  48921. var data = this.hostTree.data;
  48922. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  48923. };
  48924. TreeNode.prototype.setLayout = function (layout, merge) {
  48925. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
  48926. };
  48927. /**
  48928. * @return {Object} layout
  48929. */
  48930. TreeNode.prototype.getLayout = function () {
  48931. return this.hostTree.data.getItemLayout(this.dataIndex);
  48932. }; // @depcrecated
  48933. // getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
  48934. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  48935. TreeNode.prototype.getModel = function (path) {
  48936. if (this.dataIndex < 0) {
  48937. return;
  48938. }
  48939. var hostTree = this.hostTree;
  48940. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  48941. return itemModel.getModel(path);
  48942. }; // TODO: TYPE More specific model
  48943. TreeNode.prototype.getLevelModel = function () {
  48944. return (this.hostTree.levelModels || [])[this.depth];
  48945. };
  48946. TreeNode.prototype.setVisual = function (key, value) {
  48947. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  48948. };
  48949. /**
  48950. * Get item visual
  48951. * FIXME: make return type better
  48952. */
  48953. TreeNode.prototype.getVisual = function (key) {
  48954. return this.hostTree.data.getItemVisual(this.dataIndex, key);
  48955. };
  48956. TreeNode.prototype.getRawIndex = function () {
  48957. return this.hostTree.data.getRawIndex(this.dataIndex);
  48958. };
  48959. TreeNode.prototype.getId = function () {
  48960. return this.hostTree.data.getId(this.dataIndex);
  48961. };
  48962. /**
  48963. * index in parent's children
  48964. */
  48965. TreeNode.prototype.getChildIndex = function () {
  48966. if (this.parentNode) {
  48967. var children = this.parentNode.children;
  48968. for (var i = 0; i < children.length; ++i) {
  48969. if (children[i] === this) {
  48970. return i;
  48971. }
  48972. }
  48973. return -1;
  48974. }
  48975. return -1;
  48976. };
  48977. /**
  48978. * if this is an ancestor of another node
  48979. *
  48980. * @param node another node
  48981. * @return if is ancestor
  48982. */
  48983. TreeNode.prototype.isAncestorOf = function (node) {
  48984. var parent = node.parentNode;
  48985. while (parent) {
  48986. if (parent === this) {
  48987. return true;
  48988. }
  48989. parent = parent.parentNode;
  48990. }
  48991. return false;
  48992. };
  48993. /**
  48994. * if this is an descendant of another node
  48995. *
  48996. * @param node another node
  48997. * @return if is descendant
  48998. */
  48999. TreeNode.prototype.isDescendantOf = function (node) {
  49000. return node !== this && node.isAncestorOf(this);
  49001. };
  49002. return TreeNode;
  49003. }();
  49004. var Tree =
  49005. /** @class */
  49006. function () {
  49007. function Tree(hostModel) {
  49008. this.type = 'tree';
  49009. this._nodes = [];
  49010. this.hostModel = hostModel;
  49011. }
  49012. Tree.prototype.eachNode = function (options, cb, context) {
  49013. this.root.eachNode(options, cb, context);
  49014. };
  49015. Tree.prototype.getNodeByDataIndex = function (dataIndex) {
  49016. var rawIndex = this.data.getRawIndex(dataIndex);
  49017. return this._nodes[rawIndex];
  49018. };
  49019. Tree.prototype.getNodeById = function (name) {
  49020. return this.root.getNodeById(name);
  49021. };
  49022. /**
  49023. * Update item available by list,
  49024. * when list has been performed options like 'filterSelf' or 'map'.
  49025. */
  49026. Tree.prototype.update = function () {
  49027. var data = this.data;
  49028. var nodes = this._nodes;
  49029. for (var i = 0, len = nodes.length; i < len; i++) {
  49030. nodes[i].dataIndex = -1;
  49031. }
  49032. for (var i = 0, len = data.count(); i < len; i++) {
  49033. nodes[data.getRawIndex(i)].dataIndex = i;
  49034. }
  49035. };
  49036. /**
  49037. * Clear all layouts
  49038. */
  49039. Tree.prototype.clearLayouts = function () {
  49040. this.data.clearItemLayouts();
  49041. };
  49042. /**
  49043. * data node format:
  49044. * {
  49045. * name: ...
  49046. * value: ...
  49047. * children: [
  49048. * {
  49049. * name: ...
  49050. * value: ...
  49051. * children: ...
  49052. * },
  49053. * ...
  49054. * ]
  49055. * }
  49056. */
  49057. Tree.createTree = function (dataRoot, hostModel, beforeLink) {
  49058. var tree = new Tree(hostModel);
  49059. var listData = [];
  49060. var dimMax = 1;
  49061. buildHierarchy(dataRoot);
  49062. function buildHierarchy(dataNode, parentNode) {
  49063. var value = dataNode.value;
  49064. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  49065. listData.push(dataNode);
  49066. var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
  49067. parentNode ? addChild(node, parentNode) : tree.root = node;
  49068. tree._nodes.push(node);
  49069. var children = dataNode.children;
  49070. if (children) {
  49071. for (var i = 0; i < children.length; i++) {
  49072. buildHierarchy(children[i], node);
  49073. }
  49074. }
  49075. }
  49076. tree.root.updateDepthAndHeight(0);
  49077. var dimensions = prepareSeriesDataSchema(listData, {
  49078. coordDimensions: ['value'],
  49079. dimensionsCount: dimMax
  49080. }).dimensions;
  49081. var list = new SeriesData(dimensions, hostModel);
  49082. list.initData(listData);
  49083. beforeLink && beforeLink(list);
  49084. linkSeriesData({
  49085. mainData: list,
  49086. struct: tree,
  49087. structAttr: 'tree'
  49088. });
  49089. tree.update();
  49090. return tree;
  49091. };
  49092. return Tree;
  49093. }();
  49094. /**
  49095. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  49096. * so this function is not ready and not necessary to be public.
  49097. */
  49098. function addChild(child, node) {
  49099. var children = node.children;
  49100. if (child.parentNode === node) {
  49101. return;
  49102. }
  49103. children.push(child);
  49104. child.parentNode = node;
  49105. }
  49106. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  49107. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  49108. var root = seriesModel.getData().tree.root;
  49109. var targetNode = payload.targetNode;
  49110. if (isString(targetNode)) {
  49111. targetNode = root.getNodeById(targetNode);
  49112. }
  49113. if (targetNode && root.contains(targetNode)) {
  49114. return {
  49115. node: targetNode
  49116. };
  49117. }
  49118. var targetNodeId = payload.targetNodeId;
  49119. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  49120. return {
  49121. node: targetNode
  49122. };
  49123. }
  49124. }
  49125. } // Not includes the given node at the last item.
  49126. function getPathToRoot(node) {
  49127. var path = [];
  49128. while (node) {
  49129. node = node.parentNode;
  49130. node && path.push(node);
  49131. }
  49132. return path.reverse();
  49133. }
  49134. function aboveViewRoot(viewRoot, node) {
  49135. var viewPath = getPathToRoot(viewRoot);
  49136. return indexOf(viewPath, node) >= 0;
  49137. } // From root to the input node (the input node will be included).
  49138. function wrapTreePathInfo(node, seriesModel) {
  49139. var treePathInfo = [];
  49140. while (node) {
  49141. var nodeDataIndex = node.dataIndex;
  49142. treePathInfo.push({
  49143. name: node.name,
  49144. dataIndex: nodeDataIndex,
  49145. value: seriesModel.getRawValue(nodeDataIndex)
  49146. });
  49147. node = node.parentNode;
  49148. }
  49149. treePathInfo.reverse();
  49150. return treePathInfo;
  49151. }
  49152. var TreeSeriesModel =
  49153. /** @class */
  49154. function (_super) {
  49155. __extends(TreeSeriesModel, _super);
  49156. function TreeSeriesModel() {
  49157. var _this = _super !== null && _super.apply(this, arguments) || this;
  49158. _this.hasSymbolVisual = true; // Do it self.
  49159. _this.ignoreStyleOnData = true;
  49160. return _this;
  49161. }
  49162. /**
  49163. * Init a tree data structure from data in option series
  49164. */
  49165. TreeSeriesModel.prototype.getInitialData = function (option) {
  49166. // create a virtual root
  49167. var root = {
  49168. name: option.name,
  49169. children: option.data
  49170. };
  49171. var leaves = option.leaves || {};
  49172. var leavesModel = new Model(leaves, this, this.ecModel);
  49173. var tree = Tree.createTree(root, this, beforeLink);
  49174. function beforeLink(nodeData) {
  49175. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49176. var node = tree.getNodeByDataIndex(idx);
  49177. if (!(node && node.children.length && node.isExpand)) {
  49178. model.parentModel = leavesModel;
  49179. }
  49180. return model;
  49181. });
  49182. }
  49183. var treeDepth = 0;
  49184. tree.eachNode('preorder', function (node) {
  49185. if (node.depth > treeDepth) {
  49186. treeDepth = node.depth;
  49187. }
  49188. });
  49189. var expandAndCollapse = option.expandAndCollapse;
  49190. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  49191. tree.root.eachNode('preorder', function (node) {
  49192. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  49193. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  49194. });
  49195. return tree.data;
  49196. };
  49197. /**
  49198. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  49199. * @returns {string} orient
  49200. */
  49201. TreeSeriesModel.prototype.getOrient = function () {
  49202. var orient = this.get('orient');
  49203. if (orient === 'horizontal') {
  49204. orient = 'LR';
  49205. } else if (orient === 'vertical') {
  49206. orient = 'TB';
  49207. }
  49208. return orient;
  49209. };
  49210. TreeSeriesModel.prototype.setZoom = function (zoom) {
  49211. this.option.zoom = zoom;
  49212. };
  49213. TreeSeriesModel.prototype.setCenter = function (center) {
  49214. this.option.center = center;
  49215. };
  49216. TreeSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49217. var tree = this.getData().tree;
  49218. var realRoot = tree.root.children[0];
  49219. var node = tree.getNodeByDataIndex(dataIndex);
  49220. var value = node.getValue();
  49221. var name = node.name;
  49222. while (node && node !== realRoot) {
  49223. name = node.parentNode.name + '.' + name;
  49224. node = node.parentNode;
  49225. }
  49226. return createTooltipMarkup('nameValue', {
  49227. name: name,
  49228. value: value,
  49229. noValue: isNaN(value) || value == null
  49230. });
  49231. }; // Add tree path to tooltip param
  49232. TreeSeriesModel.prototype.getDataParams = function (dataIndex) {
  49233. var params = _super.prototype.getDataParams.apply(this, arguments);
  49234. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49235. params.treeAncestors = wrapTreePathInfo(node, this);
  49236. params.collapsed = !node.isExpand;
  49237. return params;
  49238. };
  49239. TreeSeriesModel.type = 'series.tree'; // can support the position parameters 'left', 'top','right','bottom', 'width',
  49240. // 'height' in the setOption() with 'merge' mode normal.
  49241. TreeSeriesModel.layoutMode = 'box';
  49242. TreeSeriesModel.defaultOption = {
  49243. // zlevel: 0,
  49244. z: 2,
  49245. coordinateSystem: 'view',
  49246. // the position of the whole view
  49247. left: '12%',
  49248. top: '12%',
  49249. right: '12%',
  49250. bottom: '12%',
  49251. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  49252. layout: 'orthogonal',
  49253. // value can be 'polyline'
  49254. edgeShape: 'curve',
  49255. edgeForkPosition: '50%',
  49256. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  49257. roam: false,
  49258. // Symbol size scale ratio in roam
  49259. nodeScaleRatio: 0.4,
  49260. // Default on center of graph
  49261. center: null,
  49262. zoom: 1,
  49263. orient: 'LR',
  49264. symbol: 'emptyCircle',
  49265. symbolSize: 7,
  49266. expandAndCollapse: true,
  49267. initialTreeDepth: 2,
  49268. lineStyle: {
  49269. color: '#ccc',
  49270. width: 1.5,
  49271. curveness: 0.5
  49272. },
  49273. itemStyle: {
  49274. color: 'lightsteelblue',
  49275. // borderColor: '#c23531',
  49276. borderWidth: 1.5
  49277. },
  49278. label: {
  49279. show: true
  49280. },
  49281. animationEasing: 'linear',
  49282. animationDuration: 700,
  49283. animationDurationUpdate: 500
  49284. };
  49285. return TreeSeriesModel;
  49286. }(SeriesModel);
  49287. /*
  49288. * Licensed to the Apache Software Foundation (ASF) under one
  49289. * or more contributor license agreements. See the NOTICE file
  49290. * distributed with this work for additional information
  49291. * regarding copyright ownership. The ASF licenses this file
  49292. * to you under the Apache License, Version 2.0 (the
  49293. * "License"); you may not use this file except in compliance
  49294. * with the License. You may obtain a copy of the License at
  49295. *
  49296. * http://www.apache.org/licenses/LICENSE-2.0
  49297. *
  49298. * Unless required by applicable law or agreed to in writing,
  49299. * software distributed under the License is distributed on an
  49300. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49301. * KIND, either express or implied. See the License for the
  49302. * specific language governing permissions and limitations
  49303. * under the License.
  49304. */
  49305. /**
  49306. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49307. */
  49308. /*
  49309. * Licensed to the Apache Software Foundation (ASF) under one
  49310. * or more contributor license agreements. See the NOTICE file
  49311. * distributed with this work for additional information
  49312. * regarding copyright ownership. The ASF licenses this file
  49313. * to you under the Apache License, Version 2.0 (the
  49314. * "License"); you may not use this file except in compliance
  49315. * with the License. You may obtain a copy of the License at
  49316. *
  49317. * http://www.apache.org/licenses/LICENSE-2.0
  49318. *
  49319. * Unless required by applicable law or agreed to in writing,
  49320. * software distributed under the License is distributed on an
  49321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49322. * KIND, either express or implied. See the License for the
  49323. * specific language governing permissions and limitations
  49324. * under the License.
  49325. */
  49326. /**
  49327. * Traverse the tree from bottom to top and do something
  49328. */
  49329. function eachAfter(root, callback, separation) {
  49330. var nodes = [root];
  49331. var next = [];
  49332. var node;
  49333. while (node = nodes.pop()) {
  49334. // jshint ignore:line
  49335. next.push(node);
  49336. if (node.isExpand) {
  49337. var children = node.children;
  49338. if (children.length) {
  49339. for (var i = 0; i < children.length; i++) {
  49340. nodes.push(children[i]);
  49341. }
  49342. }
  49343. }
  49344. }
  49345. while (node = next.pop()) {
  49346. // jshint ignore:line
  49347. callback(node, separation);
  49348. }
  49349. }
  49350. /**
  49351. * Traverse the tree from top to bottom and do something
  49352. */
  49353. function eachBefore(root, callback) {
  49354. var nodes = [root];
  49355. var node;
  49356. while (node = nodes.pop()) {
  49357. // jshint ignore:line
  49358. callback(node);
  49359. if (node.isExpand) {
  49360. var children = node.children;
  49361. if (children.length) {
  49362. for (var i = children.length - 1; i >= 0; i--) {
  49363. nodes.push(children[i]);
  49364. }
  49365. }
  49366. }
  49367. }
  49368. }
  49369. function treeLayout(ecModel, api) {
  49370. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49371. commonLayout(seriesModel, api);
  49372. });
  49373. }
  49374. function commonLayout(seriesModel, api) {
  49375. var layoutInfo = getViewRect$1(seriesModel, api);
  49376. seriesModel.layoutInfo = layoutInfo;
  49377. var layout = seriesModel.get('layout');
  49378. var width = 0;
  49379. var height = 0;
  49380. var separation$1 = null;
  49381. if (layout === 'radial') {
  49382. width = 2 * Math.PI;
  49383. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  49384. separation$1 = separation(function (node1, node2) {
  49385. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  49386. });
  49387. } else {
  49388. width = layoutInfo.width;
  49389. height = layoutInfo.height;
  49390. separation$1 = separation();
  49391. }
  49392. var virtualRoot = seriesModel.getData().tree.root;
  49393. var realRoot = virtualRoot.children[0];
  49394. if (realRoot) {
  49395. init$2(virtualRoot);
  49396. eachAfter(realRoot, firstWalk, separation$1);
  49397. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  49398. eachBefore(realRoot, secondWalk);
  49399. var left_1 = realRoot;
  49400. var right_1 = realRoot;
  49401. var bottom_1 = realRoot;
  49402. eachBefore(realRoot, function (node) {
  49403. var x = node.getLayout().x;
  49404. if (x < left_1.getLayout().x) {
  49405. left_1 = node;
  49406. }
  49407. if (x > right_1.getLayout().x) {
  49408. right_1 = node;
  49409. }
  49410. if (node.depth > bottom_1.depth) {
  49411. bottom_1 = node;
  49412. }
  49413. });
  49414. var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2;
  49415. var tx_1 = delta - left_1.getLayout().x;
  49416. var kx_1 = 0;
  49417. var ky_1 = 0;
  49418. var coorX_1 = 0;
  49419. var coorY_1 = 0;
  49420. if (layout === 'radial') {
  49421. kx_1 = width / (right_1.getLayout().x + delta + tx_1); // here we use (node.depth - 1), bucause the real root's depth is 1
  49422. ky_1 = height / (bottom_1.depth - 1 || 1);
  49423. eachBefore(realRoot, function (node) {
  49424. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49425. coorY_1 = (node.depth - 1) * ky_1;
  49426. var finalCoor = radialCoordinate(coorX_1, coorY_1);
  49427. node.setLayout({
  49428. x: finalCoor.x,
  49429. y: finalCoor.y,
  49430. rawX: coorX_1,
  49431. rawY: coorY_1
  49432. }, true);
  49433. });
  49434. } else {
  49435. var orient_1 = seriesModel.getOrient();
  49436. if (orient_1 === 'RL' || orient_1 === 'LR') {
  49437. ky_1 = height / (right_1.getLayout().x + delta + tx_1);
  49438. kx_1 = width / (bottom_1.depth - 1 || 1);
  49439. eachBefore(realRoot, function (node) {
  49440. coorY_1 = (node.getLayout().x + tx_1) * ky_1;
  49441. coorX_1 = orient_1 === 'LR' ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1;
  49442. node.setLayout({
  49443. x: coorX_1,
  49444. y: coorY_1
  49445. }, true);
  49446. });
  49447. } else if (orient_1 === 'TB' || orient_1 === 'BT') {
  49448. kx_1 = width / (right_1.getLayout().x + delta + tx_1);
  49449. ky_1 = height / (bottom_1.depth - 1 || 1);
  49450. eachBefore(realRoot, function (node) {
  49451. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  49452. coorY_1 = orient_1 === 'TB' ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1;
  49453. node.setLayout({
  49454. x: coorX_1,
  49455. y: coorY_1
  49456. }, true);
  49457. });
  49458. }
  49459. }
  49460. }
  49461. }
  49462. function treeVisual(ecModel) {
  49463. ecModel.eachSeriesByType('tree', function (seriesModel) {
  49464. var data = seriesModel.getData();
  49465. var tree = data.tree;
  49466. tree.eachNode(function (node) {
  49467. var model = node.getModel(); // TODO Optimize
  49468. var style = model.getModel('itemStyle').getItemStyle();
  49469. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  49470. extend(existsStyle, style);
  49471. });
  49472. });
  49473. }
  49474. function installTreeAction(registers) {
  49475. registers.registerAction({
  49476. type: 'treeExpandAndCollapse',
  49477. event: 'treeExpandAndCollapse',
  49478. update: 'update'
  49479. }, function (payload, ecModel) {
  49480. ecModel.eachComponent({
  49481. mainType: 'series',
  49482. subType: 'tree',
  49483. query: payload
  49484. }, function (seriesModel) {
  49485. var dataIndex = payload.dataIndex;
  49486. var tree = seriesModel.getData().tree;
  49487. var node = tree.getNodeByDataIndex(dataIndex);
  49488. node.isExpand = !node.isExpand;
  49489. });
  49490. });
  49491. registers.registerAction({
  49492. type: 'treeRoam',
  49493. event: 'treeRoam',
  49494. // Here we set 'none' instead of 'update', because roam action
  49495. // just need to update the transform matrix without having to recalculate
  49496. // the layout. So don't need to go through the whole update process, such
  49497. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  49498. update: 'none'
  49499. }, function (payload, ecModel, api) {
  49500. ecModel.eachComponent({
  49501. mainType: 'series',
  49502. subType: 'tree',
  49503. query: payload
  49504. }, function (seriesModel) {
  49505. var coordSys = seriesModel.coordinateSystem;
  49506. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  49507. seriesModel.setCenter && seriesModel.setCenter(res.center);
  49508. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  49509. });
  49510. });
  49511. }
  49512. function install$b(registers) {
  49513. registers.registerChartView(TreeView);
  49514. registers.registerSeriesModel(TreeSeriesModel);
  49515. registers.registerLayout(treeLayout);
  49516. registers.registerVisual(treeVisual);
  49517. installTreeAction(registers);
  49518. }
  49519. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  49520. function installTreemapAction(registers) {
  49521. for (var i = 0; i < actionTypes.length; i++) {
  49522. registers.registerAction({
  49523. type: actionTypes[i],
  49524. update: 'updateView'
  49525. }, noop);
  49526. }
  49527. registers.registerAction({
  49528. type: 'treemapRootToNode',
  49529. update: 'updateView'
  49530. }, function (payload, ecModel) {
  49531. ecModel.eachComponent({
  49532. mainType: 'series',
  49533. subType: 'treemap',
  49534. query: payload
  49535. }, handleRootToNode);
  49536. function handleRootToNode(model, index) {
  49537. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  49538. var targetInfo = retrieveTargetInfo(payload, types, model);
  49539. if (targetInfo) {
  49540. var originViewRoot = model.getViewRoot();
  49541. if (originViewRoot) {
  49542. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  49543. }
  49544. model.resetViewRoot(targetInfo.node);
  49545. }
  49546. }
  49547. });
  49548. }
  49549. function enableAriaDecalForTree(seriesModel) {
  49550. var data = seriesModel.getData();
  49551. var tree = data.tree;
  49552. var decalPaletteScope = {};
  49553. tree.eachNode(function (node) {
  49554. // Use decal of level 1 node
  49555. var current = node;
  49556. while (current && current.depth > 1) {
  49557. current = current.parentNode;
  49558. }
  49559. var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope);
  49560. node.setVisual('decal', decal);
  49561. });
  49562. }
  49563. var TreemapSeriesModel =
  49564. /** @class */
  49565. function (_super) {
  49566. __extends(TreemapSeriesModel, _super);
  49567. function TreemapSeriesModel() {
  49568. var _this = _super !== null && _super.apply(this, arguments) || this;
  49569. _this.type = TreemapSeriesModel.type;
  49570. _this.preventUsingHoverLayer = true;
  49571. return _this;
  49572. }
  49573. /**
  49574. * @override
  49575. */
  49576. TreemapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  49577. // Create a virtual root.
  49578. var root = {
  49579. name: option.name,
  49580. children: option.data
  49581. };
  49582. completeTreeValue(root);
  49583. var levels = option.levels || []; // Used in "visual priority" in `treemapVisual.js`.
  49584. // This way is a little tricky, must satisfy the precondition:
  49585. // 1. There is no `treeNode.getModel('itemStyle.xxx')` used.
  49586. // 2. The `Model.prototype.getModel()` will not use any clone-like way.
  49587. var designatedVisualItemStyle = this.designatedVisualItemStyle = {};
  49588. var designatedVisualModel = new Model({
  49589. itemStyle: designatedVisualItemStyle
  49590. }, this, ecModel);
  49591. levels = option.levels = setDefault(levels, ecModel);
  49592. var levelModels = map(levels || [], function (levelDefine) {
  49593. return new Model(levelDefine, designatedVisualModel, ecModel);
  49594. }, this); // Make sure always a new tree is created when setOption,
  49595. // in TreemapView, we check whether oldTree === newTree
  49596. // to choose mappings approach among old shapes and new shapes.
  49597. var tree = Tree.createTree(root, this, beforeLink);
  49598. function beforeLink(nodeData) {
  49599. nodeData.wrapMethod('getItemModel', function (model, idx) {
  49600. var node = tree.getNodeByDataIndex(idx);
  49601. var levelModel = node ? levelModels[node.depth] : null; // If no levelModel, we also need `designatedVisualModel`.
  49602. model.parentModel = levelModel || designatedVisualModel;
  49603. return model;
  49604. });
  49605. }
  49606. return tree.data;
  49607. };
  49608. TreemapSeriesModel.prototype.optionUpdated = function () {
  49609. this.resetViewRoot();
  49610. };
  49611. /**
  49612. * @override
  49613. * @param {number} dataIndex
  49614. * @param {boolean} [mutipleSeries=false]
  49615. */
  49616. TreemapSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  49617. var data = this.getData();
  49618. var value = this.getRawValue(dataIndex);
  49619. var name = data.getName(dataIndex);
  49620. return createTooltipMarkup('nameValue', {
  49621. name: name,
  49622. value: value
  49623. });
  49624. };
  49625. /**
  49626. * Add tree path to tooltip param
  49627. *
  49628. * @override
  49629. * @param {number} dataIndex
  49630. * @return {Object}
  49631. */
  49632. TreemapSeriesModel.prototype.getDataParams = function (dataIndex) {
  49633. var params = _super.prototype.getDataParams.apply(this, arguments);
  49634. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  49635. params.treeAncestors = wrapTreePathInfo(node, this); // compatitable the previous code.
  49636. params.treePathInfo = params.treeAncestors;
  49637. return params;
  49638. };
  49639. /**
  49640. * @public
  49641. * @param {Object} layoutInfo {
  49642. * x: containerGroup x
  49643. * y: containerGroup y
  49644. * width: containerGroup width
  49645. * height: containerGroup height
  49646. * }
  49647. */
  49648. TreemapSeriesModel.prototype.setLayoutInfo = function (layoutInfo) {
  49649. /**
  49650. * @readOnly
  49651. * @type {Object}
  49652. */
  49653. this.layoutInfo = this.layoutInfo || {};
  49654. extend(this.layoutInfo, layoutInfo);
  49655. };
  49656. /**
  49657. * @param {string} id
  49658. * @return {number} index
  49659. */
  49660. TreemapSeriesModel.prototype.mapIdToIndex = function (id) {
  49661. // A feature is implemented:
  49662. // index is monotone increasing with the sequence of
  49663. // input id at the first time.
  49664. // This feature can make sure that each data item and its
  49665. // mapped color have the same index between data list and
  49666. // color list at the beginning, which is useful for user
  49667. // to adjust data-color mapping.
  49668. /**
  49669. * @private
  49670. * @type {Object}
  49671. */
  49672. var idIndexMap = this._idIndexMap;
  49673. if (!idIndexMap) {
  49674. idIndexMap = this._idIndexMap = createHashMap();
  49675. /**
  49676. * @private
  49677. * @type {number}
  49678. */
  49679. this._idIndexMapCount = 0;
  49680. }
  49681. var index = idIndexMap.get(id);
  49682. if (index == null) {
  49683. idIndexMap.set(id, index = this._idIndexMapCount++);
  49684. }
  49685. return index;
  49686. };
  49687. TreemapSeriesModel.prototype.getViewRoot = function () {
  49688. return this._viewRoot;
  49689. };
  49690. TreemapSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  49691. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  49692. var root = this.getRawData().tree.root;
  49693. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  49694. this._viewRoot = root;
  49695. }
  49696. };
  49697. TreemapSeriesModel.prototype.enableAriaDecal = function () {
  49698. enableAriaDecalForTree(this);
  49699. };
  49700. TreemapSeriesModel.type = 'series.treemap';
  49701. TreemapSeriesModel.layoutMode = 'box';
  49702. TreemapSeriesModel.defaultOption = {
  49703. // Disable progressive rendering
  49704. progressive: 0,
  49705. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  49706. left: 'center',
  49707. top: 'middle',
  49708. width: '80%',
  49709. height: '80%',
  49710. sort: true,
  49711. clipWindow: 'origin',
  49712. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  49713. leafDepth: null,
  49714. drillDownIcon: '▶',
  49715. // to align specialized icon. ▷▶❒❐▼✚
  49716. zoomToNodeRatio: 0.32 * 0.32,
  49717. roam: true,
  49718. nodeClick: 'zoomToNode',
  49719. animation: true,
  49720. animationDurationUpdate: 900,
  49721. animationEasing: 'quinticInOut',
  49722. breadcrumb: {
  49723. show: true,
  49724. height: 22,
  49725. left: 'center',
  49726. top: 'bottom',
  49727. // right
  49728. // bottom
  49729. emptyItemWidth: 25,
  49730. itemStyle: {
  49731. color: 'rgba(0,0,0,0.7)',
  49732. textStyle: {
  49733. color: '#fff'
  49734. }
  49735. },
  49736. emphasis: {
  49737. itemStyle: {
  49738. color: 'rgba(0,0,0,0.9)' // '#5793f3',
  49739. }
  49740. }
  49741. },
  49742. label: {
  49743. show: true,
  49744. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  49745. distance: 0,
  49746. padding: 5,
  49747. position: 'inside',
  49748. // formatter: null,
  49749. color: '#fff',
  49750. overflow: 'truncate' // align
  49751. // verticalAlign
  49752. },
  49753. upperLabel: {
  49754. show: false,
  49755. position: [0, '50%'],
  49756. height: 20,
  49757. // formatter: null,
  49758. // color: '#fff',
  49759. overflow: 'truncate',
  49760. // align: null,
  49761. verticalAlign: 'middle'
  49762. },
  49763. itemStyle: {
  49764. color: null,
  49765. colorAlpha: null,
  49766. colorSaturation: null,
  49767. borderWidth: 0,
  49768. gapWidth: 0,
  49769. borderColor: '#fff',
  49770. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  49771. // border color is evaluated by color of current node and
  49772. // borderColorSaturation.
  49773. },
  49774. emphasis: {
  49775. upperLabel: {
  49776. show: true,
  49777. position: [0, '50%'],
  49778. overflow: 'truncate',
  49779. verticalAlign: 'middle'
  49780. }
  49781. },
  49782. visualDimension: 0,
  49783. visualMin: null,
  49784. visualMax: null,
  49785. color: [],
  49786. // level[n].color (if necessary).
  49787. // + Specify color list of each level. level[0].color would be global
  49788. // color list if not specified. (see method `setDefault`).
  49789. // + But set as a empty array to forbid fetch color from global palette
  49790. // when using nodeModel.get('color'), otherwise nodes on deep level
  49791. // will always has color palette set and are not able to inherit color
  49792. // from parent node.
  49793. // + TreemapSeries.color can not be set as 'none', otherwise effect
  49794. // legend color fetching (see seriesColor.js).
  49795. colorAlpha: null,
  49796. colorSaturation: null,
  49797. colorMappingBy: 'index',
  49798. visibleMin: 10,
  49799. // be rendered. Only works when sort is 'asc' or 'desc'.
  49800. childrenVisibleMin: null,
  49801. // grandchildren will not show.
  49802. // Why grandchildren? If not grandchildren but children,
  49803. // some siblings show children and some not,
  49804. // the appearance may be mess and not consistent,
  49805. levels: [] // Each item: {
  49806. // visibleMin, itemStyle, visualDimension, label
  49807. // }
  49808. };
  49809. return TreemapSeriesModel;
  49810. }(SeriesModel);
  49811. /**
  49812. * @param {Object} dataNode
  49813. */
  49814. function completeTreeValue(dataNode) {
  49815. // Postorder travel tree.
  49816. // If value of none-leaf node is not set,
  49817. // calculate it by suming up the value of all children.
  49818. var sum = 0;
  49819. each(dataNode.children, function (child) {
  49820. completeTreeValue(child);
  49821. var childValue = child.value;
  49822. isArray(childValue) && (childValue = childValue[0]);
  49823. sum += childValue;
  49824. });
  49825. var thisValue = dataNode.value;
  49826. if (isArray(thisValue)) {
  49827. thisValue = thisValue[0];
  49828. }
  49829. if (thisValue == null || isNaN(thisValue)) {
  49830. thisValue = sum;
  49831. } // Value should not less than 0.
  49832. if (thisValue < 0) {
  49833. thisValue = 0;
  49834. }
  49835. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  49836. }
  49837. /**
  49838. * set default to level configuration
  49839. */
  49840. function setDefault(levels, ecModel) {
  49841. var globalColorList = normalizeToArray(ecModel.get('color'));
  49842. var globalDecalList = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  49843. if (!globalColorList) {
  49844. return;
  49845. }
  49846. levels = levels || [];
  49847. var hasColorDefine;
  49848. var hasDecalDefine;
  49849. each(levels, function (levelDefine) {
  49850. var model = new Model(levelDefine);
  49851. var modelColor = model.get('color');
  49852. var modelDecal = model.get('decal');
  49853. if (model.get(['itemStyle', 'color']) || modelColor && modelColor !== 'none') {
  49854. hasColorDefine = true;
  49855. }
  49856. if (model.get(['itemStyle', 'decal']) || modelDecal && modelDecal !== 'none') {
  49857. hasDecalDefine = true;
  49858. }
  49859. });
  49860. var level0 = levels[0] || (levels[0] = {});
  49861. if (!hasColorDefine) {
  49862. level0.color = globalColorList.slice();
  49863. }
  49864. if (!hasDecalDefine && globalDecalList) {
  49865. level0.decal = globalDecalList.slice();
  49866. }
  49867. return levels;
  49868. }
  49869. var TEXT_PADDING = 8;
  49870. var ITEM_GAP = 8;
  49871. var ARRAY_LENGTH = 5;
  49872. var Breadcrumb =
  49873. /** @class */
  49874. function () {
  49875. function Breadcrumb(containerGroup) {
  49876. this.group = new Group();
  49877. containerGroup.add(this.group);
  49878. }
  49879. Breadcrumb.prototype.render = function (seriesModel, api, targetNode, onSelect) {
  49880. var model = seriesModel.getModel('breadcrumb');
  49881. var thisGroup = this.group;
  49882. thisGroup.removeAll();
  49883. if (!model.get('show') || !targetNode) {
  49884. return;
  49885. }
  49886. var normalStyleModel = model.getModel('itemStyle');
  49887. var emphasisModel = model.getModel('emphasis');
  49888. var textStyleModel = normalStyleModel.getModel('textStyle');
  49889. var emphasisTextStyleModel = emphasisModel.getModel(['itemStyle', 'textStyle']);
  49890. var layoutParam = {
  49891. pos: {
  49892. left: model.get('left'),
  49893. right: model.get('right'),
  49894. top: model.get('top'),
  49895. bottom: model.get('bottom')
  49896. },
  49897. box: {
  49898. width: api.getWidth(),
  49899. height: api.getHeight()
  49900. },
  49901. emptyItemWidth: model.get('emptyItemWidth'),
  49902. totalWidth: 0,
  49903. renderList: []
  49904. };
  49905. this._prepare(targetNode, layoutParam, textStyleModel);
  49906. this._renderContent(seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect);
  49907. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  49908. };
  49909. /**
  49910. * Prepare render list and total width
  49911. * @private
  49912. */
  49913. Breadcrumb.prototype._prepare = function (targetNode, layoutParam, textStyleModel) {
  49914. for (var node = targetNode; node; node = node.parentNode) {
  49915. var text = convertOptionIdName(node.getModel().get('name'), '');
  49916. var textRect = textStyleModel.getTextRect(text);
  49917. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  49918. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  49919. layoutParam.renderList.push({
  49920. node: node,
  49921. text: text,
  49922. width: itemWidth
  49923. });
  49924. }
  49925. };
  49926. /**
  49927. * @private
  49928. */
  49929. Breadcrumb.prototype._renderContent = function (seriesModel, layoutParam, normalStyleModel, emphasisModel, textStyleModel, emphasisTextStyleModel, onSelect) {
  49930. // Start rendering.
  49931. var lastX = 0;
  49932. var emptyItemWidth = layoutParam.emptyItemWidth;
  49933. var height = seriesModel.get(['breadcrumb', 'height']);
  49934. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  49935. var totalWidth = layoutParam.totalWidth;
  49936. var renderList = layoutParam.renderList;
  49937. var emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  49938. for (var i = renderList.length - 1; i >= 0; i--) {
  49939. var item = renderList[i];
  49940. var itemNode = item.node;
  49941. var itemWidth = item.width;
  49942. var text = item.text; // Hdie text and shorten width if necessary.
  49943. if (totalWidth > availableSize.width) {
  49944. totalWidth -= itemWidth - emptyItemWidth;
  49945. itemWidth = emptyItemWidth;
  49946. text = null;
  49947. }
  49948. var el = new Polygon({
  49949. shape: {
  49950. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  49951. },
  49952. style: defaults(normalStyleModel.getItemStyle(), {
  49953. lineJoin: 'bevel'
  49954. }),
  49955. textContent: new ZRText({
  49956. style: createTextStyle(textStyleModel, {
  49957. text: text
  49958. })
  49959. }),
  49960. textConfig: {
  49961. position: 'inside'
  49962. },
  49963. z2: Z2_EMPHASIS_LIFT * 1e4,
  49964. onclick: curry(onSelect, itemNode)
  49965. });
  49966. el.disableLabelAnimation = true;
  49967. el.getTextContent().ensureState('emphasis').style = createTextStyle(emphasisTextStyleModel, {
  49968. text: text
  49969. });
  49970. el.ensureState('emphasis').style = emphasisItemStyle;
  49971. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  49972. this.group.add(el);
  49973. packEventData(el, seriesModel, itemNode);
  49974. lastX += itemWidth + ITEM_GAP;
  49975. }
  49976. };
  49977. Breadcrumb.prototype.remove = function () {
  49978. this.group.removeAll();
  49979. };
  49980. return Breadcrumb;
  49981. }();
  49982. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  49983. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  49984. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  49985. !head && points.push([x, y + itemHeight / 2]);
  49986. return points;
  49987. } // Package custom mouse event.
  49988. function packEventData(el, seriesModel, itemNode) {
  49989. getECData(el).eventData = {
  49990. componentType: 'series',
  49991. componentSubType: 'treemap',
  49992. componentIndex: seriesModel.componentIndex,
  49993. seriesIndex: seriesModel.seriesIndex,
  49994. seriesName: seriesModel.name,
  49995. seriesType: 'treemap',
  49996. selfType: 'breadcrumb',
  49997. nodeData: {
  49998. dataIndex: itemNode && itemNode.dataIndex,
  49999. name: itemNode && itemNode.name
  50000. },
  50001. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  50002. };
  50003. }
  50004. /*
  50005. * Licensed to the Apache Software Foundation (ASF) under one
  50006. * or more contributor license agreements. See the NOTICE file
  50007. * distributed with this work for additional information
  50008. * regarding copyright ownership. The ASF licenses this file
  50009. * to you under the Apache License, Version 2.0 (the
  50010. * "License"); you may not use this file except in compliance
  50011. * with the License. You may obtain a copy of the License at
  50012. *
  50013. * http://www.apache.org/licenses/LICENSE-2.0
  50014. *
  50015. * Unless required by applicable law or agreed to in writing,
  50016. * software distributed under the License is distributed on an
  50017. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50018. * KIND, either express or implied. See the License for the
  50019. * specific language governing permissions and limitations
  50020. * under the License.
  50021. */
  50022. /**
  50023. * AUTO-GENERATED FILE. DO NOT MODIFY.
  50024. */
  50025. /*
  50026. * Licensed to the Apache Software Foundation (ASF) under one
  50027. * or more contributor license agreements. See the NOTICE file
  50028. * distributed with this work for additional information
  50029. * regarding copyright ownership. The ASF licenses this file
  50030. * to you under the Apache License, Version 2.0 (the
  50031. * "License"); you may not use this file except in compliance
  50032. * with the License. You may obtain a copy of the License at
  50033. *
  50034. * http://www.apache.org/licenses/LICENSE-2.0
  50035. *
  50036. * Unless required by applicable law or agreed to in writing,
  50037. * software distributed under the License is distributed on an
  50038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50039. * KIND, either express or implied. See the License for the
  50040. * specific language governing permissions and limitations
  50041. * under the License.
  50042. */
  50043. /**
  50044. * Animate multiple elements with a single done-callback.
  50045. *
  50046. * @example
  50047. * animation
  50048. * .createWrap()
  50049. * .add(el1, {x: 10, y: 10})
  50050. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  50051. * .done(function () { // done })
  50052. * .start('cubicOut');
  50053. */
  50054. var AnimationWrap =
  50055. /** @class */
  50056. function () {
  50057. function AnimationWrap() {
  50058. this._storage = [];
  50059. this._elExistsMap = {};
  50060. }
  50061. /**
  50062. * Caution: a el can only be added once, otherwise 'done'
  50063. * might not be called. This method checks this (by el.id),
  50064. * suppresses adding and returns false when existing el found.
  50065. *
  50066. * @return Whether adding succeeded.
  50067. */
  50068. AnimationWrap.prototype.add = function (el, target, duration, delay, easing) {
  50069. if (this._elExistsMap[el.id]) {
  50070. return false;
  50071. }
  50072. this._elExistsMap[el.id] = true;
  50073. this._storage.push({
  50074. el: el,
  50075. target: target,
  50076. duration: duration,
  50077. delay: delay,
  50078. easing: easing
  50079. });
  50080. return true;
  50081. };
  50082. /**
  50083. * Only execute when animation done/aborted.
  50084. */
  50085. AnimationWrap.prototype.finished = function (callback) {
  50086. this._finishedCallback = callback;
  50087. return this;
  50088. };
  50089. /**
  50090. * Will stop exist animation firstly.
  50091. */
  50092. AnimationWrap.prototype.start = function () {
  50093. var _this = this;
  50094. var count = this._storage.length;
  50095. var checkTerminate = function () {
  50096. count--;
  50097. if (count <= 0) {
  50098. // Guard.
  50099. _this._storage.length = 0;
  50100. _this._elExistsMap = {};
  50101. _this._finishedCallback && _this._finishedCallback();
  50102. }
  50103. };
  50104. for (var i = 0, len = this._storage.length; i < len; i++) {
  50105. var item = this._storage[i];
  50106. item.el.animateTo(item.target, {
  50107. duration: item.duration,
  50108. delay: item.delay,
  50109. easing: item.easing,
  50110. setToFinal: true,
  50111. done: checkTerminate,
  50112. aborted: checkTerminate
  50113. });
  50114. }
  50115. return this;
  50116. };
  50117. return AnimationWrap;
  50118. }();
  50119. function createWrap() {
  50120. return new AnimationWrap();
  50121. }
  50122. var Group$1 = Group;
  50123. var Rect$1 = Rect;
  50124. var DRAG_THRESHOLD = 3;
  50125. var PATH_LABEL_NOAMAL = 'label';
  50126. var PATH_UPPERLABEL_NORMAL = 'upperLabel'; // Should larger than emphasis states lift z
  50127. var Z2_BASE = Z2_EMPHASIS_LIFT * 10; // Should bigger than every z2.
  50128. var Z2_BG = Z2_EMPHASIS_LIFT * 2;
  50129. var Z2_CONTENT = Z2_EMPHASIS_LIFT * 3;
  50130. var getStateItemStyle = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  50131. // so use `stroke` to indicate the stroke of the rect.
  50132. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  50133. // So do not transfer decal directly.
  50134. ]);
  50135. var getItemStyleNormal = function (model) {
  50136. // Normal style props should include emphasis style props.
  50137. var itemStyle = getStateItemStyle(model); // Clear styles set by emphasis.
  50138. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  50139. return itemStyle;
  50140. };
  50141. var inner$8 = makeInner();
  50142. var TreemapView =
  50143. /** @class */
  50144. function (_super) {
  50145. __extends(TreemapView, _super);
  50146. function TreemapView() {
  50147. var _this = _super !== null && _super.apply(this, arguments) || this;
  50148. _this.type = TreemapView.type;
  50149. _this._state = 'ready';
  50150. _this._storage = createStorage();
  50151. return _this;
  50152. }
  50153. /**
  50154. * @override
  50155. */
  50156. TreemapView.prototype.render = function (seriesModel, ecModel, api, payload) {
  50157. var models = ecModel.findComponents({
  50158. mainType: 'series',
  50159. subType: 'treemap',
  50160. query: payload
  50161. });
  50162. if (indexOf(models, seriesModel) < 0) {
  50163. return;
  50164. }
  50165. this.seriesModel = seriesModel;
  50166. this.api = api;
  50167. this.ecModel = ecModel;
  50168. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  50169. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  50170. var payloadType = payload && payload.type;
  50171. var layoutInfo = seriesModel.layoutInfo;
  50172. var isInit = !this._oldTree;
  50173. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  50174. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  50175. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  50176. direction: payload.direction
  50177. } : null;
  50178. var containerGroup = this._giveContainerGroup(layoutInfo);
  50179. var hasAnimation = seriesModel.get('animation');
  50180. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  50181. hasAnimation && !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  50182. this._resetController(api);
  50183. this._renderBreadcrumb(seriesModel, api, targetInfo);
  50184. };
  50185. TreemapView.prototype._giveContainerGroup = function (layoutInfo) {
  50186. var containerGroup = this._containerGroup;
  50187. if (!containerGroup) {
  50188. // FIXME
  50189. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  50190. containerGroup = this._containerGroup = new Group$1();
  50191. this._initEvents(containerGroup);
  50192. this.group.add(containerGroup);
  50193. }
  50194. containerGroup.x = layoutInfo.x;
  50195. containerGroup.y = layoutInfo.y;
  50196. return containerGroup;
  50197. };
  50198. TreemapView.prototype._doRender = function (containerGroup, seriesModel, reRoot) {
  50199. var thisTree = seriesModel.getData().tree;
  50200. var oldTree = this._oldTree; // Clear last shape records.
  50201. var lastsForAnimation = createStorage();
  50202. var thisStorage = createStorage();
  50203. var oldStorage = this._storage;
  50204. var willInvisibleEls = [];
  50205. function doRenderNode(thisNode, oldNode, parentGroup, depth) {
  50206. return renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth);
  50207. } // Notice: When thisTree and oldTree are the same tree (see list.cloneShallow),
  50208. // the oldTree is actually losted, so we cannot find all of the old graphic
  50209. // elements from tree. So we use this strategy: make element storage, move
  50210. // from old storage to new storage, clear old storage.
  50211. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  50212. var willDeleteEls = clearStorage(oldStorage);
  50213. this._oldTree = thisTree;
  50214. this._storage = thisStorage;
  50215. return {
  50216. lastsForAnimation: lastsForAnimation,
  50217. willDeleteEls: willDeleteEls,
  50218. renderFinally: renderFinally
  50219. };
  50220. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  50221. // When 'render' is triggered by action,
  50222. // 'this' and 'old' may be the same tree,
  50223. // we use rawIndex in that case.
  50224. if (sameTree) {
  50225. oldViewChildren = thisViewChildren;
  50226. each(thisViewChildren, function (child, index) {
  50227. !child.isRemoved() && processNode(index, index);
  50228. });
  50229. } // Diff hierarchically (diff only in each subtree, but not whole).
  50230. // because, consistency of view is important.
  50231. else {
  50232. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  50233. }
  50234. function getKey(node) {
  50235. // Identify by name or raw index.
  50236. return node.getId();
  50237. }
  50238. function processNode(newIndex, oldIndex) {
  50239. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  50240. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  50241. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  50242. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  50243. }
  50244. }
  50245. function clearStorage(storage) {
  50246. var willDeleteEls = createStorage();
  50247. storage && each(storage, function (store, storageName) {
  50248. var delEls = willDeleteEls[storageName];
  50249. each(store, function (el) {
  50250. el && (delEls.push(el), inner$8(el).willDelete = true);
  50251. });
  50252. });
  50253. return willDeleteEls;
  50254. }
  50255. function renderFinally() {
  50256. each(willDeleteEls, function (els) {
  50257. each(els, function (el) {
  50258. el.parent && el.parent.remove(el);
  50259. });
  50260. });
  50261. each(willInvisibleEls, function (el) {
  50262. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  50263. // just mark as invisible.
  50264. el.dirty();
  50265. });
  50266. }
  50267. };
  50268. TreemapView.prototype._doAnimation = function (containerGroup, renderResult, seriesModel, reRoot) {
  50269. var durationOption = seriesModel.get('animationDurationUpdate');
  50270. var easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary.
  50271. var duration = (isFunction(durationOption) ? 0 : durationOption) || 0;
  50272. var easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut';
  50273. var animationWrap = createWrap(); // Make delete animations.
  50274. each(renderResult.willDeleteEls, function (store, storageName) {
  50275. each(store, function (el, rawIndex) {
  50276. if (el.invisible) {
  50277. return;
  50278. }
  50279. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  50280. var target;
  50281. var innerStore = inner$8(parent);
  50282. if (reRoot && reRoot.direction === 'drillDown') {
  50283. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  50284. // Only `content` will enter this branch, because
  50285. // `background` and `nodeGroup` will not be deleted.
  50286. ? {
  50287. shape: {
  50288. x: 0,
  50289. y: 0,
  50290. width: innerStore.nodeWidth,
  50291. height: innerStore.nodeHeight
  50292. },
  50293. style: {
  50294. opacity: 0
  50295. }
  50296. } // Others.
  50297. : {
  50298. style: {
  50299. opacity: 0
  50300. }
  50301. };
  50302. } else {
  50303. var targetX = 0;
  50304. var targetY = 0;
  50305. if (!innerStore.willDelete) {
  50306. // Let node animate to right-bottom corner, cooperating with fadeout,
  50307. // which is appropriate for user understanding.
  50308. // Divided by 2 for reRoot rolling up effect.
  50309. targetX = innerStore.nodeWidth / 2;
  50310. targetY = innerStore.nodeHeight / 2;
  50311. }
  50312. target = storageName === 'nodeGroup' ? {
  50313. x: targetX,
  50314. y: targetY,
  50315. style: {
  50316. opacity: 0
  50317. }
  50318. } : {
  50319. shape: {
  50320. x: targetX,
  50321. y: targetY,
  50322. width: 0,
  50323. height: 0
  50324. },
  50325. style: {
  50326. opacity: 0
  50327. }
  50328. };
  50329. } // TODO: do not support delay until necessary.
  50330. target && animationWrap.add(el, target, duration, 0, easing);
  50331. });
  50332. }); // Make other animations
  50333. each(this._storage, function (store, storageName) {
  50334. each(store, function (el, rawIndex) {
  50335. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  50336. var target = {};
  50337. if (!last) {
  50338. return;
  50339. }
  50340. if (el instanceof Group) {
  50341. if (last.oldX != null) {
  50342. target.x = el.x;
  50343. target.y = el.y;
  50344. el.x = last.oldX;
  50345. el.y = last.oldY;
  50346. }
  50347. } else {
  50348. if (last.oldShape) {
  50349. target.shape = extend({}, el.shape);
  50350. el.setShape(last.oldShape);
  50351. }
  50352. if (last.fadein) {
  50353. el.setStyle('opacity', 0);
  50354. target.style = {
  50355. opacity: 1
  50356. };
  50357. } // When animation is stopped for succedent animation starting,
  50358. // el.style.opacity might not be 1
  50359. else if (el.style.opacity !== 1) {
  50360. target.style = {
  50361. opacity: 1
  50362. };
  50363. }
  50364. }
  50365. animationWrap.add(el, target, duration, 0, easing);
  50366. });
  50367. }, this);
  50368. this._state = 'animating';
  50369. animationWrap.finished(bind(function () {
  50370. this._state = 'ready';
  50371. renderResult.renderFinally();
  50372. }, this)).start();
  50373. };
  50374. TreemapView.prototype._resetController = function (api) {
  50375. var controller = this._controller; // Init controller.
  50376. if (!controller) {
  50377. controller = this._controller = new RoamController(api.getZr());
  50378. controller.enable(this.seriesModel.get('roam'));
  50379. controller.on('pan', bind(this._onPan, this));
  50380. controller.on('zoom', bind(this._onZoom, this));
  50381. }
  50382. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  50383. controller.setPointerChecker(function (e, x, y) {
  50384. return rect.contain(x, y);
  50385. });
  50386. };
  50387. TreemapView.prototype._clearController = function () {
  50388. var controller = this._controller;
  50389. if (controller) {
  50390. controller.dispose();
  50391. controller = null;
  50392. }
  50393. };
  50394. TreemapView.prototype._onPan = function (e) {
  50395. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  50396. // These param must not be cached.
  50397. var root = this.seriesModel.getData().tree.root;
  50398. if (!root) {
  50399. return;
  50400. }
  50401. var rootLayout = root.getLayout();
  50402. if (!rootLayout) {
  50403. return;
  50404. }
  50405. this.api.dispatchAction({
  50406. type: 'treemapMove',
  50407. from: this.uid,
  50408. seriesId: this.seriesModel.id,
  50409. rootRect: {
  50410. x: rootLayout.x + e.dx,
  50411. y: rootLayout.y + e.dy,
  50412. width: rootLayout.width,
  50413. height: rootLayout.height
  50414. }
  50415. });
  50416. }
  50417. };
  50418. TreemapView.prototype._onZoom = function (e) {
  50419. var mouseX = e.originX;
  50420. var mouseY = e.originY;
  50421. if (this._state !== 'animating') {
  50422. // These param must not be cached.
  50423. var root = this.seriesModel.getData().tree.root;
  50424. if (!root) {
  50425. return;
  50426. }
  50427. var rootLayout = root.getLayout();
  50428. if (!rootLayout) {
  50429. return;
  50430. }
  50431. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  50432. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  50433. mouseX -= layoutInfo.x;
  50434. mouseY -= layoutInfo.y; // Scale root bounding rect.
  50435. var m = create$1();
  50436. translate(m, m, [-mouseX, -mouseY]);
  50437. scale$1(m, m, [e.scale, e.scale]);
  50438. translate(m, m, [mouseX, mouseY]);
  50439. rect.applyTransform(m);
  50440. this.api.dispatchAction({
  50441. type: 'treemapRender',
  50442. from: this.uid,
  50443. seriesId: this.seriesModel.id,
  50444. rootRect: {
  50445. x: rect.x,
  50446. y: rect.y,
  50447. width: rect.width,
  50448. height: rect.height
  50449. }
  50450. });
  50451. }
  50452. };
  50453. TreemapView.prototype._initEvents = function (containerGroup) {
  50454. var _this = this;
  50455. containerGroup.on('click', function (e) {
  50456. if (_this._state !== 'ready') {
  50457. return;
  50458. }
  50459. var nodeClick = _this.seriesModel.get('nodeClick', true);
  50460. if (!nodeClick) {
  50461. return;
  50462. }
  50463. var targetInfo = _this.findTarget(e.offsetX, e.offsetY);
  50464. if (!targetInfo) {
  50465. return;
  50466. }
  50467. var node = targetInfo.node;
  50468. if (node.getLayout().isLeafRoot) {
  50469. _this._rootToNode(targetInfo);
  50470. } else {
  50471. if (nodeClick === 'zoomToNode') {
  50472. _this._zoomToNode(targetInfo);
  50473. } else if (nodeClick === 'link') {
  50474. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  50475. var link = itemModel.get('link', true);
  50476. var linkTarget = itemModel.get('target', true) || 'blank';
  50477. link && windowOpen(link, linkTarget);
  50478. }
  50479. }
  50480. }, this);
  50481. };
  50482. TreemapView.prototype._renderBreadcrumb = function (seriesModel, api, targetInfo) {
  50483. var _this = this;
  50484. if (!targetInfo) {
  50485. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  50486. node: seriesModel.getViewRoot()
  50487. } // FIXME
  50488. // better way?
  50489. // Find breadcrumb tail on center of containerGroup.
  50490. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  50491. if (!targetInfo) {
  50492. targetInfo = {
  50493. node: seriesModel.getData().tree.root
  50494. };
  50495. }
  50496. }
  50497. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function (node) {
  50498. if (_this._state !== 'animating') {
  50499. aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({
  50500. node: node
  50501. }) : _this._zoomToNode({
  50502. node: node
  50503. });
  50504. }
  50505. });
  50506. };
  50507. /**
  50508. * @override
  50509. */
  50510. TreemapView.prototype.remove = function () {
  50511. this._clearController();
  50512. this._containerGroup && this._containerGroup.removeAll();
  50513. this._storage = createStorage();
  50514. this._state = 'ready';
  50515. this._breadcrumb && this._breadcrumb.remove();
  50516. };
  50517. TreemapView.prototype.dispose = function () {
  50518. this._clearController();
  50519. };
  50520. TreemapView.prototype._zoomToNode = function (targetInfo) {
  50521. this.api.dispatchAction({
  50522. type: 'treemapZoomToNode',
  50523. from: this.uid,
  50524. seriesId: this.seriesModel.id,
  50525. targetNode: targetInfo.node
  50526. });
  50527. };
  50528. TreemapView.prototype._rootToNode = function (targetInfo) {
  50529. this.api.dispatchAction({
  50530. type: 'treemapRootToNode',
  50531. from: this.uid,
  50532. seriesId: this.seriesModel.id,
  50533. targetNode: targetInfo.node
  50534. });
  50535. };
  50536. /**
  50537. * @public
  50538. * @param {number} x Global coord x.
  50539. * @param {number} y Global coord y.
  50540. * @return {Object} info If not found, return undefined;
  50541. * @return {number} info.node Target node.
  50542. * @return {number} info.offsetX x refer to target node.
  50543. * @return {number} info.offsetY y refer to target node.
  50544. */
  50545. TreemapView.prototype.findTarget = function (x, y) {
  50546. var targetInfo;
  50547. var viewRoot = this.seriesModel.getViewRoot();
  50548. viewRoot.eachNode({
  50549. attr: 'viewChildren',
  50550. order: 'preorder'
  50551. }, function (node) {
  50552. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  50553. if (bgEl) {
  50554. var point = bgEl.transformCoordToLocal(x, y);
  50555. var shape = bgEl.shape; // For performance consideration, don't use 'getBoundingRect'.
  50556. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  50557. targetInfo = {
  50558. node: node,
  50559. offsetX: point[0],
  50560. offsetY: point[1]
  50561. };
  50562. } else {
  50563. return false; // Suppress visit subtree.
  50564. }
  50565. }
  50566. }, this);
  50567. return targetInfo;
  50568. };
  50569. TreemapView.type = 'treemap';
  50570. return TreemapView;
  50571. }(ChartView);
  50572. /**
  50573. * @inner
  50574. */
  50575. function createStorage() {
  50576. return {
  50577. nodeGroup: [],
  50578. background: [],
  50579. content: []
  50580. };
  50581. }
  50582. /**
  50583. * @inner
  50584. * @return Return undefined means do not travel further.
  50585. */
  50586. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  50587. // Whether under viewRoot.
  50588. if (!thisNode) {
  50589. // Deleting nodes will be performed finally. This method just find
  50590. // element from old storage, or create new element, set them to new
  50591. // storage, and set styles.
  50592. return;
  50593. } // -------------------------------------------------------------------
  50594. // Start of closure variables available in "Procedures in renderNode".
  50595. var thisLayout = thisNode.getLayout();
  50596. var data = seriesModel.getData();
  50597. var nodeModel = thisNode.getModel(); // Only for enabling highlight/downplay. Clear firstly.
  50598. // Because some node will not be rendered.
  50599. data.setItemGraphicEl(thisNode.dataIndex, null);
  50600. if (!thisLayout || !thisLayout.isInView) {
  50601. return;
  50602. }
  50603. var thisWidth = thisLayout.width;
  50604. var thisHeight = thisLayout.height;
  50605. var borderWidth = thisLayout.borderWidth;
  50606. var thisInvisible = thisLayout.invisible;
  50607. var thisRawIndex = thisNode.getRawIndex();
  50608. var oldRawIndex = oldNode && oldNode.getRawIndex();
  50609. var thisViewChildren = thisNode.viewChildren;
  50610. var upperHeight = thisLayout.upperHeight;
  50611. var isParent = thisViewChildren && thisViewChildren.length;
  50612. var itemStyleNormalModel = nodeModel.getModel('itemStyle');
  50613. var itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']);
  50614. var itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']);
  50615. var itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']);
  50616. var borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode".
  50617. // -----------------------------------------------------------------
  50618. // Node group
  50619. var group = giveGraphic('nodeGroup', Group$1);
  50620. if (!group) {
  50621. return;
  50622. }
  50623. parentGroup.add(group); // x,y are not set when el is above view root.
  50624. group.x = thisLayout.x || 0;
  50625. group.y = thisLayout.y || 0;
  50626. group.markRedraw();
  50627. inner$8(group).nodeWidth = thisWidth;
  50628. inner$8(group).nodeHeight = thisHeight;
  50629. if (thisLayout.isAboveViewRoot) {
  50630. return group;
  50631. } // Background
  50632. var bg = giveGraphic('background', Rect$1, depth, Z2_BG);
  50633. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  50634. var emphasisModel = nodeModel.getModel('emphasis');
  50635. var focus = emphasisModel.get('focus');
  50636. var blurScope = emphasisModel.get('blurScope');
  50637. var isDisabled = emphasisModel.get('disabled');
  50638. var focusOrIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : focus; // No children, render content.
  50639. if (isParent) {
  50640. // Because of the implementation about "traverse" in graphic hover style, we
  50641. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  50642. // hover event from the descendents will be listenered.
  50643. if (isHighDownDispatcher(group)) {
  50644. setAsHighDownDispatcher(group, false);
  50645. }
  50646. if (bg) {
  50647. setAsHighDownDispatcher(bg, !isDisabled); // Only for enabling highlight/downplay.
  50648. data.setItemGraphicEl(thisNode.dataIndex, bg);
  50649. enableHoverFocus(bg, focusOrIndices, blurScope);
  50650. }
  50651. } else {
  50652. var content = giveGraphic('content', Rect$1, depth, Z2_CONTENT);
  50653. content && renderContent(group, content);
  50654. bg.disableMorphing = true;
  50655. if (bg && isHighDownDispatcher(bg)) {
  50656. setAsHighDownDispatcher(bg, false);
  50657. }
  50658. setAsHighDownDispatcher(group, !isDisabled); // Only for enabling highlight/downplay.
  50659. data.setItemGraphicEl(thisNode.dataIndex, group);
  50660. enableHoverFocus(group, focusOrIndices, blurScope);
  50661. }
  50662. return group; // ----------------------------
  50663. // | Procedures in renderNode |
  50664. // ----------------------------
  50665. function renderBackground(group, bg, useUpperLabel) {
  50666. var ecData = getECData(bg); // For tooltip.
  50667. ecData.dataIndex = thisNode.dataIndex;
  50668. ecData.seriesIndex = seriesModel.seriesIndex;
  50669. bg.setShape({
  50670. x: 0,
  50671. y: 0,
  50672. width: thisWidth,
  50673. height: thisHeight,
  50674. r: borderRadius
  50675. });
  50676. if (thisInvisible) {
  50677. // If invisible, do not set visual, otherwise the element will
  50678. // change immediately before animation. We think it is OK to
  50679. // remain its origin color when moving out of the view window.
  50680. processInvisible(bg);
  50681. } else {
  50682. bg.invisible = false;
  50683. var style = thisNode.getVisual('style');
  50684. var visualBorderColor = style.stroke;
  50685. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50686. normalStyle.fill = visualBorderColor;
  50687. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50688. emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor');
  50689. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50690. blurStyle.fill = itemStyleBlurModel.get('borderColor');
  50691. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  50692. selectStyle.fill = itemStyleSelectModel.get('borderColor');
  50693. if (useUpperLabel) {
  50694. var upperLabelWidth = thisWidth - 2 * borderWidth;
  50695. prepareText( // PENDING: convert ZRColor to ColorString for text.
  50696. bg, visualBorderColor, style.opacity, {
  50697. x: borderWidth,
  50698. y: 0,
  50699. width: upperLabelWidth,
  50700. height: upperHeight
  50701. });
  50702. } // For old bg.
  50703. else {
  50704. bg.removeTextContent();
  50705. }
  50706. bg.setStyle(normalStyle);
  50707. bg.ensureState('emphasis').style = emphasisStyle;
  50708. bg.ensureState('blur').style = blurStyle;
  50709. bg.ensureState('select').style = selectStyle;
  50710. setDefaultStateProxy(bg);
  50711. }
  50712. group.add(bg);
  50713. }
  50714. function renderContent(group, content) {
  50715. var ecData = getECData(content); // For tooltip.
  50716. ecData.dataIndex = thisNode.dataIndex;
  50717. ecData.seriesIndex = seriesModel.seriesIndex;
  50718. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  50719. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  50720. content.culling = true;
  50721. content.setShape({
  50722. x: borderWidth,
  50723. y: borderWidth,
  50724. width: contentWidth,
  50725. height: contentHeight,
  50726. r: borderRadius
  50727. });
  50728. if (thisInvisible) {
  50729. // If invisible, do not set visual, otherwise the element will
  50730. // change immediately before animation. We think it is OK to
  50731. // remain its origin color when moving out of the view window.
  50732. processInvisible(content);
  50733. } else {
  50734. content.invisible = false;
  50735. var nodeStyle = thisNode.getVisual('style');
  50736. var visualColor = nodeStyle.fill;
  50737. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  50738. normalStyle.fill = visualColor;
  50739. normalStyle.decal = nodeStyle.decal;
  50740. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  50741. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  50742. var selectStyle = getStateItemStyle(itemStyleSelectModel); // PENDING: convert ZRColor to ColorString for text.
  50743. prepareText(content, visualColor, nodeStyle.opacity, null);
  50744. content.setStyle(normalStyle);
  50745. content.ensureState('emphasis').style = emphasisStyle;
  50746. content.ensureState('blur').style = blurStyle;
  50747. content.ensureState('select').style = selectStyle;
  50748. setDefaultStateProxy(content);
  50749. }
  50750. group.add(content);
  50751. }
  50752. function processInvisible(element) {
  50753. // Delay invisible setting utill animation finished,
  50754. // avoid element vanish suddenly before animation.
  50755. !element.invisible && willInvisibleEls.push(element);
  50756. }
  50757. function prepareText(rectEl, visualColor, visualOpacity, // Can be null/undefined
  50758. upperLabelRect) {
  50759. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  50760. var defaultText = convertOptionIdName(nodeModel.get('name'), null);
  50761. var isShow = normalLabelModel.getShallow('show');
  50762. setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), {
  50763. defaultText: isShow ? defaultText : null,
  50764. inheritColor: visualColor,
  50765. defaultOpacity: visualOpacity,
  50766. labelFetcher: seriesModel,
  50767. labelDataIndex: thisNode.dataIndex
  50768. });
  50769. var textEl = rectEl.getTextContent();
  50770. if (!textEl) {
  50771. return;
  50772. }
  50773. var textStyle = textEl.style;
  50774. var textPadding = normalizeCssArray(textStyle.padding || 0);
  50775. if (upperLabelRect) {
  50776. rectEl.setTextConfig({
  50777. layoutRect: upperLabelRect
  50778. });
  50779. textEl.disableLabelLayout = true;
  50780. }
  50781. textEl.beforeUpdate = function () {
  50782. var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0);
  50783. var height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0);
  50784. if (textStyle.width !== width || textStyle.height !== height) {
  50785. textEl.setStyle({
  50786. width: width,
  50787. height: height
  50788. });
  50789. }
  50790. };
  50791. textStyle.truncateMinChar = 2;
  50792. textStyle.lineOverflow = 'truncate';
  50793. addDrillDownIcon(textStyle, upperLabelRect, thisLayout);
  50794. var textEmphasisState = textEl.getState('emphasis');
  50795. addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout);
  50796. }
  50797. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  50798. var text = style ? style.text : null;
  50799. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  50800. var iconChar = seriesModel.get('drillDownIcon', true);
  50801. style.text = iconChar ? iconChar + ' ' + text : text;
  50802. }
  50803. }
  50804. function giveGraphic(storageName, Ctor, depth, z) {
  50805. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  50806. var lasts = lastsForAnimation[storageName];
  50807. if (element) {
  50808. // Remove from oldStorage
  50809. oldStorage[storageName][oldRawIndex] = null;
  50810. prepareAnimationWhenHasOld(lasts, element);
  50811. } // If invisible and no old element, do not create new element (for optimizing).
  50812. else if (!thisInvisible) {
  50813. element = new Ctor();
  50814. if (element instanceof Displayable) {
  50815. element.z2 = calculateZ2(depth, z);
  50816. }
  50817. prepareAnimationWhenNoOld(lasts, element);
  50818. } // Set to thisStorage
  50819. return thisStorage[storageName][thisRawIndex] = element;
  50820. }
  50821. function prepareAnimationWhenHasOld(lasts, element) {
  50822. var lastCfg = lasts[thisRawIndex] = {};
  50823. if (element instanceof Group$1) {
  50824. lastCfg.oldX = element.x;
  50825. lastCfg.oldY = element.y;
  50826. } else {
  50827. lastCfg.oldShape = extend({}, element.shape);
  50828. }
  50829. } // If a element is new, we need to find the animation start point carefully,
  50830. // otherwise it will looks strange when 'zoomToNode'.
  50831. function prepareAnimationWhenNoOld(lasts, element) {
  50832. var lastCfg = lasts[thisRawIndex] = {};
  50833. var parentNode = thisNode.parentNode;
  50834. var isGroup = element instanceof Group;
  50835. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  50836. var parentOldX = 0;
  50837. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  50838. // For convenience, get old bounding rect from background.
  50839. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  50840. if (!reRoot && parentOldBg && parentOldBg.oldShape) {
  50841. parentOldX = parentOldBg.oldShape.width;
  50842. parentOldY = parentOldBg.oldShape.height;
  50843. } // When no parent old shape found, its parent is new too,
  50844. // so we can just use {x:0, y:0}.
  50845. if (isGroup) {
  50846. lastCfg.oldX = 0;
  50847. lastCfg.oldY = parentOldY;
  50848. } else {
  50849. lastCfg.oldShape = {
  50850. x: parentOldX,
  50851. y: parentOldY,
  50852. width: 0,
  50853. height: 0
  50854. };
  50855. }
  50856. } // Fade in, user can be aware that these nodes are new.
  50857. lastCfg.fadein = !isGroup;
  50858. }
  50859. } // We cannot set all background with the same z, because the behaviour of
  50860. // drill down and roll up differ background creation sequence from tree
  50861. // hierarchy sequence, which cause lower background elements to overlap
  50862. // upper ones. So we calculate z based on depth.
  50863. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  50864. // treemap with large z overlaps other components.
  50865. function calculateZ2(depth, z2InLevel) {
  50866. return depth * Z2_BASE + z2InLevel;
  50867. }
  50868. var each$3 = each;
  50869. var isObject$3 = isObject;
  50870. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  50871. var VisualMapping =
  50872. /** @class */
  50873. function () {
  50874. function VisualMapping(option) {
  50875. var mappingMethod = option.mappingMethod;
  50876. var visualType = option.type;
  50877. var thisOption = this.option = clone(option);
  50878. this.type = visualType;
  50879. this.mappingMethod = mappingMethod;
  50880. this._normalizeData = normalizers[mappingMethod];
  50881. var visualHandler = VisualMapping.visualHandlers[visualType];
  50882. this.applyVisual = visualHandler.applyVisual;
  50883. this.getColorMapper = visualHandler.getColorMapper;
  50884. this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod];
  50885. if (mappingMethod === 'piecewise') {
  50886. normalizeVisualRange(thisOption);
  50887. preprocessForPiecewise(thisOption);
  50888. } else if (mappingMethod === 'category') {
  50889. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  50890. // which need no more preprocess except normalize visual.
  50891. : normalizeVisualRange(thisOption, true);
  50892. } else {
  50893. // mappingMethod === 'linear' or 'fixed'
  50894. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  50895. normalizeVisualRange(thisOption);
  50896. }
  50897. }
  50898. VisualMapping.prototype.mapValueToVisual = function (value) {
  50899. var normalized = this._normalizeData(value);
  50900. return this._normalizedToVisual(normalized, value);
  50901. };
  50902. VisualMapping.prototype.getNormalizer = function () {
  50903. return bind(this._normalizeData, this);
  50904. };
  50905. /**
  50906. * List available visual types.
  50907. *
  50908. * @public
  50909. * @return {Array.<string>}
  50910. */
  50911. VisualMapping.listVisualTypes = function () {
  50912. return keys(VisualMapping.visualHandlers);
  50913. }; // /**
  50914. // * @public
  50915. // */
  50916. // static addVisualHandler(name, handler) {
  50917. // visualHandlers[name] = handler;
  50918. // }
  50919. /**
  50920. * @public
  50921. */
  50922. VisualMapping.isValidType = function (visualType) {
  50923. return VisualMapping.visualHandlers.hasOwnProperty(visualType);
  50924. };
  50925. /**
  50926. * Convenient method.
  50927. * Visual can be Object or Array or primary type.
  50928. */
  50929. VisualMapping.eachVisual = function (visual, callback, context) {
  50930. if (isObject(visual)) {
  50931. each(visual, callback, context);
  50932. } else {
  50933. callback.call(context, visual);
  50934. }
  50935. };
  50936. VisualMapping.mapVisual = function (visual, callback, context) {
  50937. var isPrimary;
  50938. var newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = true, null);
  50939. VisualMapping.eachVisual(visual, function (v, key) {
  50940. var newVal = callback.call(context, v, key);
  50941. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  50942. });
  50943. return newVisual;
  50944. };
  50945. /**
  50946. * Retrieve visual properties from given object.
  50947. */
  50948. VisualMapping.retrieveVisuals = function (obj) {
  50949. var ret = {};
  50950. var hasVisual;
  50951. obj && each$3(VisualMapping.visualHandlers, function (h, visualType) {
  50952. if (obj.hasOwnProperty(visualType)) {
  50953. ret[visualType] = obj[visualType];
  50954. hasVisual = true;
  50955. }
  50956. });
  50957. return hasVisual ? ret : null;
  50958. };
  50959. /**
  50960. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  50961. *
  50962. * @public
  50963. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  50964. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  50965. * @return {Array.<string>} Sorted visual types.
  50966. */
  50967. VisualMapping.prepareVisualTypes = function (visualTypes) {
  50968. if (isArray(visualTypes)) {
  50969. visualTypes = visualTypes.slice();
  50970. } else if (isObject$3(visualTypes)) {
  50971. var types_1 = [];
  50972. each$3(visualTypes, function (item, type) {
  50973. types_1.push(type);
  50974. });
  50975. visualTypes = types_1;
  50976. } else {
  50977. return [];
  50978. }
  50979. visualTypes.sort(function (type1, type2) {
  50980. // color should be front of colorSaturation, colorAlpha, ...
  50981. // symbol and symbolSize do not matter.
  50982. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  50983. });
  50984. return visualTypes;
  50985. };
  50986. /**
  50987. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  50988. * Other visuals are only depends on themself.
  50989. */
  50990. VisualMapping.dependsOn = function (visualType1, visualType2) {
  50991. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  50992. };
  50993. /**
  50994. * @param value
  50995. * @param pieceList [{value: ..., interval: [min, max]}, ...]
  50996. * Always from small to big.
  50997. * @param findClosestWhenOutside Default to be false
  50998. * @return index
  50999. */
  51000. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  51001. var possibleI;
  51002. var abs = Infinity; // value has the higher priority.
  51003. for (var i = 0, len = pieceList.length; i < len; i++) {
  51004. var pieceValue = pieceList[i].value;
  51005. if (pieceValue != null) {
  51006. if (pieceValue === value // FIXME
  51007. // It is supposed to compare value according to value type of dimension,
  51008. // but currently value type can exactly be string or number.
  51009. // Compromise for numeric-like string (like '12'), especially
  51010. // in the case that visualMap.categories is ['22', '33'].
  51011. || isString(pieceValue) && pieceValue === value + '') {
  51012. return i;
  51013. }
  51014. findClosestWhenOutside && updatePossible(pieceValue, i);
  51015. }
  51016. }
  51017. for (var i = 0, len = pieceList.length; i < len; i++) {
  51018. var piece = pieceList[i];
  51019. var interval = piece.interval;
  51020. var close_1 = piece.close;
  51021. if (interval) {
  51022. if (interval[0] === -Infinity) {
  51023. if (littleThan(close_1[1], value, interval[1])) {
  51024. return i;
  51025. }
  51026. } else if (interval[1] === Infinity) {
  51027. if (littleThan(close_1[0], interval[0], value)) {
  51028. return i;
  51029. }
  51030. } else if (littleThan(close_1[0], interval[0], value) && littleThan(close_1[1], value, interval[1])) {
  51031. return i;
  51032. }
  51033. findClosestWhenOutside && updatePossible(interval[0], i);
  51034. findClosestWhenOutside && updatePossible(interval[1], i);
  51035. }
  51036. }
  51037. if (findClosestWhenOutside) {
  51038. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  51039. }
  51040. function updatePossible(val, index) {
  51041. var newAbs = Math.abs(val - value);
  51042. if (newAbs < abs) {
  51043. abs = newAbs;
  51044. possibleI = index;
  51045. }
  51046. }
  51047. };
  51048. VisualMapping.visualHandlers = {
  51049. color: {
  51050. applyVisual: makeApplyVisual('color'),
  51051. getColorMapper: function () {
  51052. var thisOption = this.option;
  51053. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  51054. !isNormalized && (value = this._normalizeData(value));
  51055. return doMapCategory.call(this, value);
  51056. } : function (value, isNormalized, out) {
  51057. // If output rgb array
  51058. // which will be much faster and useful in pixel manipulation
  51059. var returnRGBArray = !!out;
  51060. !isNormalized && (value = this._normalizeData(value));
  51061. out = fastLerp(value, thisOption.parsedVisual, out);
  51062. return returnRGBArray ? out : stringify(out, 'rgba');
  51063. }, this);
  51064. },
  51065. _normalizedToVisual: {
  51066. linear: function (normalized) {
  51067. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51068. },
  51069. category: doMapCategory,
  51070. piecewise: function (normalized, value) {
  51071. var result = getSpecifiedVisual.call(this, value);
  51072. if (result == null) {
  51073. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  51074. }
  51075. return result;
  51076. },
  51077. fixed: doMapFixed
  51078. }
  51079. },
  51080. colorHue: makePartialColorVisualHandler(function (color$1, value) {
  51081. return modifyHSL(color$1, value);
  51082. }),
  51083. colorSaturation: makePartialColorVisualHandler(function (color$1, value) {
  51084. return modifyHSL(color$1, null, value);
  51085. }),
  51086. colorLightness: makePartialColorVisualHandler(function (color$1, value) {
  51087. return modifyHSL(color$1, null, null, value);
  51088. }),
  51089. colorAlpha: makePartialColorVisualHandler(function (color$1, value) {
  51090. return modifyAlpha(color$1, value);
  51091. }),
  51092. decal: {
  51093. applyVisual: makeApplyVisual('decal'),
  51094. _normalizedToVisual: {
  51095. linear: null,
  51096. category: doMapCategory,
  51097. piecewise: null,
  51098. fixed: null
  51099. }
  51100. },
  51101. opacity: {
  51102. applyVisual: makeApplyVisual('opacity'),
  51103. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51104. },
  51105. liftZ: {
  51106. applyVisual: makeApplyVisual('liftZ'),
  51107. _normalizedToVisual: {
  51108. linear: doMapFixed,
  51109. category: doMapFixed,
  51110. piecewise: doMapFixed,
  51111. fixed: doMapFixed
  51112. }
  51113. },
  51114. symbol: {
  51115. applyVisual: function (value, getter, setter) {
  51116. var symbolCfg = this.mapValueToVisual(value);
  51117. setter('symbol', symbolCfg);
  51118. },
  51119. _normalizedToVisual: {
  51120. linear: doMapToArray,
  51121. category: doMapCategory,
  51122. piecewise: function (normalized, value) {
  51123. var result = getSpecifiedVisual.call(this, value);
  51124. if (result == null) {
  51125. result = doMapToArray.call(this, normalized);
  51126. }
  51127. return result;
  51128. },
  51129. fixed: doMapFixed
  51130. }
  51131. },
  51132. symbolSize: {
  51133. applyVisual: makeApplyVisual('symbolSize'),
  51134. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51135. }
  51136. };
  51137. return VisualMapping;
  51138. }();
  51139. function preprocessForPiecewise(thisOption) {
  51140. var pieceList = thisOption.pieceList;
  51141. thisOption.hasSpecialVisual = false;
  51142. each(pieceList, function (piece, index) {
  51143. piece.originIndex = index; // piece.visual is "result visual value" but not
  51144. // a visual range, so it does not need to be normalized.
  51145. if (piece.visual != null) {
  51146. thisOption.hasSpecialVisual = true;
  51147. }
  51148. });
  51149. }
  51150. function preprocessForSpecifiedCategory(thisOption) {
  51151. // Hash categories.
  51152. var categories = thisOption.categories;
  51153. var categoryMap = thisOption.categoryMap = {};
  51154. var visual = thisOption.visual;
  51155. each$3(categories, function (cate, index) {
  51156. categoryMap[cate] = index;
  51157. }); // Process visual map input.
  51158. if (!isArray(visual)) {
  51159. var visualArr_1 = [];
  51160. if (isObject(visual)) {
  51161. each$3(visual, function (v, cate) {
  51162. var index = categoryMap[cate];
  51163. visualArr_1[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  51164. });
  51165. } else {
  51166. // Is primary type, represents default visual.
  51167. visualArr_1[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  51168. }
  51169. visual = setVisualToOption(thisOption, visualArr_1);
  51170. } // Remove categories that has no visual,
  51171. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  51172. for (var i = categories.length - 1; i >= 0; i--) {
  51173. if (visual[i] == null) {
  51174. delete categoryMap[categories[i]];
  51175. categories.pop();
  51176. }
  51177. }
  51178. }
  51179. function normalizeVisualRange(thisOption, isCategory) {
  51180. var visual = thisOption.visual;
  51181. var visualArr = [];
  51182. if (isObject(visual)) {
  51183. each$3(visual, function (v) {
  51184. visualArr.push(v);
  51185. });
  51186. } else if (visual != null) {
  51187. visualArr.push(visual);
  51188. }
  51189. var doNotNeedPair = {
  51190. color: 1,
  51191. symbol: 1
  51192. };
  51193. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  51194. // Do not care visualArr.length === 0, which is illegal.
  51195. visualArr[1] = visualArr[0];
  51196. }
  51197. setVisualToOption(thisOption, visualArr);
  51198. }
  51199. function makePartialColorVisualHandler(applyValue) {
  51200. return {
  51201. applyVisual: function (value, getter, setter) {
  51202. // Only used in HSL
  51203. var colorChannel = this.mapValueToVisual(value); // Must not be array value
  51204. setter('color', applyValue(getter('color'), colorChannel));
  51205. },
  51206. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  51207. };
  51208. }
  51209. function doMapToArray(normalized) {
  51210. var visual = this.option.visual;
  51211. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {}; // TODO {}?
  51212. }
  51213. function makeApplyVisual(visualType) {
  51214. return function (value, getter, setter) {
  51215. setter(visualType, this.mapValueToVisual(value));
  51216. };
  51217. }
  51218. function doMapCategory(normalized) {
  51219. var visual = this.option.visual;
  51220. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  51221. }
  51222. function doMapFixed() {
  51223. // visual will be convert to array.
  51224. return this.option.visual[0];
  51225. }
  51226. /**
  51227. * Create mapped to numeric visual
  51228. */
  51229. function createNormalizedToNumericVisual(sourceExtent) {
  51230. return {
  51231. linear: function (normalized) {
  51232. return linearMap(normalized, sourceExtent, this.option.visual, true);
  51233. },
  51234. category: doMapCategory,
  51235. piecewise: function (normalized, value) {
  51236. var result = getSpecifiedVisual.call(this, value);
  51237. if (result == null) {
  51238. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  51239. }
  51240. return result;
  51241. },
  51242. fixed: doMapFixed
  51243. };
  51244. }
  51245. function getSpecifiedVisual(value) {
  51246. var thisOption = this.option;
  51247. var pieceList = thisOption.pieceList;
  51248. if (thisOption.hasSpecialVisual) {
  51249. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  51250. var piece = pieceList[pieceIndex];
  51251. if (piece && piece.visual) {
  51252. return piece.visual[this.type];
  51253. }
  51254. }
  51255. }
  51256. function setVisualToOption(thisOption, visualArr) {
  51257. thisOption.visual = visualArr;
  51258. if (thisOption.type === 'color') {
  51259. thisOption.parsedVisual = map(visualArr, function (item) {
  51260. var color$1 = parse(item);
  51261. if (!color$1 && "development" !== 'production') {
  51262. warn("'" + item + "' is an illegal color, fallback to '#000000'", true);
  51263. }
  51264. return color$1 || [0, 0, 0, 1];
  51265. });
  51266. }
  51267. return visualArr;
  51268. }
  51269. /**
  51270. * Normalizers by mapping methods.
  51271. */
  51272. var normalizers = {
  51273. linear: function (value) {
  51274. return linearMap(value, this.option.dataExtent, [0, 1], true);
  51275. },
  51276. piecewise: function (value) {
  51277. var pieceList = this.option.pieceList;
  51278. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  51279. if (pieceIndex != null) {
  51280. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  51281. }
  51282. },
  51283. category: function (value) {
  51284. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal value
  51285. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  51286. },
  51287. fixed: noop
  51288. };
  51289. function littleThan(close, a, b) {
  51290. return close ? a <= b : a < b;
  51291. }
  51292. var ITEM_STYLE_NORMAL = 'itemStyle';
  51293. var inner$9 = makeInner();
  51294. var treemapVisual = {
  51295. seriesType: 'treemap',
  51296. reset: function (seriesModel) {
  51297. var tree = seriesModel.getData().tree;
  51298. var root = tree.root;
  51299. if (root.isRemoved()) {
  51300. return;
  51301. }
  51302. travelTree(root, // Visual should calculate from tree root but not view root.
  51303. {}, seriesModel.getViewRoot().getAncestors(), seriesModel);
  51304. }
  51305. };
  51306. function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) {
  51307. var nodeModel = node.getModel();
  51308. var nodeLayout = node.getLayout();
  51309. var data = node.hostTree.data; // Optimize
  51310. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  51311. return;
  51312. }
  51313. var nodeItemStyleModel = nodeModel.getModel(ITEM_STYLE_NORMAL);
  51314. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel);
  51315. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'); // calculate border color
  51316. var borderColor = nodeItemStyleModel.get('borderColor');
  51317. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  51318. var thisNodeColor;
  51319. if (borderColorSaturation != null) {
  51320. // For performance, do not always execute 'calculateColor'.
  51321. thisNodeColor = calculateColor(visuals);
  51322. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  51323. }
  51324. existsStyle.stroke = borderColor;
  51325. var viewChildren = node.viewChildren;
  51326. if (!viewChildren || !viewChildren.length) {
  51327. thisNodeColor = calculateColor(visuals); // Apply visual to this node.
  51328. existsStyle.fill = thisNodeColor;
  51329. } else {
  51330. var mapping_1 = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  51331. each(viewChildren, function (child, index) {
  51332. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  51333. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  51334. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping_1, seriesModel);
  51335. travelTree(child, childVisual, viewRootAncestors, seriesModel);
  51336. }
  51337. });
  51338. }
  51339. }
  51340. function buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel) {
  51341. var visuals = extend({}, designatedVisual);
  51342. var designatedVisualItemStyle = seriesModel.designatedVisualItemStyle;
  51343. each(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  51344. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  51345. designatedVisualItemStyle[visualName] = designatedVisual[visualName];
  51346. var val = nodeItemStyleModel.get(visualName);
  51347. designatedVisualItemStyle[visualName] = null;
  51348. val != null && (visuals[visualName] = val);
  51349. });
  51350. return visuals;
  51351. }
  51352. function calculateColor(visuals) {
  51353. var color = getValueVisualDefine(visuals, 'color');
  51354. if (color) {
  51355. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  51356. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  51357. if (colorSaturation) {
  51358. color = modifyHSL(color, null, null, colorSaturation);
  51359. }
  51360. if (colorAlpha) {
  51361. color = modifyAlpha(color, colorAlpha);
  51362. }
  51363. return color;
  51364. }
  51365. }
  51366. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  51367. return thisNodeColor != null // Can only be string
  51368. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  51369. }
  51370. function getValueVisualDefine(visuals, name) {
  51371. var value = visuals[name];
  51372. if (value != null && value !== 'none') {
  51373. return value;
  51374. }
  51375. }
  51376. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  51377. if (!viewChildren || !viewChildren.length) {
  51378. return;
  51379. }
  51380. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  51381. if (!rangeVisual) {
  51382. return;
  51383. }
  51384. var visualMin = nodeModel.get('visualMin');
  51385. var visualMax = nodeModel.get('visualMax');
  51386. var dataExtent = nodeLayout.dataExtent.slice();
  51387. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  51388. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  51389. var colorMappingBy = nodeModel.get('colorMappingBy');
  51390. var opt = {
  51391. type: rangeVisual.name,
  51392. dataExtent: dataExtent,
  51393. visual: rangeVisual.range
  51394. };
  51395. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  51396. opt.mappingMethod = 'category';
  51397. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  51398. } else {
  51399. opt.mappingMethod = 'linear';
  51400. }
  51401. var mapping = new VisualMapping(opt);
  51402. inner$9(mapping).drColorMappingBy = colorMappingBy;
  51403. return mapping;
  51404. } // Notice: If we don't have the attribute 'colorRange', but only use
  51405. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  51406. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  51407. // this problem will be encountered:
  51408. // If a level-1 node doesn't have children, and its siblings have children,
  51409. // and colorRange is set on level-1, then the node cannot be colored.
  51410. // So we separate 'colorRange' and 'color' to different attributes.
  51411. function getRangeVisual(nodeModel, name) {
  51412. // 'colorRange', 'colorARange', 'colorSRange'.
  51413. // If not exists on this node, fetch from levels and series.
  51414. var range = nodeModel.get(name);
  51415. return isArray(range) && range.length ? {
  51416. name: name,
  51417. range: range
  51418. } : null;
  51419. }
  51420. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  51421. var childVisuals = extend({}, visuals);
  51422. if (mapping) {
  51423. // Only support color, colorAlpha, colorSaturation.
  51424. var mappingType = mapping.type;
  51425. var colorMappingBy = mappingType === 'color' && inner$9(mapping).drColorMappingBy;
  51426. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  51427. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  51428. }
  51429. return childVisuals;
  51430. }
  51431. var mathMax$7 = Math.max;
  51432. var mathMin$7 = Math.min;
  51433. var retrieveValue = retrieve;
  51434. var each$4 = each;
  51435. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  51436. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  51437. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  51438. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  51439. /**
  51440. * @public
  51441. */
  51442. var treemapLayout = {
  51443. seriesType: 'treemap',
  51444. reset: function (seriesModel, ecModel, api, payload) {
  51445. // Layout result in each node:
  51446. // {x, y, width, height, area, borderWidth}
  51447. var ecWidth = api.getWidth();
  51448. var ecHeight = api.getHeight();
  51449. var seriesOption = seriesModel.option;
  51450. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  51451. width: api.getWidth(),
  51452. height: api.getHeight()
  51453. });
  51454. var size = seriesOption.size || []; // Compatible with ec2.
  51455. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  51456. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  51457. var payloadType = payload && payload.type;
  51458. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  51459. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  51460. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  51461. var viewRoot = seriesModel.getViewRoot();
  51462. var viewAbovePath = getPathToRoot(viewRoot);
  51463. if (payloadType !== 'treemapMove') {
  51464. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  51465. var sort_1 = seriesOption.sort;
  51466. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  51467. // Default to be desc order.
  51468. sort_1 = 'desc';
  51469. }
  51470. var options = {
  51471. squareRatio: seriesOption.squareRatio,
  51472. sort: sort_1,
  51473. leafDepth: seriesOption.leafDepth
  51474. }; // layout should be cleared because using updateView but not update.
  51475. viewRoot.hostTree.clearLayouts(); // TODO
  51476. // optimize: if out of view clip, do not layout.
  51477. // But take care that if do not render node out of view clip,
  51478. // how to calculate start po
  51479. var viewRootLayout_1 = {
  51480. x: 0,
  51481. y: 0,
  51482. width: rootSize[0],
  51483. height: rootSize[1],
  51484. area: rootSize[0] * rootSize[1]
  51485. };
  51486. viewRoot.setLayout(viewRootLayout_1);
  51487. squarify(viewRoot, options, false, 0); // Supplement layout.
  51488. viewRootLayout_1 = viewRoot.getLayout();
  51489. each$4(viewAbovePath, function (node, index) {
  51490. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  51491. node.setLayout(extend({
  51492. dataExtent: [childValue, childValue],
  51493. borderWidth: 0,
  51494. upperHeight: 0
  51495. }, viewRootLayout_1));
  51496. });
  51497. }
  51498. var treeRoot = seriesModel.getData().tree.root;
  51499. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  51500. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  51501. // 现在没有clip功能,暂时取ec高宽。
  51502. prunning(treeRoot, // Transform to base element coordinate system.
  51503. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  51504. }
  51505. };
  51506. /**
  51507. * Layout treemap with squarify algorithm.
  51508. * The original presentation of this algorithm
  51509. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  51510. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  51511. * The implementation of this algorithm was originally copied from "d3.js"
  51512. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  51513. * with some modifications made for this program.
  51514. * See the license statement at the head of this file.
  51515. *
  51516. * @protected
  51517. * @param {module:echarts/data/Tree~TreeNode} node
  51518. * @param {Object} options
  51519. * @param {string} options.sort 'asc' or 'desc'
  51520. * @param {number} options.squareRatio
  51521. * @param {boolean} hideChildren
  51522. * @param {number} depth
  51523. */
  51524. function squarify(node, options, hideChildren, depth) {
  51525. var width;
  51526. var height;
  51527. if (node.isRemoved()) {
  51528. return;
  51529. }
  51530. var thisLayout = node.getLayout();
  51531. width = thisLayout.width;
  51532. height = thisLayout.height; // Considering border and gap
  51533. var nodeModel = node.getModel();
  51534. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  51535. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  51536. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  51537. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  51538. var layoutOffset = borderWidth - halfGapWidth;
  51539. var layoutOffsetUpper = upperHeight - halfGapWidth;
  51540. node.setLayout({
  51541. borderWidth: borderWidth,
  51542. upperHeight: upperHeight,
  51543. upperLabelHeight: upperLabelHeight
  51544. }, true);
  51545. width = mathMax$7(width - 2 * layoutOffset, 0);
  51546. height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0);
  51547. var totalArea = width * height;
  51548. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  51549. if (!viewChildren.length) {
  51550. return;
  51551. }
  51552. var rect = {
  51553. x: layoutOffset,
  51554. y: layoutOffsetUpper,
  51555. width: width,
  51556. height: height
  51557. };
  51558. var rowFixedLength = mathMin$7(width, height);
  51559. var best = Infinity; // the best row score so far
  51560. var row = [];
  51561. row.area = 0;
  51562. for (var i = 0, len = viewChildren.length; i < len;) {
  51563. var child = viewChildren[i];
  51564. row.push(child);
  51565. row.area += child.getLayout().area;
  51566. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  51567. if (score <= best) {
  51568. i++;
  51569. best = score;
  51570. } // abort, and try a different orientation
  51571. else {
  51572. row.area -= row.pop().getLayout().area;
  51573. position(row, rowFixedLength, rect, halfGapWidth, false);
  51574. rowFixedLength = mathMin$7(rect.width, rect.height);
  51575. row.length = row.area = 0;
  51576. best = Infinity;
  51577. }
  51578. }
  51579. if (row.length) {
  51580. position(row, rowFixedLength, rect, halfGapWidth, true);
  51581. }
  51582. if (!hideChildren) {
  51583. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  51584. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  51585. hideChildren = true;
  51586. }
  51587. }
  51588. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51589. squarify(viewChildren[i], options, hideChildren, depth + 1);
  51590. }
  51591. }
  51592. /**
  51593. * Set area to each child, and calculate data extent for visual coding.
  51594. */
  51595. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  51596. var viewChildren = node.children || [];
  51597. var orderBy = options.sort;
  51598. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  51599. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  51600. if (hideChildren && !overLeafDepth) {
  51601. return node.viewChildren = [];
  51602. } // Sort children, order by desc.
  51603. viewChildren = filter(viewChildren, function (child) {
  51604. return !child.isRemoved();
  51605. });
  51606. sort$1(viewChildren, orderBy);
  51607. var info = statistic(nodeModel, viewChildren, orderBy);
  51608. if (info.sum === 0) {
  51609. return node.viewChildren = [];
  51610. }
  51611. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  51612. if (info.sum === 0) {
  51613. return node.viewChildren = [];
  51614. } // Set area to each child.
  51615. for (var i = 0, len = viewChildren.length; i < len; i++) {
  51616. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  51617. viewChildren[i].setLayout({
  51618. area: area
  51619. });
  51620. }
  51621. if (overLeafDepth) {
  51622. viewChildren.length && node.setLayout({
  51623. isLeafRoot: true
  51624. }, true);
  51625. viewChildren.length = 0;
  51626. }
  51627. node.viewChildren = viewChildren;
  51628. node.setLayout({
  51629. dataExtent: info.dataExtent
  51630. }, true);
  51631. return viewChildren;
  51632. }
  51633. /**
  51634. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  51635. */
  51636. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  51637. // visibleMin is not supported yet when no option.sort.
  51638. if (!orderBy) {
  51639. return sum;
  51640. }
  51641. var visibleMin = nodeModel.get('visibleMin');
  51642. var len = orderedChildren.length;
  51643. var deletePoint = len; // Always travel from little value to big value.
  51644. for (var i = len - 1; i >= 0; i--) {
  51645. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  51646. if (value / sum * totalArea < visibleMin) {
  51647. deletePoint = i;
  51648. sum -= value;
  51649. }
  51650. }
  51651. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  51652. return sum;
  51653. }
  51654. /**
  51655. * Sort
  51656. */
  51657. function sort$1(viewChildren, orderBy) {
  51658. if (orderBy) {
  51659. viewChildren.sort(function (a, b) {
  51660. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  51661. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  51662. });
  51663. }
  51664. return viewChildren;
  51665. }
  51666. /**
  51667. * Statistic
  51668. */
  51669. function statistic(nodeModel, children, orderBy) {
  51670. // Calculate sum.
  51671. var sum = 0;
  51672. for (var i = 0, len = children.length; i < len; i++) {
  51673. sum += children[i].getValue();
  51674. } // Statistic data extent for latter visual coding.
  51675. // Notice: data extent should be calculate based on raw children
  51676. // but not filtered view children, otherwise visual mapping will not
  51677. // be stable when zoom (where children is filtered by visibleMin).
  51678. var dimension = nodeModel.get('visualDimension');
  51679. var dataExtent; // The same as area dimension.
  51680. if (!children || !children.length) {
  51681. dataExtent = [NaN, NaN];
  51682. } else if (dimension === 'value' && orderBy) {
  51683. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  51684. orderBy === 'asc' && dataExtent.reverse();
  51685. } // Other dimension.
  51686. else {
  51687. dataExtent = [Infinity, -Infinity];
  51688. each$4(children, function (child) {
  51689. var value = child.getValue(dimension);
  51690. value < dataExtent[0] && (dataExtent[0] = value);
  51691. value > dataExtent[1] && (dataExtent[1] = value);
  51692. });
  51693. }
  51694. return {
  51695. sum: sum,
  51696. dataExtent: dataExtent
  51697. };
  51698. }
  51699. /**
  51700. * Computes the score for the specified row,
  51701. * as the worst aspect ratio.
  51702. */
  51703. function worst(row, rowFixedLength, ratio) {
  51704. var areaMax = 0;
  51705. var areaMin = Infinity;
  51706. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  51707. area = row[i].getLayout().area;
  51708. if (area) {
  51709. area < areaMin && (areaMin = area);
  51710. area > areaMax && (areaMax = area);
  51711. }
  51712. }
  51713. var squareArea = row.area * row.area;
  51714. var f = rowFixedLength * rowFixedLength * ratio;
  51715. return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  51716. }
  51717. /**
  51718. * Positions the specified row of nodes. Modifies `rect`.
  51719. */
  51720. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  51721. // When rowFixedLength === rect.width,
  51722. // it is horizontal subdivision,
  51723. // rowFixedLength is the width of the subdivision,
  51724. // rowOtherLength is the height of the subdivision,
  51725. // and nodes will be positioned from left to right.
  51726. // wh[idx0WhenH] means: when horizontal,
  51727. // wh[idx0WhenH] => wh[0] => 'width'.
  51728. // xy[idx1WhenH] => xy[1] => 'y'.
  51729. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  51730. var idx1WhenH = 1 - idx0WhenH;
  51731. var xy = ['x', 'y'];
  51732. var wh = ['width', 'height'];
  51733. var last = rect[xy[idx0WhenH]];
  51734. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  51735. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  51736. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  51737. }
  51738. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  51739. var node = row[i];
  51740. var nodeLayout = {};
  51741. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  51742. 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.
  51743. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  51744. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  51745. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0);
  51746. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2);
  51747. nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2);
  51748. last += modWH;
  51749. node.setLayout(nodeLayout, true);
  51750. }
  51751. rect[xy[idx1WhenH]] += rowOtherLength;
  51752. rect[wh[idx1WhenH]] -= rowOtherLength;
  51753. } // Return [containerWidth, containerHeight] as default.
  51754. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  51755. // If targetInfo.node exists, we zoom to the node,
  51756. // so estimate whole width and height by target node.
  51757. var currNode = (targetInfo || {}).node;
  51758. var defaultSize = [containerWidth, containerHeight];
  51759. if (!currNode || currNode === viewRoot) {
  51760. return defaultSize;
  51761. }
  51762. var parent;
  51763. var viewArea = containerWidth * containerHeight;
  51764. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  51765. while (parent = currNode.parentNode) {
  51766. // jshint ignore:line
  51767. var sum = 0;
  51768. var siblings = parent.children;
  51769. for (var i = 0, len = siblings.length; i < len; i++) {
  51770. sum += siblings[i].getValue();
  51771. }
  51772. var currNodeValue = currNode.getValue();
  51773. if (currNodeValue === 0) {
  51774. return defaultSize;
  51775. }
  51776. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  51777. var parentModel = parent.getModel();
  51778. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  51779. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  51780. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  51781. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  51782. currNode = parent;
  51783. }
  51784. area < viewArea && (area = viewArea);
  51785. var scale = Math.pow(area / viewArea, 0.5);
  51786. return [containerWidth * scale, containerHeight * scale];
  51787. } // Root position based on coord of containerGroup
  51788. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  51789. if (rootRect) {
  51790. return {
  51791. x: rootRect.x,
  51792. y: rootRect.y
  51793. };
  51794. }
  51795. var defaultPosition = {
  51796. x: 0,
  51797. y: 0
  51798. };
  51799. if (!targetInfo) {
  51800. return defaultPosition;
  51801. } // If targetInfo is fetched by 'retrieveTargetInfo',
  51802. // old tree and new tree are the same tree,
  51803. // so the node still exists and we can visit it.
  51804. var targetNode = targetInfo.node;
  51805. var layout = targetNode.getLayout();
  51806. if (!layout) {
  51807. return defaultPosition;
  51808. } // Transform coord from local to container.
  51809. var targetCenter = [layout.width / 2, layout.height / 2];
  51810. var node = targetNode;
  51811. while (node) {
  51812. var nodeLayout = node.getLayout();
  51813. targetCenter[0] += nodeLayout.x;
  51814. targetCenter[1] += nodeLayout.y;
  51815. node = node.parentNode;
  51816. }
  51817. return {
  51818. x: layoutInfo.width / 2 - targetCenter[0],
  51819. y: layoutInfo.height / 2 - targetCenter[1]
  51820. };
  51821. } // Mark nodes visible for prunning when visual coding and rendering.
  51822. // Prunning depends on layout and root position, so we have to do it after layout.
  51823. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  51824. var nodeLayout = node.getLayout();
  51825. var nodeInViewAbovePath = viewAbovePath[depth];
  51826. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  51827. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  51828. return;
  51829. }
  51830. node.setLayout({
  51831. // isInView means: viewRoot sub tree + viewAbovePath
  51832. isInView: true,
  51833. // invisible only means: outside view clip so that the node can not
  51834. // see but still layout for animation preparation but not render.
  51835. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  51836. isAboveViewRoot: isAboveViewRoot
  51837. }, true); // Transform to child coordinate.
  51838. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  51839. each$4(node.viewChildren || [], function (child) {
  51840. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  51841. });
  51842. }
  51843. function getUpperLabelHeight(model) {
  51844. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  51845. }
  51846. function install$c(registers) {
  51847. registers.registerSeriesModel(TreemapSeriesModel);
  51848. registers.registerChartView(TreemapView);
  51849. registers.registerVisual(treemapVisual);
  51850. registers.registerLayout(treemapLayout);
  51851. installTreemapAction(registers);
  51852. }
  51853. function categoryFilter(ecModel) {
  51854. var legendModels = ecModel.findComponents({
  51855. mainType: 'legend'
  51856. });
  51857. if (!legendModels || !legendModels.length) {
  51858. return;
  51859. }
  51860. ecModel.eachSeriesByType('graph', function (graphSeries) {
  51861. var categoriesData = graphSeries.getCategoriesData();
  51862. var graph = graphSeries.getGraph();
  51863. var data = graph.data;
  51864. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  51865. data.filterSelf(function (idx) {
  51866. var model = data.getItemModel(idx);
  51867. var category = model.getShallow('category');
  51868. if (category != null) {
  51869. if (isNumber(category)) {
  51870. category = categoryNames[category];
  51871. } // If in any legend component the status is not selected.
  51872. for (var i = 0; i < legendModels.length; i++) {
  51873. if (!legendModels[i].isSelected(category)) {
  51874. return false;
  51875. }
  51876. }
  51877. }
  51878. return true;
  51879. });
  51880. });
  51881. }
  51882. function categoryVisual(ecModel) {
  51883. var paletteScope = {};
  51884. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51885. var categoriesData = seriesModel.getCategoriesData();
  51886. var data = seriesModel.getData();
  51887. var categoryNameIdxMap = {};
  51888. categoriesData.each(function (idx) {
  51889. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  51890. categoryNameIdxMap['ec-' + name] = idx;
  51891. var itemModel = categoriesData.getItemModel(idx);
  51892. var style = itemModel.getModel('itemStyle').getItemStyle();
  51893. if (!style.fill) {
  51894. // Get color from palette.
  51895. style.fill = seriesModel.getColorFromPalette(name, paletteScope);
  51896. }
  51897. categoriesData.setItemVisual(idx, 'style', style);
  51898. var symbolVisualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51899. for (var i = 0; i < symbolVisualList.length; i++) {
  51900. var symbolVisual = itemModel.getShallow(symbolVisualList[i], true);
  51901. if (symbolVisual != null) {
  51902. categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual);
  51903. }
  51904. }
  51905. }); // Assign category color to visual
  51906. if (categoriesData.count()) {
  51907. data.each(function (idx) {
  51908. var model = data.getItemModel(idx);
  51909. var categoryIdx = model.getShallow('category');
  51910. if (categoryIdx != null) {
  51911. if (isString(categoryIdx)) {
  51912. categoryIdx = categoryNameIdxMap['ec-' + categoryIdx];
  51913. }
  51914. var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style');
  51915. var style = data.ensureUniqueItemVisual(idx, 'style');
  51916. extend(style, categoryStyle);
  51917. var visualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  51918. for (var i = 0; i < visualList.length; i++) {
  51919. data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i]));
  51920. }
  51921. }
  51922. });
  51923. }
  51924. });
  51925. }
  51926. function normalize$2(a) {
  51927. if (!(a instanceof Array)) {
  51928. a = [a, a];
  51929. }
  51930. return a;
  51931. }
  51932. function graphEdgeVisual(ecModel) {
  51933. ecModel.eachSeriesByType('graph', function (seriesModel) {
  51934. var graph = seriesModel.getGraph();
  51935. var edgeData = seriesModel.getEdgeData();
  51936. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  51937. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); // const colorQuery = ['lineStyle', 'color'] as const;
  51938. // const opacityQuery = ['lineStyle', 'opacity'] as const;
  51939. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  51940. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  51941. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  51942. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  51943. edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle());
  51944. edgeData.each(function (idx) {
  51945. var itemModel = edgeData.getItemModel(idx);
  51946. var edge = graph.getEdgeByIndex(idx);
  51947. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  51948. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  51949. var style = itemModel.getModel('lineStyle').getLineStyle();
  51950. var existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style');
  51951. extend(existsStyle, style);
  51952. switch (existsStyle.stroke) {
  51953. case 'source':
  51954. {
  51955. var nodeStyle = edge.node1.getVisual('style');
  51956. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51957. break;
  51958. }
  51959. case 'target':
  51960. {
  51961. var nodeStyle = edge.node2.getVisual('style');
  51962. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  51963. break;
  51964. }
  51965. }
  51966. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  51967. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  51968. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  51969. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  51970. });
  51971. });
  51972. }
  51973. var KEY_DELIMITER = '-->';
  51974. /**
  51975. * params handler
  51976. * @param {module:echarts/model/SeriesModel} seriesModel
  51977. * @returns {*}
  51978. */
  51979. var getAutoCurvenessParams = function (seriesModel) {
  51980. return seriesModel.get('autoCurveness') || null;
  51981. };
  51982. /**
  51983. * Generate a list of edge curvatures, 20 is the default
  51984. * @param {module:echarts/model/SeriesModel} seriesModel
  51985. * @param {number} appendLength
  51986. * @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]
  51987. */
  51988. var createCurveness = function (seriesModel, appendLength) {
  51989. var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
  51990. var length = 20;
  51991. var curvenessList = []; // handler the function set
  51992. if (isNumber(autoCurvenessParmas)) {
  51993. length = autoCurvenessParmas;
  51994. } else if (isArray(autoCurvenessParmas)) {
  51995. seriesModel.__curvenessList = autoCurvenessParmas;
  51996. return;
  51997. } // append length
  51998. if (appendLength > length) {
  51999. length = appendLength;
  52000. } // make sure the length is even
  52001. var len = length % 2 ? length + 2 : length + 3;
  52002. curvenessList = [];
  52003. for (var i = 0; i < len; i++) {
  52004. curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
  52005. }
  52006. seriesModel.__curvenessList = curvenessList;
  52007. };
  52008. /**
  52009. * Create different cache key data in the positive and negative directions, in order to set the curvature later
  52010. * @param {number|string|module:echarts/data/Graph.Node} n1
  52011. * @param {number|string|module:echarts/data/Graph.Node} n2
  52012. * @param {module:echarts/model/SeriesModel} seriesModel
  52013. * @returns {string} key
  52014. */
  52015. var getKeyOfEdges = function (n1, n2, seriesModel) {
  52016. var source = [n1.id, n1.dataIndex].join('.');
  52017. var target = [n2.id, n2.dataIndex].join('.');
  52018. return [seriesModel.uid, source, target].join(KEY_DELIMITER);
  52019. };
  52020. /**
  52021. * get opposite key
  52022. * @param {string} key
  52023. * @returns {string}
  52024. */
  52025. var getOppositeKey = function (key) {
  52026. var keys = key.split(KEY_DELIMITER);
  52027. return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
  52028. };
  52029. /**
  52030. * get edgeMap with key
  52031. * @param edge
  52032. * @param {module:echarts/model/SeriesModel} seriesModel
  52033. */
  52034. var getEdgeFromMap = function (edge, seriesModel) {
  52035. var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52036. return seriesModel.__edgeMap[key];
  52037. };
  52038. /**
  52039. * calculate all cases total length
  52040. * @param edge
  52041. * @param seriesModel
  52042. * @returns {number}
  52043. */
  52044. var getTotalLengthBetweenNodes = function (edge, seriesModel) {
  52045. var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
  52046. var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);
  52047. return len + lenV;
  52048. };
  52049. /**
  52050. *
  52051. * @param key
  52052. */
  52053. var getEdgeMapLengthWithKey = function (key, seriesModel) {
  52054. var edgeMap = seriesModel.__edgeMap;
  52055. return edgeMap[key] ? edgeMap[key].length : 0;
  52056. };
  52057. /**
  52058. * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
  52059. * @see /graph/GraphSeries.js@getInitialData
  52060. * @param {module:echarts/model/SeriesModel} seriesModel
  52061. */
  52062. function initCurvenessList(seriesModel) {
  52063. if (!getAutoCurvenessParams(seriesModel)) {
  52064. return;
  52065. }
  52066. seriesModel.__curvenessList = [];
  52067. seriesModel.__edgeMap = {}; // calc the array of curveness List
  52068. createCurveness(seriesModel);
  52069. }
  52070. /**
  52071. * set edgeMap with key
  52072. * @param {number|string|module:echarts/data/Graph.Node} n1
  52073. * @param {number|string|module:echarts/data/Graph.Node} n2
  52074. * @param {module:echarts/model/SeriesModel} seriesModel
  52075. * @param {number} index
  52076. */
  52077. function createEdgeMapForCurveness(n1, n2, seriesModel, index) {
  52078. if (!getAutoCurvenessParams(seriesModel)) {
  52079. return;
  52080. }
  52081. var key = getKeyOfEdges(n1, n2, seriesModel);
  52082. var edgeMap = seriesModel.__edgeMap;
  52083. var oppositeEdges = edgeMap[getOppositeKey(key)]; // set direction
  52084. if (edgeMap[key] && !oppositeEdges) {
  52085. edgeMap[key].isForward = true;
  52086. } else if (oppositeEdges && edgeMap[key]) {
  52087. oppositeEdges.isForward = true;
  52088. edgeMap[key].isForward = false;
  52089. }
  52090. edgeMap[key] = edgeMap[key] || [];
  52091. edgeMap[key].push(index);
  52092. }
  52093. /**
  52094. * get curvature for edge
  52095. * @param edge
  52096. * @param {module:echarts/model/SeriesModel} seriesModel
  52097. * @param index
  52098. */
  52099. function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
  52100. var autoCurvenessParams = getAutoCurvenessParams(seriesModel);
  52101. var isArrayParam = isArray(autoCurvenessParams);
  52102. if (!autoCurvenessParams) {
  52103. return null;
  52104. }
  52105. var edgeArray = getEdgeFromMap(edge, seriesModel);
  52106. if (!edgeArray) {
  52107. return null;
  52108. }
  52109. var edgeIndex = -1;
  52110. for (var i = 0; i < edgeArray.length; i++) {
  52111. if (edgeArray[i] === index) {
  52112. edgeIndex = i;
  52113. break;
  52114. }
  52115. } // if totalLen is Longer createCurveness
  52116. var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
  52117. createCurveness(seriesModel, totalLen);
  52118. edge.lineStyle = edge.lineStyle || {}; // if is opposite edge, must set curvenss to opposite number
  52119. var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  52120. var curvenessList = seriesModel.__curvenessList; // if pass array no need parity
  52121. var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;
  52122. if (!edgeArray.isForward) {
  52123. // the opposite edge show outside
  52124. var oppositeKey = getOppositeKey(curKey);
  52125. var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
  52126. var resValue = curvenessList[edgeIndex + len + parityCorrection]; // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
  52127. if (needReverse) {
  52128. // set as array may make the parity handle with the len of opposite
  52129. if (isArrayParam) {
  52130. if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
  52131. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52132. } else {
  52133. return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
  52134. }
  52135. } else {
  52136. return (len + parityCorrection) % 2 ? resValue : -resValue;
  52137. }
  52138. } else {
  52139. return curvenessList[edgeIndex + len + parityCorrection];
  52140. }
  52141. } else {
  52142. return curvenessList[parityCorrection + edgeIndex];
  52143. }
  52144. }
  52145. function simpleLayout(seriesModel) {
  52146. var coordSys = seriesModel.coordinateSystem;
  52147. if (coordSys && coordSys.type !== 'view') {
  52148. return;
  52149. }
  52150. var graph = seriesModel.getGraph();
  52151. graph.eachNode(function (node) {
  52152. var model = node.getModel();
  52153. node.setLayout([+model.get('x'), +model.get('y')]);
  52154. });
  52155. simpleLayoutEdge(graph, seriesModel);
  52156. }
  52157. function simpleLayoutEdge(graph, seriesModel) {
  52158. graph.eachEdge(function (edge, index) {
  52159. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, seriesModel, index, true), 0);
  52160. var p1 = clone$1(edge.node1.getLayout());
  52161. var p2 = clone$1(edge.node2.getLayout());
  52162. var points = [p1, p2];
  52163. if (+curveness) {
  52164. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  52165. }
  52166. edge.setLayout(points);
  52167. });
  52168. }
  52169. function graphSimpleLayout(ecModel, api) {
  52170. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52171. var layout = seriesModel.get('layout');
  52172. var coordSys = seriesModel.coordinateSystem;
  52173. if (coordSys && coordSys.type !== 'view') {
  52174. var data_1 = seriesModel.getData();
  52175. var dimensions_1 = [];
  52176. each(coordSys.dimensions, function (coordDim) {
  52177. dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim));
  52178. });
  52179. for (var dataIndex = 0; dataIndex < data_1.count(); dataIndex++) {
  52180. var value = [];
  52181. var hasValue = false;
  52182. for (var i = 0; i < dimensions_1.length; i++) {
  52183. var val = data_1.get(dimensions_1[i], dataIndex);
  52184. if (!isNaN(val)) {
  52185. hasValue = true;
  52186. }
  52187. value.push(val);
  52188. }
  52189. if (hasValue) {
  52190. data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  52191. } else {
  52192. // Also {Array.<number>}, not undefined to avoid if...else... statement
  52193. data_1.setItemLayout(dataIndex, [NaN, NaN]);
  52194. }
  52195. }
  52196. simpleLayoutEdge(data_1.graph, seriesModel);
  52197. } else if (!layout || layout === 'none') {
  52198. simpleLayout(seriesModel);
  52199. }
  52200. });
  52201. }
  52202. /*
  52203. * Licensed to the Apache Software Foundation (ASF) under one
  52204. * or more contributor license agreements. See the NOTICE file
  52205. * distributed with this work for additional information
  52206. * regarding copyright ownership. The ASF licenses this file
  52207. * to you under the Apache License, Version 2.0 (the
  52208. * "License"); you may not use this file except in compliance
  52209. * with the License. You may obtain a copy of the License at
  52210. *
  52211. * http://www.apache.org/licenses/LICENSE-2.0
  52212. *
  52213. * Unless required by applicable law or agreed to in writing,
  52214. * software distributed under the License is distributed on an
  52215. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52216. * KIND, either express or implied. See the License for the
  52217. * specific language governing permissions and limitations
  52218. * under the License.
  52219. */
  52220. /**
  52221. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52222. */
  52223. /*
  52224. * Licensed to the Apache Software Foundation (ASF) under one
  52225. * or more contributor license agreements. See the NOTICE file
  52226. * distributed with this work for additional information
  52227. * regarding copyright ownership. The ASF licenses this file
  52228. * to you under the Apache License, Version 2.0 (the
  52229. * "License"); you may not use this file except in compliance
  52230. * with the License. You may obtain a copy of the License at
  52231. *
  52232. * http://www.apache.org/licenses/LICENSE-2.0
  52233. *
  52234. * Unless required by applicable law or agreed to in writing,
  52235. * software distributed under the License is distributed on an
  52236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52237. * KIND, either express or implied. See the License for the
  52238. * specific language governing permissions and limitations
  52239. * under the License.
  52240. */
  52241. function getNodeGlobalScale(seriesModel) {
  52242. var coordSys = seriesModel.coordinateSystem;
  52243. if (coordSys.type !== 'view') {
  52244. return 1;
  52245. }
  52246. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  52247. var groupZoom = coordSys.scaleX; // Scale node when zoom changes
  52248. var roamZoom = coordSys.getZoom();
  52249. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  52250. return nodeScale / groupZoom;
  52251. }
  52252. function getSymbolSize(node) {
  52253. var symbolSize = node.getVisual('symbolSize');
  52254. if (symbolSize instanceof Array) {
  52255. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  52256. }
  52257. return +symbolSize;
  52258. }
  52259. var PI$6 = Math.PI;
  52260. var _symbolRadiansHalf = [];
  52261. /**
  52262. * `basedOn` can be:
  52263. * 'value':
  52264. * This layout is not accurate and have same bad case. For example,
  52265. * if the min value is very smaller than the max value, the nodes
  52266. * with the min value probably overlap even though there is enough
  52267. * space to layout them. So we only use this approach in the as the
  52268. * init layout of the force layout.
  52269. * FIXME
  52270. * Probably we do not need this method any more but use
  52271. * `basedOn: 'symbolSize'` in force layout if
  52272. * delay its init operations to GraphView.
  52273. * 'symbolSize':
  52274. * This approach work only if all of the symbol size calculated.
  52275. * That is, the progressive rendering is not applied to graph.
  52276. * FIXME
  52277. * If progressive rendering is applied to graph some day,
  52278. * probably we have to use `basedOn: 'value'`.
  52279. */
  52280. function circularLayout(seriesModel, basedOn, draggingNode, pointer) {
  52281. var coordSys = seriesModel.coordinateSystem;
  52282. if (coordSys && coordSys.type !== 'view') {
  52283. return;
  52284. }
  52285. var rect = coordSys.getBoundingRect();
  52286. var nodeData = seriesModel.getData();
  52287. var graph = nodeData.graph;
  52288. var cx = rect.width / 2 + rect.x;
  52289. var cy = rect.height / 2 + rect.y;
  52290. var r = Math.min(rect.width, rect.height) / 2;
  52291. var count = nodeData.count();
  52292. nodeData.setLayout({
  52293. cx: cx,
  52294. cy: cy
  52295. });
  52296. if (!count) {
  52297. return;
  52298. }
  52299. if (draggingNode) {
  52300. var _a = coordSys.pointToData(pointer),
  52301. tempX = _a[0],
  52302. tempY = _a[1];
  52303. var v = [tempX - cx, tempY - cy];
  52304. normalize(v, v);
  52305. scale(v, v, r);
  52306. draggingNode.setLayout([cx + v[0], cy + v[1]], true);
  52307. var circularRotateLabel = seriesModel.get(['circular', 'rotateLabel']);
  52308. rotateNodeLabel(draggingNode, circularRotateLabel, cx, cy);
  52309. }
  52310. _layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count);
  52311. graph.eachEdge(function (edge, index) {
  52312. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), getCurvenessForEdge(edge, seriesModel, index), 0);
  52313. var p1 = clone$1(edge.node1.getLayout());
  52314. var p2 = clone$1(edge.node2.getLayout());
  52315. var cp1;
  52316. var x12 = (p1[0] + p2[0]) / 2;
  52317. var y12 = (p1[1] + p2[1]) / 2;
  52318. if (+curveness) {
  52319. curveness *= 3;
  52320. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  52321. }
  52322. edge.setLayout([p1, p2, cp1]);
  52323. });
  52324. }
  52325. var _layoutNodesBasedOn = {
  52326. value: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52327. var angle = 0;
  52328. var sum = nodeData.getSum('value');
  52329. var unitAngle = Math.PI * 2 / (sum || count);
  52330. graph.eachNode(function (node) {
  52331. var value = node.getValue('value');
  52332. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  52333. angle += radianHalf;
  52334. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52335. angle += radianHalf;
  52336. });
  52337. },
  52338. symbolSize: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  52339. var sumRadian = 0;
  52340. _symbolRadiansHalf.length = count;
  52341. var nodeScale = getNodeGlobalScale(seriesModel);
  52342. graph.eachNode(function (node) {
  52343. var symbolSize = getSymbolSize(node); // Normally this case will not happen, but we still add
  52344. // some the defensive code (2px is an arbitrary value).
  52345. isNaN(symbolSize) && (symbolSize = 2);
  52346. symbolSize < 0 && (symbolSize = 0);
  52347. symbolSize *= nodeScale;
  52348. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  52349. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2);
  52350. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  52351. sumRadian += symbolRadianHalf * 2;
  52352. });
  52353. var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2;
  52354. var angle = 0;
  52355. graph.eachNode(function (node) {
  52356. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  52357. angle += radianHalf; // init circular layout for
  52358. // 1. layout undefined node
  52359. // 2. not fixed node
  52360. (!node.getLayout() || !node.getLayout().fixed) && node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  52361. angle += radianHalf;
  52362. });
  52363. }
  52364. };
  52365. function rotateNodeLabel(node, circularRotateLabel, cx, cy) {
  52366. var el = node.getGraphicEl(); // need to check if el exists. '-' value may not create node element.
  52367. if (!el) {
  52368. return;
  52369. }
  52370. var nodeModel = node.getModel();
  52371. var labelRotate = nodeModel.get(['label', 'rotate']) || 0;
  52372. var symbolPath = el.getSymbolPath();
  52373. if (circularRotateLabel) {
  52374. var pos = node.getLayout();
  52375. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  52376. if (rad < 0) {
  52377. rad = Math.PI * 2 + rad;
  52378. }
  52379. var isLeft = pos[0] < cx;
  52380. if (isLeft) {
  52381. rad = rad - Math.PI;
  52382. }
  52383. var textPosition = isLeft ? 'left' : 'right';
  52384. symbolPath.setTextConfig({
  52385. rotation: -rad,
  52386. position: textPosition,
  52387. origin: 'center'
  52388. });
  52389. var emphasisState = symbolPath.ensureState('emphasis');
  52390. extend(emphasisState.textConfig || (emphasisState.textConfig = {}), {
  52391. position: textPosition
  52392. });
  52393. } else {
  52394. symbolPath.setTextConfig({
  52395. rotation: labelRotate *= Math.PI / 180
  52396. });
  52397. }
  52398. }
  52399. function graphCircularLayout(ecModel) {
  52400. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52401. if (seriesModel.get('layout') === 'circular') {
  52402. circularLayout(seriesModel, 'symbolSize');
  52403. }
  52404. });
  52405. }
  52406. var scaleAndAdd$1 = scaleAndAdd; // function adjacentNode(n, e) {
  52407. // return e.n1 === n ? e.n2 : e.n1;
  52408. // }
  52409. function forceLayout(inNodes, inEdges, opts) {
  52410. var nodes = inNodes;
  52411. var edges = inEdges;
  52412. var rect = opts.rect;
  52413. var width = rect.width;
  52414. var height = rect.height;
  52415. var center = [rect.x + width / 2, rect.y + height / 2]; // let scale = opts.scale || 1;
  52416. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (let i = 0; i < edges.length; i++) {
  52417. // let e = edges[i];
  52418. // let n1 = e.n1;
  52419. // let n2 = e.n2;
  52420. // n1.edges = n1.edges || [];
  52421. // n2.edges = n2.edges || [];
  52422. // n1.edges.push(e);
  52423. // n2.edges.push(e);
  52424. // }
  52425. // Init position
  52426. for (var i = 0; i < nodes.length; i++) {
  52427. var n = nodes[i];
  52428. if (!n.p) {
  52429. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  52430. }
  52431. n.pp = clone$1(n.p);
  52432. n.edges = null;
  52433. } // Formula in 'Graph Drawing by Force-directed Placement'
  52434. // let k = scale * Math.sqrt(width * height / nodes.length);
  52435. // let k2 = k * k;
  52436. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  52437. var friction = initialFriction;
  52438. var beforeStepCallback;
  52439. var afterStepCallback;
  52440. return {
  52441. warmUp: function () {
  52442. friction = initialFriction * 0.8;
  52443. },
  52444. setFixed: function (idx) {
  52445. nodes[idx].fixed = true;
  52446. },
  52447. setUnfixed: function (idx) {
  52448. nodes[idx].fixed = false;
  52449. },
  52450. /**
  52451. * Before step hook
  52452. */
  52453. beforeStep: function (cb) {
  52454. beforeStepCallback = cb;
  52455. },
  52456. /**
  52457. * After step hook
  52458. */
  52459. afterStep: function (cb) {
  52460. afterStepCallback = cb;
  52461. },
  52462. /**
  52463. * Some formulas were originally copied from "d3.js"
  52464. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  52465. * with some modifications made for this project.
  52466. * See the license statement at the head of this file.
  52467. */
  52468. step: function (cb) {
  52469. beforeStepCallback && beforeStepCallback(nodes, edges);
  52470. var v12 = [];
  52471. var nLen = nodes.length;
  52472. for (var i = 0; i < edges.length; i++) {
  52473. var e = edges[i];
  52474. if (e.ignoreForceLayout) {
  52475. continue;
  52476. }
  52477. var n1 = e.n1;
  52478. var n2 = e.n2;
  52479. sub(v12, n2.p, n1.p);
  52480. var d = len(v12) - e.d;
  52481. var w = n2.w / (n1.w + n2.w);
  52482. if (isNaN(w)) {
  52483. w = 0;
  52484. }
  52485. normalize(v12, v12);
  52486. !n1.fixed && scaleAndAdd$1(n1.p, n1.p, v12, w * d * friction);
  52487. !n2.fixed && scaleAndAdd$1(n2.p, n2.p, v12, -(1 - w) * d * friction);
  52488. } // Gravity
  52489. for (var i = 0; i < nLen; i++) {
  52490. var n = nodes[i];
  52491. if (!n.fixed) {
  52492. sub(v12, center, n.p); // let d = vec2.len(v12);
  52493. // vec2.scale(v12, v12, 1 / d);
  52494. // let gravityFactor = gravity;
  52495. scaleAndAdd$1(n.p, n.p, v12, gravity * friction);
  52496. }
  52497. } // Repulsive
  52498. // PENDING
  52499. for (var i = 0; i < nLen; i++) {
  52500. var n1 = nodes[i];
  52501. for (var j = i + 1; j < nLen; j++) {
  52502. var n2 = nodes[j];
  52503. sub(v12, n2.p, n1.p);
  52504. var d = len(v12);
  52505. if (d === 0) {
  52506. // Random repulse
  52507. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  52508. d = 1;
  52509. }
  52510. var repFact = (n1.rep + n2.rep) / d / d;
  52511. !n1.fixed && scaleAndAdd$1(n1.pp, n1.pp, v12, repFact);
  52512. !n2.fixed && scaleAndAdd$1(n2.pp, n2.pp, v12, -repFact);
  52513. }
  52514. }
  52515. var v = [];
  52516. for (var i = 0; i < nLen; i++) {
  52517. var n = nodes[i];
  52518. if (!n.fixed) {
  52519. sub(v, n.p, n.pp);
  52520. scaleAndAdd$1(n.p, n.p, v, friction);
  52521. copy(n.pp, n.p);
  52522. }
  52523. }
  52524. friction = friction * 0.992;
  52525. var finished = friction < 0.01;
  52526. afterStepCallback && afterStepCallback(nodes, edges, finished);
  52527. cb && cb(finished);
  52528. }
  52529. };
  52530. }
  52531. function graphForceLayout(ecModel) {
  52532. ecModel.eachSeriesByType('graph', function (graphSeries) {
  52533. var coordSys = graphSeries.coordinateSystem;
  52534. if (coordSys && coordSys.type !== 'view') {
  52535. return;
  52536. }
  52537. if (graphSeries.get('layout') === 'force') {
  52538. var preservedPoints_1 = graphSeries.preservedPoints || {};
  52539. var graph_1 = graphSeries.getGraph();
  52540. var nodeData_1 = graph_1.data;
  52541. var edgeData = graph_1.edgeData;
  52542. var forceModel = graphSeries.getModel('force');
  52543. var initLayout = forceModel.get('initLayout');
  52544. if (graphSeries.preservedPoints) {
  52545. nodeData_1.each(function (idx) {
  52546. var id = nodeData_1.getId(idx);
  52547. nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [NaN, NaN]);
  52548. });
  52549. } else if (!initLayout || initLayout === 'none') {
  52550. simpleLayout(graphSeries);
  52551. } else if (initLayout === 'circular') {
  52552. circularLayout(graphSeries, 'value');
  52553. }
  52554. var nodeDataExtent_1 = nodeData_1.getDataExtent('value');
  52555. var edgeDataExtent_1 = edgeData.getDataExtent('value'); // let edgeDataExtent = edgeData.getDataExtent('value');
  52556. var repulsion = forceModel.get('repulsion');
  52557. var edgeLength = forceModel.get('edgeLength');
  52558. var repulsionArr_1 = isArray(repulsion) ? repulsion : [repulsion, repulsion];
  52559. var edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [edgeLength, edgeLength]; // Larger value has smaller length
  52560. edgeLengthArr_1 = [edgeLengthArr_1[1], edgeLengthArr_1[0]];
  52561. var nodes_1 = nodeData_1.mapArray('value', function (value, idx) {
  52562. var point = nodeData_1.getItemLayout(idx);
  52563. var rep = linearMap(value, nodeDataExtent_1, repulsionArr_1);
  52564. if (isNaN(rep)) {
  52565. rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2;
  52566. }
  52567. return {
  52568. w: rep,
  52569. rep: rep,
  52570. fixed: nodeData_1.getItemModel(idx).get('fixed'),
  52571. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  52572. };
  52573. });
  52574. var edges = edgeData.mapArray('value', function (value, idx) {
  52575. var edge = graph_1.getEdgeByIndex(idx);
  52576. var d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1);
  52577. if (isNaN(d)) {
  52578. d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2;
  52579. }
  52580. var edgeModel = edge.getModel();
  52581. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, graphSeries, idx, true), 0);
  52582. return {
  52583. n1: nodes_1[edge.node1.dataIndex],
  52584. n2: nodes_1[edge.node2.dataIndex],
  52585. d: d,
  52586. curveness: curveness,
  52587. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  52588. };
  52589. }); // let coordSys = graphSeries.coordinateSystem;
  52590. var rect = coordSys.getBoundingRect();
  52591. var forceInstance = forceLayout(nodes_1, edges, {
  52592. rect: rect,
  52593. gravity: forceModel.get('gravity'),
  52594. friction: forceModel.get('friction')
  52595. });
  52596. forceInstance.beforeStep(function (nodes, edges) {
  52597. for (var i = 0, l = nodes.length; i < l; i++) {
  52598. if (nodes[i].fixed) {
  52599. // Write back to layout instance
  52600. copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout());
  52601. }
  52602. }
  52603. });
  52604. forceInstance.afterStep(function (nodes, edges, stopped) {
  52605. for (var i = 0, l = nodes.length; i < l; i++) {
  52606. if (!nodes[i].fixed) {
  52607. graph_1.getNodeByIndex(i).setLayout(nodes[i].p);
  52608. }
  52609. preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p;
  52610. }
  52611. for (var i = 0, l = edges.length; i < l; i++) {
  52612. var e = edges[i];
  52613. var edge = graph_1.getEdgeByIndex(i);
  52614. var p1 = e.n1.p;
  52615. var p2 = e.n2.p;
  52616. var points = edge.getLayout();
  52617. points = points ? points.slice() : [];
  52618. points[0] = points[0] || [];
  52619. points[1] = points[1] || [];
  52620. copy(points[0], p1);
  52621. copy(points[1], p2);
  52622. if (+e.curveness) {
  52623. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  52624. }
  52625. edge.setLayout(points);
  52626. }
  52627. });
  52628. graphSeries.forceLayout = forceInstance;
  52629. graphSeries.preservedPoints = preservedPoints_1; // Step to get the layout
  52630. forceInstance.step();
  52631. } else {
  52632. // Remove prev injected forceLayout instance
  52633. graphSeries.forceLayout = null;
  52634. }
  52635. });
  52636. }
  52637. function getViewRect$2(seriesModel, api, aspect) {
  52638. var option = extend(seriesModel.getBoxLayoutParams(), {
  52639. aspect: aspect
  52640. });
  52641. return getLayoutRect(option, {
  52642. width: api.getWidth(),
  52643. height: api.getHeight()
  52644. });
  52645. }
  52646. function createViewCoordSys(ecModel, api) {
  52647. var viewList = [];
  52648. ecModel.eachSeriesByType('graph', function (seriesModel) {
  52649. var coordSysType = seriesModel.get('coordinateSystem');
  52650. if (!coordSysType || coordSysType === 'view') {
  52651. var data_1 = seriesModel.getData();
  52652. var positions = data_1.mapArray(function (idx) {
  52653. var itemModel = data_1.getItemModel(idx);
  52654. return [+itemModel.get('x'), +itemModel.get('y')];
  52655. });
  52656. var min = [];
  52657. var max = [];
  52658. fromPoints(positions, min, max); // If width or height is 0
  52659. if (max[0] - min[0] === 0) {
  52660. max[0] += 1;
  52661. min[0] -= 1;
  52662. }
  52663. if (max[1] - min[1] === 0) {
  52664. max[1] += 1;
  52665. min[1] -= 1;
  52666. }
  52667. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  52668. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  52669. if (isNaN(aspect)) {
  52670. min = [viewRect.x, viewRect.y];
  52671. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  52672. }
  52673. var bbWidth = max[0] - min[0];
  52674. var bbHeight = max[1] - min[1];
  52675. var viewWidth = viewRect.width;
  52676. var viewHeight = viewRect.height;
  52677. var viewCoordSys = seriesModel.coordinateSystem = new View();
  52678. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  52679. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  52680. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  52681. viewCoordSys.setCenter(seriesModel.get('center'), api);
  52682. viewCoordSys.setZoom(seriesModel.get('zoom'));
  52683. viewList.push(viewCoordSys);
  52684. }
  52685. });
  52686. return viewList;
  52687. }
  52688. var straightLineProto = Line.prototype;
  52689. var bezierCurveProto = BezierCurve.prototype;
  52690. var StraightLineShape =
  52691. /** @class */
  52692. function () {
  52693. function StraightLineShape() {
  52694. // Start point
  52695. this.x1 = 0;
  52696. this.y1 = 0; // End point
  52697. this.x2 = 0;
  52698. this.y2 = 0;
  52699. this.percent = 1;
  52700. }
  52701. return StraightLineShape;
  52702. }();
  52703. var CurveShape =
  52704. /** @class */
  52705. function (_super) {
  52706. __extends(CurveShape, _super);
  52707. function CurveShape() {
  52708. return _super !== null && _super.apply(this, arguments) || this;
  52709. }
  52710. return CurveShape;
  52711. }(StraightLineShape);
  52712. function isStraightLine(shape) {
  52713. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  52714. }
  52715. var ECLinePath =
  52716. /** @class */
  52717. function (_super) {
  52718. __extends(ECLinePath, _super);
  52719. function ECLinePath(opts) {
  52720. var _this = _super.call(this, opts) || this;
  52721. _this.type = 'ec-line';
  52722. return _this;
  52723. }
  52724. ECLinePath.prototype.getDefaultStyle = function () {
  52725. return {
  52726. stroke: '#000',
  52727. fill: null
  52728. };
  52729. };
  52730. ECLinePath.prototype.getDefaultShape = function () {
  52731. return new StraightLineShape();
  52732. };
  52733. ECLinePath.prototype.buildPath = function (ctx, shape) {
  52734. if (isStraightLine(shape)) {
  52735. straightLineProto.buildPath.call(this, ctx, shape);
  52736. } else {
  52737. bezierCurveProto.buildPath.call(this, ctx, shape);
  52738. }
  52739. };
  52740. ECLinePath.prototype.pointAt = function (t) {
  52741. if (isStraightLine(this.shape)) {
  52742. return straightLineProto.pointAt.call(this, t);
  52743. } else {
  52744. return bezierCurveProto.pointAt.call(this, t);
  52745. }
  52746. };
  52747. ECLinePath.prototype.tangentAt = function (t) {
  52748. var shape = this.shape;
  52749. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  52750. return normalize(p, p);
  52751. };
  52752. return ECLinePath;
  52753. }(Path);
  52754. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  52755. function makeSymbolTypeKey(symbolCategory) {
  52756. return '_' + symbolCategory + 'Type';
  52757. }
  52758. function makeSymbolTypeValue(name, lineData, idx) {
  52759. var symbolType = lineData.getItemVisual(idx, name);
  52760. if (!symbolType || symbolType === 'none') {
  52761. return symbolType;
  52762. }
  52763. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52764. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52765. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52766. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52767. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52768. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52769. return symbolType + symbolSizeArr + symbolOffsetArr + (symbolRotate || '') + (symbolKeepAspect || '');
  52770. }
  52771. /**
  52772. * @inner
  52773. */
  52774. function createSymbol$1(name, lineData, idx) {
  52775. var symbolType = lineData.getItemVisual(idx, name);
  52776. if (!symbolType || symbolType === 'none') {
  52777. return;
  52778. }
  52779. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  52780. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  52781. var symbolOffset = lineData.getItemVisual(idx, name + 'Offset');
  52782. var symbolKeepAspect = lineData.getItemVisual(idx, name + 'KeepAspect');
  52783. var symbolSizeArr = normalizeSymbolSize(symbolSize);
  52784. var symbolOffsetArr = normalizeSymbolOffset(symbolOffset || 0, symbolSizeArr);
  52785. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2 + symbolOffsetArr[0], -symbolSizeArr[1] / 2 + symbolOffsetArr[1], symbolSizeArr[0], symbolSizeArr[1], null, symbolKeepAspect);
  52786. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  52787. symbolPath.name = name;
  52788. return symbolPath;
  52789. }
  52790. function createLine(points) {
  52791. var line = new ECLinePath({
  52792. name: 'line',
  52793. subPixelOptimize: true
  52794. });
  52795. setLinePoints(line.shape, points);
  52796. return line;
  52797. }
  52798. function setLinePoints(targetShape, points) {
  52799. targetShape.x1 = points[0][0];
  52800. targetShape.y1 = points[0][1];
  52801. targetShape.x2 = points[1][0];
  52802. targetShape.y2 = points[1][1];
  52803. targetShape.percent = 1;
  52804. var cp1 = points[2];
  52805. if (cp1) {
  52806. targetShape.cpx1 = cp1[0];
  52807. targetShape.cpy1 = cp1[1];
  52808. } else {
  52809. targetShape.cpx1 = NaN;
  52810. targetShape.cpy1 = NaN;
  52811. }
  52812. }
  52813. var Line$1 =
  52814. /** @class */
  52815. function (_super) {
  52816. __extends(Line, _super);
  52817. function Line(lineData, idx, seriesScope) {
  52818. var _this = _super.call(this) || this;
  52819. _this._createLine(lineData, idx, seriesScope);
  52820. return _this;
  52821. }
  52822. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  52823. var seriesModel = lineData.hostModel;
  52824. var linePoints = lineData.getItemLayout(idx);
  52825. var line = createLine(linePoints);
  52826. line.shape.percent = 0;
  52827. initProps(line, {
  52828. shape: {
  52829. percent: 1
  52830. }
  52831. }, seriesModel, idx);
  52832. this.add(line);
  52833. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52834. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  52835. // it will be updated after line#update.
  52836. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  52837. this.add(symbol);
  52838. this[makeSymbolTypeKey(symbolCategory)] = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52839. }, this);
  52840. this._updateCommonStl(lineData, idx, seriesScope);
  52841. }; // TODO More strict on the List type in parameters?
  52842. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  52843. var seriesModel = lineData.hostModel;
  52844. var line = this.childOfName('line');
  52845. var linePoints = lineData.getItemLayout(idx);
  52846. var target = {
  52847. shape: {}
  52848. };
  52849. setLinePoints(target.shape, linePoints);
  52850. updateProps(line, target, seriesModel, idx);
  52851. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52852. var symbolType = makeSymbolTypeValue(symbolCategory, lineData, idx);
  52853. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  52854. if (this[key] !== symbolType) {
  52855. this.remove(this.childOfName(symbolCategory));
  52856. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  52857. this.add(symbol);
  52858. }
  52859. this[key] = symbolType;
  52860. }, this);
  52861. this._updateCommonStl(lineData, idx, seriesScope);
  52862. };
  52863. Line.prototype.getLinePath = function () {
  52864. return this.childAt(0);
  52865. };
  52866. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  52867. var seriesModel = lineData.hostModel;
  52868. var line = this.childOfName('line');
  52869. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  52870. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  52871. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  52872. var labelStatesModels = seriesScope && seriesScope.labelStatesModels;
  52873. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  52874. var focus = seriesScope && seriesScope.focus;
  52875. var blurScope = seriesScope && seriesScope.blurScope; // Optimization for large dataset
  52876. if (!seriesScope || lineData.hasItemOption) {
  52877. var itemModel = lineData.getItemModel(idx);
  52878. var emphasisModel = itemModel.getModel('emphasis');
  52879. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  52880. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  52881. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  52882. emphasisDisabled = emphasisModel.get('disabled');
  52883. focus = emphasisModel.get('focus');
  52884. blurScope = emphasisModel.get('blurScope');
  52885. labelStatesModels = getLabelStatesModels(itemModel);
  52886. }
  52887. var lineStyle = lineData.getItemVisual(idx, 'style');
  52888. var visualColor = lineStyle.stroke;
  52889. line.useStyle(lineStyle);
  52890. line.style.fill = null;
  52891. line.style.strokeNoScale = true;
  52892. line.ensureState('emphasis').style = emphasisLineStyle;
  52893. line.ensureState('blur').style = blurLineStyle;
  52894. line.ensureState('select').style = selectLineStyle; // Update symbol
  52895. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  52896. var symbol = this.childOfName(symbolCategory);
  52897. if (symbol) {
  52898. // Share opacity and color with line.
  52899. symbol.setColor(visualColor);
  52900. symbol.style.opacity = lineStyle.opacity;
  52901. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  52902. var stateName = SPECIAL_STATES[i];
  52903. var lineState = line.getState(stateName);
  52904. if (lineState) {
  52905. var lineStateStyle = lineState.style || {};
  52906. var state = symbol.ensureState(stateName);
  52907. var stateStyle = state.style || (state.style = {});
  52908. if (lineStateStyle.stroke != null) {
  52909. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  52910. }
  52911. if (lineStateStyle.opacity != null) {
  52912. stateStyle.opacity = lineStateStyle.opacity;
  52913. }
  52914. }
  52915. }
  52916. symbol.markRedraw();
  52917. }
  52918. }, this);
  52919. var rawVal = seriesModel.getRawValue(idx);
  52920. setLabelStyle(this, labelStatesModels, {
  52921. labelDataIndex: idx,
  52922. labelFetcher: {
  52923. getFormattedLabel: function (dataIndex, stateName) {
  52924. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  52925. }
  52926. },
  52927. inheritColor: visualColor || '#000',
  52928. defaultOpacity: lineStyle.opacity,
  52929. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  52930. });
  52931. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  52932. // values have to be set on `normalStyle`.
  52933. if (label) {
  52934. var labelNormalModel = labelStatesModels.normal;
  52935. label.__align = label.style.align;
  52936. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  52937. label.__position = labelNormalModel.get('position') || 'middle';
  52938. var distance = labelNormalModel.get('distance');
  52939. if (!isArray(distance)) {
  52940. distance = [distance, distance];
  52941. }
  52942. label.__labelDistance = distance;
  52943. }
  52944. this.setTextConfig({
  52945. position: null,
  52946. local: true,
  52947. inside: false // Can't be inside for stroke element.
  52948. });
  52949. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  52950. };
  52951. Line.prototype.highlight = function () {
  52952. enterEmphasis(this);
  52953. };
  52954. Line.prototype.downplay = function () {
  52955. leaveEmphasis(this);
  52956. };
  52957. Line.prototype.updateLayout = function (lineData, idx) {
  52958. this.setLinePoints(lineData.getItemLayout(idx));
  52959. };
  52960. Line.prototype.setLinePoints = function (points) {
  52961. var linePath = this.childOfName('line');
  52962. setLinePoints(linePath.shape, points);
  52963. linePath.dirty();
  52964. };
  52965. Line.prototype.beforeUpdate = function () {
  52966. var lineGroup = this;
  52967. var symbolFrom = lineGroup.childOfName('fromSymbol');
  52968. var symbolTo = lineGroup.childOfName('toSymbol');
  52969. var label = lineGroup.getTextContent(); // Quick reject
  52970. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  52971. return;
  52972. }
  52973. var invScale = 1;
  52974. var parentNode = this.parent;
  52975. while (parentNode) {
  52976. if (parentNode.scaleX) {
  52977. invScale /= parentNode.scaleX;
  52978. }
  52979. parentNode = parentNode.parent;
  52980. }
  52981. var line = lineGroup.childOfName('line'); // If line not changed
  52982. // FIXME Parent scale changed
  52983. if (!this.__dirty && !line.__dirty) {
  52984. return;
  52985. }
  52986. var percent = line.shape.percent;
  52987. var fromPos = line.pointAt(0);
  52988. var toPos = line.pointAt(percent);
  52989. var d = sub([], toPos, fromPos);
  52990. normalize(d, d);
  52991. function setSymbolRotation(symbol, percent) {
  52992. // Fix #12388
  52993. // when symbol is set to be 'arrow' in markLine,
  52994. // symbolRotate value will be ignored, and compulsively use tangent angle.
  52995. // rotate by default if symbol rotation is not specified
  52996. var specifiedRotation = symbol.__specifiedRotation;
  52997. if (specifiedRotation == null) {
  52998. var tangent = line.tangentAt(percent);
  52999. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  53000. } else {
  53001. symbol.attr('rotation', specifiedRotation);
  53002. }
  53003. }
  53004. if (symbolFrom) {
  53005. symbolFrom.setPosition(fromPos);
  53006. setSymbolRotation(symbolFrom, 0);
  53007. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  53008. symbolFrom.markRedraw();
  53009. }
  53010. if (symbolTo) {
  53011. symbolTo.setPosition(toPos);
  53012. setSymbolRotation(symbolTo, 1);
  53013. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  53014. symbolTo.markRedraw();
  53015. }
  53016. if (label && !label.ignore) {
  53017. label.x = label.y = 0;
  53018. label.originX = label.originY = 0;
  53019. var textAlign = void 0;
  53020. var textVerticalAlign = void 0;
  53021. var distance = label.__labelDistance;
  53022. var distanceX = distance[0] * invScale;
  53023. var distanceY = distance[1] * invScale;
  53024. var halfPercent = percent / 2;
  53025. var tangent = line.tangentAt(halfPercent);
  53026. var n = [tangent[1], -tangent[0]];
  53027. var cp = line.pointAt(halfPercent);
  53028. if (n[1] > 0) {
  53029. n[0] = -n[0];
  53030. n[1] = -n[1];
  53031. }
  53032. var dir = tangent[0] < 0 ? -1 : 1;
  53033. if (label.__position !== 'start' && label.__position !== 'end') {
  53034. var rotation = -Math.atan2(tangent[1], tangent[0]);
  53035. if (toPos[0] < fromPos[0]) {
  53036. rotation = Math.PI + rotation;
  53037. }
  53038. label.rotation = rotation;
  53039. }
  53040. var dy = void 0;
  53041. switch (label.__position) {
  53042. case 'insideStartTop':
  53043. case 'insideMiddleTop':
  53044. case 'insideEndTop':
  53045. case 'middle':
  53046. dy = -distanceY;
  53047. textVerticalAlign = 'bottom';
  53048. break;
  53049. case 'insideStartBottom':
  53050. case 'insideMiddleBottom':
  53051. case 'insideEndBottom':
  53052. dy = distanceY;
  53053. textVerticalAlign = 'top';
  53054. break;
  53055. default:
  53056. dy = 0;
  53057. textVerticalAlign = 'middle';
  53058. }
  53059. switch (label.__position) {
  53060. case 'end':
  53061. label.x = d[0] * distanceX + toPos[0];
  53062. label.y = d[1] * distanceY + toPos[1];
  53063. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  53064. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  53065. break;
  53066. case 'start':
  53067. label.x = -d[0] * distanceX + fromPos[0];
  53068. label.y = -d[1] * distanceY + fromPos[1];
  53069. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  53070. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  53071. break;
  53072. case 'insideStartTop':
  53073. case 'insideStart':
  53074. case 'insideStartBottom':
  53075. label.x = distanceX * dir + fromPos[0];
  53076. label.y = fromPos[1] + dy;
  53077. textAlign = tangent[0] < 0 ? 'right' : 'left';
  53078. label.originX = -distanceX * dir;
  53079. label.originY = -dy;
  53080. break;
  53081. case 'insideMiddleTop':
  53082. case 'insideMiddle':
  53083. case 'insideMiddleBottom':
  53084. case 'middle':
  53085. label.x = cp[0];
  53086. label.y = cp[1] + dy;
  53087. textAlign = 'center';
  53088. label.originY = -dy;
  53089. break;
  53090. case 'insideEndTop':
  53091. case 'insideEnd':
  53092. case 'insideEndBottom':
  53093. label.x = -distanceX * dir + toPos[0];
  53094. label.y = toPos[1] + dy;
  53095. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  53096. label.originX = distanceX * dir;
  53097. label.originY = -dy;
  53098. break;
  53099. }
  53100. label.scaleX = label.scaleY = invScale;
  53101. label.setStyle({
  53102. // Use the user specified text align and baseline first
  53103. verticalAlign: label.__verticalAlign || textVerticalAlign,
  53104. align: label.__align || textAlign
  53105. });
  53106. }
  53107. };
  53108. return Line;
  53109. }(Group);
  53110. var LineDraw =
  53111. /** @class */
  53112. function () {
  53113. function LineDraw(LineCtor) {
  53114. this.group = new Group();
  53115. this._LineCtor = LineCtor || Line$1;
  53116. }
  53117. LineDraw.prototype.updateData = function (lineData) {
  53118. var _this = this; // Remove progressive els.
  53119. this._progressiveEls = null;
  53120. var lineDraw = this;
  53121. var group = lineDraw.group;
  53122. var oldLineData = lineDraw._lineData;
  53123. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  53124. // stream mode to normal mode, where previous elements should be removed.
  53125. if (!oldLineData) {
  53126. group.removeAll();
  53127. }
  53128. var seriesScope = makeSeriesScope$1(lineData);
  53129. lineData.diff(oldLineData).add(function (idx) {
  53130. _this._doAdd(lineData, idx, seriesScope);
  53131. }).update(function (newIdx, oldIdx) {
  53132. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  53133. }).remove(function (idx) {
  53134. group.remove(oldLineData.getItemGraphicEl(idx));
  53135. }).execute();
  53136. };
  53137. LineDraw.prototype.updateLayout = function () {
  53138. var lineData = this._lineData; // Do not support update layout in incremental mode.
  53139. if (!lineData) {
  53140. return;
  53141. }
  53142. lineData.eachItemGraphicEl(function (el, idx) {
  53143. el.updateLayout(lineData, idx);
  53144. }, this);
  53145. };
  53146. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  53147. this._seriesScope = makeSeriesScope$1(lineData);
  53148. this._lineData = null;
  53149. this.group.removeAll();
  53150. };
  53151. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  53152. this._progressiveEls = [];
  53153. function updateIncrementalAndHover(el) {
  53154. if (!el.isGroup && !isEffectObject(el)) {
  53155. el.incremental = true;
  53156. el.ensureState('emphasis').hoverLayer = true;
  53157. }
  53158. }
  53159. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  53160. var itemLayout = lineData.getItemLayout(idx);
  53161. if (lineNeedsDraw(itemLayout)) {
  53162. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  53163. el.traverse(updateIncrementalAndHover);
  53164. this.group.add(el);
  53165. lineData.setItemGraphicEl(idx, el);
  53166. this._progressiveEls.push(el);
  53167. }
  53168. }
  53169. };
  53170. LineDraw.prototype.remove = function () {
  53171. this.group.removeAll();
  53172. };
  53173. LineDraw.prototype.eachRendered = function (cb) {
  53174. traverseElements(this._progressiveEls || this.group, cb);
  53175. };
  53176. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  53177. var itemLayout = lineData.getItemLayout(idx);
  53178. if (!lineNeedsDraw(itemLayout)) {
  53179. return;
  53180. }
  53181. var el = new this._LineCtor(lineData, idx, seriesScope);
  53182. lineData.setItemGraphicEl(idx, el);
  53183. this.group.add(el);
  53184. };
  53185. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  53186. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  53187. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  53188. this.group.remove(itemEl);
  53189. return;
  53190. }
  53191. if (!itemEl) {
  53192. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  53193. } else {
  53194. itemEl.updateData(newLineData, newIdx, seriesScope);
  53195. }
  53196. newLineData.setItemGraphicEl(newIdx, itemEl);
  53197. this.group.add(itemEl);
  53198. };
  53199. return LineDraw;
  53200. }();
  53201. function isEffectObject(el) {
  53202. return el.animators && el.animators.length > 0;
  53203. }
  53204. function makeSeriesScope$1(lineData) {
  53205. var hostModel = lineData.hostModel;
  53206. var emphasisModel = hostModel.getModel('emphasis');
  53207. return {
  53208. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  53209. emphasisLineStyle: emphasisModel.getModel(['lineStyle']).getLineStyle(),
  53210. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  53211. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  53212. emphasisDisabled: emphasisModel.get('disabled'),
  53213. blurScope: emphasisModel.get('blurScope'),
  53214. focus: emphasisModel.get('focus'),
  53215. labelStatesModels: getLabelStatesModels(hostModel)
  53216. };
  53217. }
  53218. function isPointNaN(pt) {
  53219. return isNaN(pt[0]) || isNaN(pt[1]);
  53220. }
  53221. function lineNeedsDraw(pts) {
  53222. return pts && !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  53223. }
  53224. var v1 = [];
  53225. var v2 = [];
  53226. var v3 = [];
  53227. var quadraticAt$1 = quadraticAt;
  53228. var v2DistSquare = distSquare;
  53229. var mathAbs$2 = Math.abs;
  53230. function intersectCurveCircle(curvePoints, center, radius) {
  53231. var p0 = curvePoints[0];
  53232. var p1 = curvePoints[1];
  53233. var p2 = curvePoints[2];
  53234. var d = Infinity;
  53235. var t;
  53236. var radiusSquare = radius * radius;
  53237. var interval = 0.1;
  53238. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  53239. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  53240. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  53241. var diff = mathAbs$2(v2DistSquare(v1, center) - radiusSquare);
  53242. if (diff < d) {
  53243. d = diff;
  53244. t = _t;
  53245. }
  53246. } // Assume the segment is monotone,Find root through Bisection method
  53247. // At most 32 iteration
  53248. for (var i = 0; i < 32; i++) {
  53249. // let prev = t - interval;
  53250. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  53251. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  53252. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  53253. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  53254. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  53255. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  53256. var diff = v2DistSquare(v2, center) - radiusSquare;
  53257. if (mathAbs$2(diff) < 1e-2) {
  53258. break;
  53259. } // let prevDiff = v2DistSquare(v1, center) - radiusSquare;
  53260. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  53261. interval /= 2;
  53262. if (diff < 0) {
  53263. if (nextDiff >= 0) {
  53264. t = t + interval;
  53265. } else {
  53266. t = t - interval;
  53267. }
  53268. } else {
  53269. if (nextDiff >= 0) {
  53270. t = t - interval;
  53271. } else {
  53272. t = t + interval;
  53273. }
  53274. }
  53275. }
  53276. return t;
  53277. } // Adjust edge to avoid
  53278. function adjustEdge(graph, scale) {
  53279. var tmp0 = [];
  53280. var quadraticSubdivide$1 = quadraticSubdivide;
  53281. var pts = [[], [], []];
  53282. var pts2 = [[], []];
  53283. var v = [];
  53284. scale /= 2;
  53285. graph.eachEdge(function (edge, idx) {
  53286. var linePoints = edge.getLayout();
  53287. var fromSymbol = edge.getVisual('fromSymbol');
  53288. var toSymbol = edge.getVisual('toSymbol');
  53289. if (!linePoints.__original) {
  53290. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  53291. if (linePoints[2]) {
  53292. linePoints.__original.push(clone$1(linePoints[2]));
  53293. }
  53294. }
  53295. var originalPoints = linePoints.__original; // Quadratic curve
  53296. if (linePoints[2] != null) {
  53297. copy(pts[0], originalPoints[0]);
  53298. copy(pts[1], originalPoints[2]);
  53299. copy(pts[2], originalPoints[1]);
  53300. if (fromSymbol && fromSymbol !== 'none') {
  53301. var symbolSize = getSymbolSize(edge.node1);
  53302. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); // Subdivide and get the second
  53303. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53304. pts[0][0] = tmp0[3];
  53305. pts[1][0] = tmp0[4];
  53306. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53307. pts[0][1] = tmp0[3];
  53308. pts[1][1] = tmp0[4];
  53309. }
  53310. if (toSymbol && toSymbol !== 'none') {
  53311. var symbolSize = getSymbolSize(edge.node2);
  53312. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); // Subdivide and get the first
  53313. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  53314. pts[1][0] = tmp0[1];
  53315. pts[2][0] = tmp0[2];
  53316. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  53317. pts[1][1] = tmp0[1];
  53318. pts[2][1] = tmp0[2];
  53319. } // Copy back to layout
  53320. copy(linePoints[0], pts[0]);
  53321. copy(linePoints[1], pts[2]);
  53322. copy(linePoints[2], pts[1]);
  53323. } // Line
  53324. else {
  53325. copy(pts2[0], originalPoints[0]);
  53326. copy(pts2[1], originalPoints[1]);
  53327. sub(v, pts2[1], pts2[0]);
  53328. normalize(v, v);
  53329. if (fromSymbol && fromSymbol !== 'none') {
  53330. var symbolSize = getSymbolSize(edge.node1);
  53331. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale);
  53332. }
  53333. if (toSymbol && toSymbol !== 'none') {
  53334. var symbolSize = getSymbolSize(edge.node2);
  53335. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale);
  53336. }
  53337. copy(linePoints[0], pts2[0]);
  53338. copy(linePoints[1], pts2[1]);
  53339. }
  53340. });
  53341. }
  53342. function isViewCoordSys(coordSys) {
  53343. return coordSys.type === 'view';
  53344. }
  53345. var GraphView =
  53346. /** @class */
  53347. function (_super) {
  53348. __extends(GraphView, _super);
  53349. function GraphView() {
  53350. var _this = _super !== null && _super.apply(this, arguments) || this;
  53351. _this.type = GraphView.type;
  53352. return _this;
  53353. }
  53354. GraphView.prototype.init = function (ecModel, api) {
  53355. var symbolDraw = new SymbolDraw();
  53356. var lineDraw = new LineDraw();
  53357. var group = this.group;
  53358. this._controller = new RoamController(api.getZr());
  53359. this._controllerHost = {
  53360. target: group
  53361. };
  53362. group.add(symbolDraw.group);
  53363. group.add(lineDraw.group);
  53364. this._symbolDraw = symbolDraw;
  53365. this._lineDraw = lineDraw;
  53366. this._firstRender = true;
  53367. };
  53368. GraphView.prototype.render = function (seriesModel, ecModel, api) {
  53369. var _this = this;
  53370. var coordSys = seriesModel.coordinateSystem;
  53371. this._model = seriesModel;
  53372. var symbolDraw = this._symbolDraw;
  53373. var lineDraw = this._lineDraw;
  53374. var group = this.group;
  53375. if (isViewCoordSys(coordSys)) {
  53376. var groupNewProp = {
  53377. x: coordSys.x,
  53378. y: coordSys.y,
  53379. scaleX: coordSys.scaleX,
  53380. scaleY: coordSys.scaleY
  53381. };
  53382. if (this._firstRender) {
  53383. group.attr(groupNewProp);
  53384. } else {
  53385. updateProps(group, groupNewProp, seriesModel);
  53386. }
  53387. } // Fix edge contact point with node
  53388. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53389. var data = seriesModel.getData();
  53390. symbolDraw.updateData(data);
  53391. var edgeData = seriesModel.getEdgeData(); // TODO: TYPE
  53392. lineDraw.updateData(edgeData);
  53393. this._updateNodeAndLinkScale();
  53394. this._updateController(seriesModel, ecModel, api);
  53395. clearTimeout(this._layoutTimeout);
  53396. var forceLayout = seriesModel.forceLayout;
  53397. var layoutAnimation = seriesModel.get(['force', 'layoutAnimation']);
  53398. if (forceLayout) {
  53399. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53400. }
  53401. var layout = seriesModel.get('layout');
  53402. data.graph.eachNode(function (node) {
  53403. var idx = node.dataIndex;
  53404. var el = node.getGraphicEl();
  53405. var itemModel = node.getModel();
  53406. if (!el) {
  53407. return;
  53408. } // Update draggable
  53409. el.off('drag').off('dragend');
  53410. var draggable = itemModel.get('draggable');
  53411. if (draggable) {
  53412. el.on('drag', function (e) {
  53413. switch (layout) {
  53414. case 'force':
  53415. forceLayout.warmUp();
  53416. !_this._layouting && _this._startForceLayoutIteration(forceLayout, layoutAnimation);
  53417. forceLayout.setFixed(idx); // Write position back to layout
  53418. data.setItemLayout(idx, [el.x, el.y]);
  53419. break;
  53420. case 'circular':
  53421. data.setItemLayout(idx, [el.x, el.y]); // mark node fixed
  53422. node.setLayout({
  53423. fixed: true
  53424. }, true); // recalculate circular layout
  53425. circularLayout(seriesModel, 'symbolSize', node, [e.offsetX, e.offsetY]);
  53426. _this.updateLayout(seriesModel);
  53427. break;
  53428. case 'none':
  53429. default:
  53430. data.setItemLayout(idx, [el.x, el.y]); // update edge
  53431. simpleLayoutEdge(seriesModel.getGraph(), seriesModel);
  53432. _this.updateLayout(seriesModel);
  53433. break;
  53434. }
  53435. }).on('dragend', function () {
  53436. if (forceLayout) {
  53437. forceLayout.setUnfixed(idx);
  53438. }
  53439. });
  53440. }
  53441. el.setDraggable(draggable, !!itemModel.get('cursor'));
  53442. var focus = itemModel.get(['emphasis', 'focus']);
  53443. if (focus === 'adjacency') {
  53444. getECData(el).focus = node.getAdjacentDataIndices();
  53445. }
  53446. });
  53447. data.graph.eachEdge(function (edge) {
  53448. var el = edge.getGraphicEl();
  53449. var focus = edge.getModel().get(['emphasis', 'focus']);
  53450. if (!el) {
  53451. return;
  53452. }
  53453. if (focus === 'adjacency') {
  53454. getECData(el).focus = {
  53455. edge: [edge.dataIndex],
  53456. node: [edge.node1.dataIndex, edge.node2.dataIndex]
  53457. };
  53458. }
  53459. });
  53460. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']);
  53461. var cx = data.getLayout('cx');
  53462. var cy = data.getLayout('cy');
  53463. data.graph.eachNode(function (node) {
  53464. rotateNodeLabel(node, circularRotateLabel, cx, cy);
  53465. });
  53466. this._firstRender = false;
  53467. };
  53468. GraphView.prototype.dispose = function () {
  53469. this._controller && this._controller.dispose();
  53470. this._controllerHost = null;
  53471. };
  53472. GraphView.prototype._startForceLayoutIteration = function (forceLayout, layoutAnimation) {
  53473. var self = this;
  53474. (function step() {
  53475. forceLayout.step(function (stopped) {
  53476. self.updateLayout(self._model);
  53477. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  53478. });
  53479. })();
  53480. };
  53481. GraphView.prototype._updateController = function (seriesModel, ecModel, api) {
  53482. var _this = this;
  53483. var controller = this._controller;
  53484. var controllerHost = this._controllerHost;
  53485. var group = this.group;
  53486. controller.setPointerChecker(function (e, x, y) {
  53487. var rect = group.getBoundingRect();
  53488. rect.applyTransform(group.transform);
  53489. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  53490. });
  53491. if (!isViewCoordSys(seriesModel.coordinateSystem)) {
  53492. controller.disable();
  53493. return;
  53494. }
  53495. controller.enable(seriesModel.get('roam'));
  53496. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  53497. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  53498. controller.off('pan').off('zoom').on('pan', function (e) {
  53499. updateViewOnPan(controllerHost, e.dx, e.dy);
  53500. api.dispatchAction({
  53501. seriesId: seriesModel.id,
  53502. type: 'graphRoam',
  53503. dx: e.dx,
  53504. dy: e.dy
  53505. });
  53506. }).on('zoom', function (e) {
  53507. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  53508. api.dispatchAction({
  53509. seriesId: seriesModel.id,
  53510. type: 'graphRoam',
  53511. zoom: e.scale,
  53512. originX: e.originX,
  53513. originY: e.originY
  53514. });
  53515. _this._updateNodeAndLinkScale();
  53516. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53517. _this._lineDraw.updateLayout(); // Only update label layout on zoom
  53518. api.updateLabelLayout();
  53519. });
  53520. };
  53521. GraphView.prototype._updateNodeAndLinkScale = function () {
  53522. var seriesModel = this._model;
  53523. var data = seriesModel.getData();
  53524. var nodeScale = getNodeGlobalScale(seriesModel);
  53525. data.eachItemGraphicEl(function (el, idx) {
  53526. el && el.setSymbolScale(nodeScale);
  53527. });
  53528. };
  53529. GraphView.prototype.updateLayout = function (seriesModel) {
  53530. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  53531. this._symbolDraw.updateLayout();
  53532. this._lineDraw.updateLayout();
  53533. };
  53534. GraphView.prototype.remove = function (ecModel, api) {
  53535. this._symbolDraw && this._symbolDraw.remove();
  53536. this._lineDraw && this._lineDraw.remove();
  53537. };
  53538. GraphView.type = 'graph';
  53539. return GraphView;
  53540. }(ChartView);
  53541. function generateNodeKey(id) {
  53542. return '_EC_' + id;
  53543. }
  53544. var Graph =
  53545. /** @class */
  53546. function () {
  53547. function Graph(directed) {
  53548. this.type = 'graph';
  53549. this.nodes = [];
  53550. this.edges = [];
  53551. this._nodesMap = {};
  53552. /**
  53553. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  53554. * @private
  53555. */
  53556. this._edgesMap = {};
  53557. this._directed = directed || false;
  53558. }
  53559. /**
  53560. * If is directed graph
  53561. */
  53562. Graph.prototype.isDirected = function () {
  53563. return this._directed;
  53564. };
  53565. /**
  53566. * Add a new node
  53567. */
  53568. Graph.prototype.addNode = function (id, dataIndex) {
  53569. id = id == null ? '' + dataIndex : '' + id;
  53570. var nodesMap = this._nodesMap;
  53571. if (nodesMap[generateNodeKey(id)]) {
  53572. if ("development" !== 'production') {
  53573. console.error('Graph nodes have duplicate name or id');
  53574. }
  53575. return;
  53576. }
  53577. var node = new GraphNode(id, dataIndex);
  53578. node.hostGraph = this;
  53579. this.nodes.push(node);
  53580. nodesMap[generateNodeKey(id)] = node;
  53581. return node;
  53582. };
  53583. /**
  53584. * Get node by data index
  53585. */
  53586. Graph.prototype.getNodeByIndex = function (dataIndex) {
  53587. var rawIdx = this.data.getRawIndex(dataIndex);
  53588. return this.nodes[rawIdx];
  53589. };
  53590. /**
  53591. * Get node by id
  53592. */
  53593. Graph.prototype.getNodeById = function (id) {
  53594. return this._nodesMap[generateNodeKey(id)];
  53595. };
  53596. /**
  53597. * Add a new edge
  53598. */
  53599. Graph.prototype.addEdge = function (n1, n2, dataIndex) {
  53600. var nodesMap = this._nodesMap;
  53601. var edgesMap = this._edgesMap; // PENDING
  53602. if (isNumber(n1)) {
  53603. n1 = this.nodes[n1];
  53604. }
  53605. if (isNumber(n2)) {
  53606. n2 = this.nodes[n2];
  53607. }
  53608. if (!(n1 instanceof GraphNode)) {
  53609. n1 = nodesMap[generateNodeKey(n1)];
  53610. }
  53611. if (!(n2 instanceof GraphNode)) {
  53612. n2 = nodesMap[generateNodeKey(n2)];
  53613. }
  53614. if (!n1 || !n2) {
  53615. return;
  53616. }
  53617. var key = n1.id + '-' + n2.id;
  53618. var edge = new GraphEdge(n1, n2, dataIndex);
  53619. edge.hostGraph = this;
  53620. if (this._directed) {
  53621. n1.outEdges.push(edge);
  53622. n2.inEdges.push(edge);
  53623. }
  53624. n1.edges.push(edge);
  53625. if (n1 !== n2) {
  53626. n2.edges.push(edge);
  53627. }
  53628. this.edges.push(edge);
  53629. edgesMap[key] = edge;
  53630. return edge;
  53631. };
  53632. /**
  53633. * Get edge by data index
  53634. */
  53635. Graph.prototype.getEdgeByIndex = function (dataIndex) {
  53636. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  53637. return this.edges[rawIdx];
  53638. };
  53639. /**
  53640. * Get edge by two linked nodes
  53641. */
  53642. Graph.prototype.getEdge = function (n1, n2) {
  53643. if (n1 instanceof GraphNode) {
  53644. n1 = n1.id;
  53645. }
  53646. if (n2 instanceof GraphNode) {
  53647. n2 = n2.id;
  53648. }
  53649. var edgesMap = this._edgesMap;
  53650. if (this._directed) {
  53651. return edgesMap[n1 + '-' + n2];
  53652. } else {
  53653. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  53654. }
  53655. };
  53656. /**
  53657. * Iterate all nodes
  53658. */
  53659. Graph.prototype.eachNode = function (cb, context) {
  53660. var nodes = this.nodes;
  53661. var len = nodes.length;
  53662. for (var i = 0; i < len; i++) {
  53663. if (nodes[i].dataIndex >= 0) {
  53664. cb.call(context, nodes[i], i);
  53665. }
  53666. }
  53667. };
  53668. /**
  53669. * Iterate all edges
  53670. */
  53671. Graph.prototype.eachEdge = function (cb, context) {
  53672. var edges = this.edges;
  53673. var len = edges.length;
  53674. for (var i = 0; i < len; i++) {
  53675. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  53676. cb.call(context, edges[i], i);
  53677. }
  53678. }
  53679. };
  53680. /**
  53681. * Breadth first traverse
  53682. * Return true to stop traversing
  53683. */
  53684. Graph.prototype.breadthFirstTraverse = function (cb, startNode, direction, context) {
  53685. if (!(startNode instanceof GraphNode)) {
  53686. startNode = this._nodesMap[generateNodeKey(startNode)];
  53687. }
  53688. if (!startNode) {
  53689. return;
  53690. }
  53691. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  53692. for (var i = 0; i < this.nodes.length; i++) {
  53693. this.nodes[i].__visited = false;
  53694. }
  53695. if (cb.call(context, startNode, null)) {
  53696. return;
  53697. }
  53698. var queue = [startNode];
  53699. while (queue.length) {
  53700. var currentNode = queue.shift();
  53701. var edges = currentNode[edgeType];
  53702. for (var i = 0; i < edges.length; i++) {
  53703. var e = edges[i];
  53704. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  53705. if (!otherNode.__visited) {
  53706. if (cb.call(context, otherNode, currentNode)) {
  53707. // Stop traversing
  53708. return;
  53709. }
  53710. queue.push(otherNode);
  53711. otherNode.__visited = true;
  53712. }
  53713. }
  53714. }
  53715. };
  53716. // depthFirstTraverse(
  53717. // cb, startNode, direction, context
  53718. // ) {
  53719. // };
  53720. // Filter update
  53721. Graph.prototype.update = function () {
  53722. var data = this.data;
  53723. var edgeData = this.edgeData;
  53724. var nodes = this.nodes;
  53725. var edges = this.edges;
  53726. for (var i = 0, len = nodes.length; i < len; i++) {
  53727. nodes[i].dataIndex = -1;
  53728. }
  53729. for (var i = 0, len = data.count(); i < len; i++) {
  53730. nodes[data.getRawIndex(i)].dataIndex = i;
  53731. }
  53732. edgeData.filterSelf(function (idx) {
  53733. var edge = edges[edgeData.getRawIndex(idx)];
  53734. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  53735. }); // Update edge
  53736. for (var i = 0, len = edges.length; i < len; i++) {
  53737. edges[i].dataIndex = -1;
  53738. }
  53739. for (var i = 0, len = edgeData.count(); i < len; i++) {
  53740. edges[edgeData.getRawIndex(i)].dataIndex = i;
  53741. }
  53742. };
  53743. /**
  53744. * @return {module:echarts/data/Graph}
  53745. */
  53746. Graph.prototype.clone = function () {
  53747. var graph = new Graph(this._directed);
  53748. var nodes = this.nodes;
  53749. var edges = this.edges;
  53750. for (var i = 0; i < nodes.length; i++) {
  53751. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  53752. }
  53753. for (var i = 0; i < edges.length; i++) {
  53754. var e = edges[i];
  53755. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  53756. }
  53757. return graph;
  53758. };
  53759. return Graph;
  53760. }();
  53761. var GraphNode =
  53762. /** @class */
  53763. function () {
  53764. function GraphNode(id, dataIndex) {
  53765. this.inEdges = [];
  53766. this.outEdges = [];
  53767. this.edges = [];
  53768. this.dataIndex = -1;
  53769. this.id = id == null ? '' : id;
  53770. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53771. }
  53772. /**
  53773. * @return {number}
  53774. */
  53775. GraphNode.prototype.degree = function () {
  53776. return this.edges.length;
  53777. };
  53778. /**
  53779. * @return {number}
  53780. */
  53781. GraphNode.prototype.inDegree = function () {
  53782. return this.inEdges.length;
  53783. };
  53784. /**
  53785. * @return {number}
  53786. */
  53787. GraphNode.prototype.outDegree = function () {
  53788. return this.outEdges.length;
  53789. };
  53790. GraphNode.prototype.getModel = function (path) {
  53791. if (this.dataIndex < 0) {
  53792. return;
  53793. }
  53794. var graph = this.hostGraph;
  53795. var itemModel = graph.data.getItemModel(this.dataIndex);
  53796. return itemModel.getModel(path);
  53797. };
  53798. GraphNode.prototype.getAdjacentDataIndices = function () {
  53799. var dataIndices = {
  53800. edge: [],
  53801. node: []
  53802. };
  53803. for (var i = 0; i < this.edges.length; i++) {
  53804. var adjacentEdge = this.edges[i];
  53805. if (adjacentEdge.dataIndex < 0) {
  53806. continue;
  53807. }
  53808. dataIndices.edge.push(adjacentEdge.dataIndex);
  53809. dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex);
  53810. }
  53811. return dataIndices;
  53812. };
  53813. GraphNode.prototype.getTrajectoryDataIndices = function () {
  53814. var connectedEdgesMap = createHashMap();
  53815. var connectedNodesMap = createHashMap();
  53816. for (var i = 0; i < this.edges.length; i++) {
  53817. var adjacentEdge = this.edges[i];
  53818. if (adjacentEdge.dataIndex < 0) {
  53819. continue;
  53820. }
  53821. connectedEdgesMap.set(adjacentEdge.dataIndex, true);
  53822. var sourceNodesQueue = [adjacentEdge.node1];
  53823. var targetNodesQueue = [adjacentEdge.node2];
  53824. var nodeIteratorIndex = 0;
  53825. while (nodeIteratorIndex < sourceNodesQueue.length) {
  53826. var sourceNode = sourceNodesQueue[nodeIteratorIndex];
  53827. nodeIteratorIndex++;
  53828. connectedNodesMap.set(sourceNode.dataIndex, true);
  53829. for (var j = 0; j < sourceNode.inEdges.length; j++) {
  53830. connectedEdgesMap.set(sourceNode.inEdges[j].dataIndex, true);
  53831. sourceNodesQueue.push(sourceNode.inEdges[j].node1);
  53832. }
  53833. }
  53834. nodeIteratorIndex = 0;
  53835. while (nodeIteratorIndex < targetNodesQueue.length) {
  53836. var targetNode = targetNodesQueue[nodeIteratorIndex];
  53837. nodeIteratorIndex++;
  53838. connectedNodesMap.set(targetNode.dataIndex, true);
  53839. for (var j = 0; j < targetNode.outEdges.length; j++) {
  53840. connectedEdgesMap.set(targetNode.outEdges[j].dataIndex, true);
  53841. targetNodesQueue.push(targetNode.outEdges[j].node2);
  53842. }
  53843. }
  53844. }
  53845. return {
  53846. edge: connectedEdgesMap.keys(),
  53847. node: connectedNodesMap.keys()
  53848. };
  53849. };
  53850. return GraphNode;
  53851. }();
  53852. var GraphEdge =
  53853. /** @class */
  53854. function () {
  53855. function GraphEdge(n1, n2, dataIndex) {
  53856. this.dataIndex = -1;
  53857. this.node1 = n1;
  53858. this.node2 = n2;
  53859. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  53860. } // eslint-disable-next-line @typescript-eslint/no-unused-vars
  53861. GraphEdge.prototype.getModel = function (path) {
  53862. if (this.dataIndex < 0) {
  53863. return;
  53864. }
  53865. var graph = this.hostGraph;
  53866. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  53867. return itemModel.getModel(path);
  53868. };
  53869. GraphEdge.prototype.getAdjacentDataIndices = function () {
  53870. return {
  53871. edge: [this.dataIndex],
  53872. node: [this.node1.dataIndex, this.node2.dataIndex]
  53873. };
  53874. };
  53875. GraphEdge.prototype.getTrajectoryDataIndices = function () {
  53876. var connectedEdgesMap = createHashMap();
  53877. var connectedNodesMap = createHashMap();
  53878. connectedEdgesMap.set(this.dataIndex, true);
  53879. var sourceNodes = [this.node1];
  53880. var targetNodes = [this.node2];
  53881. var nodeIteratorIndex = 0;
  53882. while (nodeIteratorIndex < sourceNodes.length) {
  53883. var sourceNode = sourceNodes[nodeIteratorIndex];
  53884. nodeIteratorIndex++;
  53885. connectedNodesMap.set(sourceNode.dataIndex, true);
  53886. for (var j = 0; j < sourceNode.inEdges.length; j++) {
  53887. connectedEdgesMap.set(sourceNode.inEdges[j].dataIndex, true);
  53888. sourceNodes.push(sourceNode.inEdges[j].node1);
  53889. }
  53890. }
  53891. nodeIteratorIndex = 0;
  53892. while (nodeIteratorIndex < targetNodes.length) {
  53893. var targetNode = targetNodes[nodeIteratorIndex];
  53894. nodeIteratorIndex++;
  53895. connectedNodesMap.set(targetNode.dataIndex, true);
  53896. for (var j = 0; j < targetNode.outEdges.length; j++) {
  53897. connectedEdgesMap.set(targetNode.outEdges[j].dataIndex, true);
  53898. targetNodes.push(targetNode.outEdges[j].node2);
  53899. }
  53900. }
  53901. return {
  53902. edge: connectedEdgesMap.keys(),
  53903. node: connectedNodesMap.keys()
  53904. };
  53905. };
  53906. return GraphEdge;
  53907. }();
  53908. function createGraphDataProxyMixin(hostName, dataName) {
  53909. return {
  53910. /**
  53911. * @param Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  53912. */
  53913. getValue: function (dimension) {
  53914. var data = this[hostName][dataName];
  53915. return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
  53916. },
  53917. // TODO: TYPE stricter type.
  53918. setVisual: function (key, value) {
  53919. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  53920. },
  53921. getVisual: function (key) {
  53922. return this[hostName][dataName].getItemVisual(this.dataIndex, key);
  53923. },
  53924. setLayout: function (layout, merge) {
  53925. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge);
  53926. },
  53927. getLayout: function () {
  53928. return this[hostName][dataName].getItemLayout(this.dataIndex);
  53929. },
  53930. getGraphicEl: function () {
  53931. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  53932. },
  53933. getRawIndex: function () {
  53934. return this[hostName][dataName].getRawIndex(this.dataIndex);
  53935. }
  53936. };
  53937. }
  53938. mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data'));
  53939. mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  53940. function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  53941. // ??? TODO
  53942. // support dataset?
  53943. var graph = new Graph(directed);
  53944. for (var i = 0; i < nodes.length; i++) {
  53945. graph.addNode(retrieve( // Id, name, dataIndex
  53946. nodes[i].id, nodes[i].name, i), i);
  53947. }
  53948. var linkNameList = [];
  53949. var validEdges = [];
  53950. var linkCount = 0;
  53951. for (var i = 0; i < edges.length; i++) {
  53952. var link = edges[i];
  53953. var source = link.source;
  53954. var target = link.target; // addEdge may fail when source or target not exists
  53955. if (graph.addEdge(source, target, linkCount)) {
  53956. validEdges.push(link);
  53957. linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target));
  53958. linkCount++;
  53959. }
  53960. }
  53961. var coordSys = seriesModel.get('coordinateSystem');
  53962. var nodeData;
  53963. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  53964. nodeData = createSeriesData(nodes, seriesModel);
  53965. } else {
  53966. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  53967. var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  53968. // `value` dimension, but graph need `value` dimension. It's better to
  53969. // uniform this behavior.
  53970. if (indexOf(coordDimensions, 'value') < 0) {
  53971. coordDimensions.concat(['value']);
  53972. }
  53973. var dimensions = prepareSeriesDataSchema(nodes, {
  53974. coordDimensions: coordDimensions,
  53975. encodeDefine: seriesModel.getEncode()
  53976. }).dimensions;
  53977. nodeData = new SeriesData(dimensions, seriesModel);
  53978. nodeData.initData(nodes);
  53979. }
  53980. var edgeData = new SeriesData(['value'], seriesModel);
  53981. edgeData.initData(validEdges, linkNameList);
  53982. beforeLink && beforeLink(nodeData, edgeData);
  53983. linkSeriesData({
  53984. mainData: nodeData,
  53985. struct: graph,
  53986. structAttr: 'graph',
  53987. datas: {
  53988. node: nodeData,
  53989. edge: edgeData
  53990. },
  53991. datasAttr: {
  53992. node: 'data',
  53993. edge: 'edgeData'
  53994. }
  53995. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  53996. graph.update();
  53997. return graph;
  53998. }
  53999. var GraphSeriesModel =
  54000. /** @class */
  54001. function (_super) {
  54002. __extends(GraphSeriesModel, _super);
  54003. function GraphSeriesModel() {
  54004. var _this = _super !== null && _super.apply(this, arguments) || this;
  54005. _this.type = GraphSeriesModel.type;
  54006. _this.hasSymbolVisual = true;
  54007. return _this;
  54008. }
  54009. GraphSeriesModel.prototype.init = function (option) {
  54010. _super.prototype.init.apply(this, arguments);
  54011. var self = this;
  54012. function getCategoriesData() {
  54013. return self._categoriesData;
  54014. } // Provide data for legend select
  54015. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  54016. this.fillDataTextStyle(option.edges || option.links);
  54017. this._updateCategoriesData();
  54018. };
  54019. GraphSeriesModel.prototype.mergeOption = function (option) {
  54020. _super.prototype.mergeOption.apply(this, arguments);
  54021. this.fillDataTextStyle(option.edges || option.links);
  54022. this._updateCategoriesData();
  54023. };
  54024. GraphSeriesModel.prototype.mergeDefaultAndTheme = function (option) {
  54025. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  54026. defaultEmphasis(option, 'edgeLabel', ['show']);
  54027. };
  54028. GraphSeriesModel.prototype.getInitialData = function (option, ecModel) {
  54029. var edges = option.edges || option.links || [];
  54030. var nodes = option.data || option.nodes || [];
  54031. var self = this;
  54032. if (nodes && edges) {
  54033. // auto curveness
  54034. initCurvenessList(this);
  54035. var graph = createGraphFromNodeEdge(nodes, edges, this, true, beforeLink);
  54036. each(graph.edges, function (edge) {
  54037. createEdgeMapForCurveness(edge.node1, edge.node2, this, edge.dataIndex);
  54038. }, this);
  54039. return graph.data;
  54040. }
  54041. function beforeLink(nodeData, edgeData) {
  54042. // Overwrite nodeData.getItemModel to
  54043. nodeData.wrapMethod('getItemModel', function (model) {
  54044. var categoriesModels = self._categoriesModels;
  54045. var categoryIdx = model.getShallow('category');
  54046. var categoryModel = categoriesModels[categoryIdx];
  54047. if (categoryModel) {
  54048. categoryModel.parentModel = model.parentModel;
  54049. model.parentModel = categoryModel;
  54050. }
  54051. return model;
  54052. }); // TODO Inherit resolveParentPath by default in Model#getModel?
  54053. var oldGetModel = Model.prototype.getModel;
  54054. function newGetModel(path, parentModel) {
  54055. var model = oldGetModel.call(this, path, parentModel);
  54056. model.resolveParentPath = resolveParentPath;
  54057. return model;
  54058. }
  54059. edgeData.wrapMethod('getItemModel', function (model) {
  54060. model.resolveParentPath = resolveParentPath;
  54061. model.getModel = newGetModel;
  54062. return model;
  54063. });
  54064. function resolveParentPath(pathArr) {
  54065. if (pathArr && (pathArr[0] === 'label' || pathArr[1] === 'label')) {
  54066. var newPathArr = pathArr.slice();
  54067. if (pathArr[0] === 'label') {
  54068. newPathArr[0] = 'edgeLabel';
  54069. } else if (pathArr[1] === 'label') {
  54070. newPathArr[1] = 'edgeLabel';
  54071. }
  54072. return newPathArr;
  54073. }
  54074. return pathArr;
  54075. }
  54076. }
  54077. };
  54078. GraphSeriesModel.prototype.getGraph = function () {
  54079. return this.getData().graph;
  54080. };
  54081. GraphSeriesModel.prototype.getEdgeData = function () {
  54082. return this.getGraph().edgeData;
  54083. };
  54084. GraphSeriesModel.prototype.getCategoriesData = function () {
  54085. return this._categoriesData;
  54086. };
  54087. GraphSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  54088. if (dataType === 'edge') {
  54089. var nodeData = this.getData();
  54090. var params = this.getDataParams(dataIndex, dataType);
  54091. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  54092. var sourceName = nodeData.getName(edge.node1.dataIndex);
  54093. var targetName = nodeData.getName(edge.node2.dataIndex);
  54094. var nameArr = [];
  54095. sourceName != null && nameArr.push(sourceName);
  54096. targetName != null && nameArr.push(targetName);
  54097. return createTooltipMarkup('nameValue', {
  54098. name: nameArr.join(' > '),
  54099. value: params.value,
  54100. noValue: params.value == null
  54101. });
  54102. } // dataType === 'node' or empty
  54103. var nodeMarkup = defaultSeriesFormatTooltip({
  54104. series: this,
  54105. dataIndex: dataIndex,
  54106. multipleSeries: multipleSeries
  54107. });
  54108. return nodeMarkup;
  54109. };
  54110. GraphSeriesModel.prototype._updateCategoriesData = function () {
  54111. var categories = map(this.option.categories || [], function (category) {
  54112. // Data must has value
  54113. return category.value != null ? category : extend({
  54114. value: 0
  54115. }, category);
  54116. });
  54117. var categoriesData = new SeriesData(['value'], this);
  54118. categoriesData.initData(categories);
  54119. this._categoriesData = categoriesData;
  54120. this._categoriesModels = categoriesData.mapArray(function (idx) {
  54121. return categoriesData.getItemModel(idx);
  54122. });
  54123. };
  54124. GraphSeriesModel.prototype.setZoom = function (zoom) {
  54125. this.option.zoom = zoom;
  54126. };
  54127. GraphSeriesModel.prototype.setCenter = function (center) {
  54128. this.option.center = center;
  54129. };
  54130. GraphSeriesModel.prototype.isAnimationEnabled = function () {
  54131. return _super.prototype.isAnimationEnabled.call(this) // Not enable animation when do force layout
  54132. && !(this.get('layout') === 'force' && this.get(['force', 'layoutAnimation']));
  54133. };
  54134. GraphSeriesModel.type = 'series.graph';
  54135. GraphSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  54136. GraphSeriesModel.defaultOption = {
  54137. // zlevel: 0,
  54138. z: 2,
  54139. coordinateSystem: 'view',
  54140. // Default option for all coordinate systems
  54141. // xAxisIndex: 0,
  54142. // yAxisIndex: 0,
  54143. // polarIndex: 0,
  54144. // geoIndex: 0,
  54145. legendHoverLink: true,
  54146. layout: null,
  54147. // Configuration of circular layout
  54148. circular: {
  54149. rotateLabel: false
  54150. },
  54151. // Configuration of force directed layout
  54152. force: {
  54153. initLayout: null,
  54154. // Node repulsion. Can be an array to represent range.
  54155. repulsion: [0, 50],
  54156. gravity: 0.1,
  54157. // Initial friction
  54158. friction: 0.6,
  54159. // Edge length. Can be an array to represent range.
  54160. edgeLength: 30,
  54161. layoutAnimation: true
  54162. },
  54163. left: 'center',
  54164. top: 'center',
  54165. // right: null,
  54166. // bottom: null,
  54167. // width: '80%',
  54168. // height: '80%',
  54169. symbol: 'circle',
  54170. symbolSize: 10,
  54171. edgeSymbol: ['none', 'none'],
  54172. edgeSymbolSize: 10,
  54173. edgeLabel: {
  54174. position: 'middle',
  54175. distance: 5
  54176. },
  54177. draggable: false,
  54178. roam: false,
  54179. // Default on center of graph
  54180. center: null,
  54181. zoom: 1,
  54182. // Symbol size scale ratio in roam
  54183. nodeScaleRatio: 0.6,
  54184. // cursor: null,
  54185. // categories: [],
  54186. // data: []
  54187. // Or
  54188. // nodes: []
  54189. //
  54190. // links: []
  54191. // Or
  54192. // edges: []
  54193. label: {
  54194. show: false,
  54195. formatter: '{b}'
  54196. },
  54197. itemStyle: {},
  54198. lineStyle: {
  54199. color: '#aaa',
  54200. width: 1,
  54201. opacity: 0.5
  54202. },
  54203. emphasis: {
  54204. scale: true,
  54205. label: {
  54206. show: true
  54207. }
  54208. },
  54209. select: {
  54210. itemStyle: {
  54211. borderColor: '#212121'
  54212. }
  54213. }
  54214. };
  54215. return GraphSeriesModel;
  54216. }(SeriesModel);
  54217. var actionInfo = {
  54218. type: 'graphRoam',
  54219. event: 'graphRoam',
  54220. update: 'none'
  54221. };
  54222. function install$d(registers) {
  54223. registers.registerChartView(GraphView);
  54224. registers.registerSeriesModel(GraphSeriesModel);
  54225. registers.registerProcessor(categoryFilter);
  54226. registers.registerVisual(categoryVisual);
  54227. registers.registerVisual(graphEdgeVisual);
  54228. registers.registerLayout(graphSimpleLayout);
  54229. registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout);
  54230. registers.registerLayout(graphForceLayout);
  54231. registers.registerCoordinateSystem('graphView', {
  54232. dimensions: View.dimensions,
  54233. create: createViewCoordSys
  54234. }); // Register legacy focus actions
  54235. registers.registerAction({
  54236. type: 'focusNodeAdjacency',
  54237. event: 'focusNodeAdjacency',
  54238. update: 'series:focusNodeAdjacency'
  54239. }, noop);
  54240. registers.registerAction({
  54241. type: 'unfocusNodeAdjacency',
  54242. event: 'unfocusNodeAdjacency',
  54243. update: 'series:unfocusNodeAdjacency'
  54244. }, noop); // Register roam action.
  54245. registers.registerAction(actionInfo, function (payload, ecModel, api) {
  54246. ecModel.eachComponent({
  54247. mainType: 'series',
  54248. query: payload
  54249. }, function (seriesModel) {
  54250. var coordSys = seriesModel.coordinateSystem;
  54251. var res = updateCenterAndZoom(coordSys, payload, undefined, api);
  54252. seriesModel.setCenter && seriesModel.setCenter(res.center);
  54253. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  54254. });
  54255. });
  54256. }
  54257. var PointerShape =
  54258. /** @class */
  54259. function () {
  54260. function PointerShape() {
  54261. this.angle = 0;
  54262. this.width = 10;
  54263. this.r = 10;
  54264. this.x = 0;
  54265. this.y = 0;
  54266. }
  54267. return PointerShape;
  54268. }();
  54269. var PointerPath =
  54270. /** @class */
  54271. function (_super) {
  54272. __extends(PointerPath, _super);
  54273. function PointerPath(opts) {
  54274. var _this = _super.call(this, opts) || this;
  54275. _this.type = 'pointer';
  54276. return _this;
  54277. }
  54278. PointerPath.prototype.getDefaultShape = function () {
  54279. return new PointerShape();
  54280. };
  54281. PointerPath.prototype.buildPath = function (ctx, shape) {
  54282. var mathCos = Math.cos;
  54283. var mathSin = Math.sin;
  54284. var r = shape.r;
  54285. var width = shape.width;
  54286. var angle = shape.angle;
  54287. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  54288. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  54289. angle = shape.angle - Math.PI / 2;
  54290. ctx.moveTo(x, y);
  54291. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  54292. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  54293. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  54294. ctx.lineTo(x, y);
  54295. };
  54296. return PointerPath;
  54297. }(Path);
  54298. function parsePosition(seriesModel, api) {
  54299. var center = seriesModel.get('center');
  54300. var width = api.getWidth();
  54301. var height = api.getHeight();
  54302. var size = Math.min(width, height);
  54303. var cx = parsePercent$1(center[0], api.getWidth());
  54304. var cy = parsePercent$1(center[1], api.getHeight());
  54305. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  54306. return {
  54307. cx: cx,
  54308. cy: cy,
  54309. r: r
  54310. };
  54311. }
  54312. function formatLabel(value, labelFormatter) {
  54313. var label = value == null ? '' : value + '';
  54314. if (labelFormatter) {
  54315. if (isString(labelFormatter)) {
  54316. label = labelFormatter.replace('{value}', label);
  54317. } else if (isFunction(labelFormatter)) {
  54318. label = labelFormatter(value);
  54319. }
  54320. }
  54321. return label;
  54322. }
  54323. var GaugeView =
  54324. /** @class */
  54325. function (_super) {
  54326. __extends(GaugeView, _super);
  54327. function GaugeView() {
  54328. var _this = _super !== null && _super.apply(this, arguments) || this;
  54329. _this.type = GaugeView.type;
  54330. return _this;
  54331. }
  54332. GaugeView.prototype.render = function (seriesModel, ecModel, api) {
  54333. this.group.removeAll();
  54334. var colorList = seriesModel.get(['axisLine', 'lineStyle', 'color']);
  54335. var posInfo = parsePosition(seriesModel, api);
  54336. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  54337. this._data = seriesModel.getData();
  54338. };
  54339. GaugeView.prototype.dispose = function () {};
  54340. GaugeView.prototype._renderMain = function (seriesModel, ecModel, api, colorList, posInfo) {
  54341. var group = this.group;
  54342. var clockwise = seriesModel.get('clockwise');
  54343. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  54344. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  54345. var axisLineModel = seriesModel.getModel('axisLine');
  54346. var roundCap = axisLineModel.get('roundCap');
  54347. var MainPath = roundCap ? SausagePath : Sector;
  54348. var showAxis = axisLineModel.get('show');
  54349. var lineStyleModel = axisLineModel.getModel('lineStyle');
  54350. var axisLineWidth = lineStyleModel.get('width');
  54351. var angles = [startAngle, endAngle];
  54352. normalizeArcAngles(angles, !clockwise);
  54353. startAngle = angles[0];
  54354. endAngle = angles[1];
  54355. var angleRangeSpan = endAngle - startAngle;
  54356. var prevEndAngle = startAngle;
  54357. var sectors = [];
  54358. for (var i = 0; showAxis && i < colorList.length; i++) {
  54359. // Clamp
  54360. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  54361. endAngle = startAngle + angleRangeSpan * percent;
  54362. var sector = new MainPath({
  54363. shape: {
  54364. startAngle: prevEndAngle,
  54365. endAngle: endAngle,
  54366. cx: posInfo.cx,
  54367. cy: posInfo.cy,
  54368. clockwise: clockwise,
  54369. r0: posInfo.r - axisLineWidth,
  54370. r: posInfo.r
  54371. },
  54372. silent: true
  54373. });
  54374. sector.setStyle({
  54375. fill: colorList[i][1]
  54376. });
  54377. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  54378. // so the properties for stroking are useless
  54379. ['color', 'width']));
  54380. sectors.push(sector);
  54381. prevEndAngle = endAngle;
  54382. }
  54383. sectors.reverse();
  54384. each(sectors, function (sector) {
  54385. return group.add(sector);
  54386. });
  54387. var getColor = function (percent) {
  54388. // Less than 0
  54389. if (percent <= 0) {
  54390. return colorList[0][1];
  54391. }
  54392. var i;
  54393. for (i = 0; i < colorList.length; i++) {
  54394. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  54395. return colorList[i][1];
  54396. }
  54397. } // More than 1
  54398. return colorList[i - 1][1];
  54399. };
  54400. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54401. this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo);
  54402. this._renderAnchor(seriesModel, posInfo);
  54403. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  54404. };
  54405. GaugeView.prototype._renderTicks = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54406. var group = this.group;
  54407. var cx = posInfo.cx;
  54408. var cy = posInfo.cy;
  54409. var r = posInfo.r;
  54410. var minVal = +seriesModel.get('min');
  54411. var maxVal = +seriesModel.get('max');
  54412. var splitLineModel = seriesModel.getModel('splitLine');
  54413. var tickModel = seriesModel.getModel('axisTick');
  54414. var labelModel = seriesModel.getModel('axisLabel');
  54415. var splitNumber = seriesModel.get('splitNumber');
  54416. var subSplitNumber = tickModel.get('splitNumber');
  54417. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  54418. var tickLen = parsePercent$1(tickModel.get('length'), r);
  54419. var angle = startAngle;
  54420. var step = (endAngle - startAngle) / splitNumber;
  54421. var subStep = step / subSplitNumber;
  54422. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  54423. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  54424. var splitLineDistance = splitLineModel.get('distance');
  54425. var unitX;
  54426. var unitY;
  54427. for (var i = 0; i <= splitNumber; i++) {
  54428. unitX = Math.cos(angle);
  54429. unitY = Math.sin(angle); // Split line
  54430. if (splitLineModel.get('show')) {
  54431. var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth;
  54432. var splitLine = new Line({
  54433. shape: {
  54434. x1: unitX * (r - distance) + cx,
  54435. y1: unitY * (r - distance) + cy,
  54436. x2: unitX * (r - splitLineLen - distance) + cx,
  54437. y2: unitY * (r - splitLineLen - distance) + cy
  54438. },
  54439. style: splitLineStyle,
  54440. silent: true
  54441. });
  54442. if (splitLineStyle.stroke === 'auto') {
  54443. splitLine.setStyle({
  54444. stroke: getColor(i / splitNumber)
  54445. });
  54446. }
  54447. group.add(splitLine);
  54448. } // Label
  54449. if (labelModel.get('show')) {
  54450. var distance = labelModel.get('distance') + splitLineDistance;
  54451. var label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  54452. var autoColor = getColor(i / splitNumber);
  54453. var textStyleX = unitX * (r - splitLineLen - distance) + cx;
  54454. var textStyleY = unitY * (r - splitLineLen - distance) + cy;
  54455. var rotateType = labelModel.get('rotate');
  54456. var rotate = 0;
  54457. if (rotateType === 'radial') {
  54458. rotate = -angle + 2 * Math.PI;
  54459. if (rotate > Math.PI / 2) {
  54460. rotate += Math.PI;
  54461. }
  54462. } else if (rotateType === 'tangential') {
  54463. rotate = -angle - Math.PI / 2;
  54464. } else if (isNumber(rotateType)) {
  54465. rotate = rotateType * Math.PI / 180;
  54466. }
  54467. if (rotate === 0) {
  54468. group.add(new ZRText({
  54469. style: createTextStyle(labelModel, {
  54470. text: label,
  54471. x: textStyleX,
  54472. y: textStyleY,
  54473. verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle',
  54474. align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  54475. }, {
  54476. inheritColor: autoColor
  54477. }),
  54478. silent: true
  54479. }));
  54480. } else {
  54481. group.add(new ZRText({
  54482. style: createTextStyle(labelModel, {
  54483. text: label,
  54484. x: textStyleX,
  54485. y: textStyleY,
  54486. verticalAlign: 'middle',
  54487. align: 'center'
  54488. }, {
  54489. inheritColor: autoColor
  54490. }),
  54491. silent: true,
  54492. originX: textStyleX,
  54493. originY: textStyleY,
  54494. rotation: rotate
  54495. }));
  54496. }
  54497. } // Axis tick
  54498. if (tickModel.get('show') && i !== splitNumber) {
  54499. var distance = tickModel.get('distance');
  54500. distance = distance ? distance + axisLineWidth : axisLineWidth;
  54501. for (var j = 0; j <= subSplitNumber; j++) {
  54502. unitX = Math.cos(angle);
  54503. unitY = Math.sin(angle);
  54504. var tickLine = new Line({
  54505. shape: {
  54506. x1: unitX * (r - distance) + cx,
  54507. y1: unitY * (r - distance) + cy,
  54508. x2: unitX * (r - tickLen - distance) + cx,
  54509. y2: unitY * (r - tickLen - distance) + cy
  54510. },
  54511. silent: true,
  54512. style: tickLineStyle
  54513. });
  54514. if (tickLineStyle.stroke === 'auto') {
  54515. tickLine.setStyle({
  54516. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  54517. });
  54518. }
  54519. group.add(tickLine);
  54520. angle += subStep;
  54521. }
  54522. angle -= subStep;
  54523. } else {
  54524. angle += step;
  54525. }
  54526. }
  54527. };
  54528. GaugeView.prototype._renderPointer = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  54529. var group = this.group;
  54530. var oldData = this._data;
  54531. var oldProgressData = this._progressEls;
  54532. var progressList = [];
  54533. var showPointer = seriesModel.get(['pointer', 'show']);
  54534. var progressModel = seriesModel.getModel('progress');
  54535. var showProgress = progressModel.get('show');
  54536. var data = seriesModel.getData();
  54537. var valueDim = data.mapDimension('value');
  54538. var minVal = +seriesModel.get('min');
  54539. var maxVal = +seriesModel.get('max');
  54540. var valueExtent = [minVal, maxVal];
  54541. var angleExtent = [startAngle, endAngle];
  54542. function createPointer(idx, angle) {
  54543. var itemModel = data.getItemModel(idx);
  54544. var pointerModel = itemModel.getModel('pointer');
  54545. var pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r);
  54546. var pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r);
  54547. var pointerStr = seriesModel.get(['pointer', 'icon']);
  54548. var pointerOffset = pointerModel.get('offsetCenter');
  54549. var pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r);
  54550. var pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r);
  54551. var pointerKeepAspect = pointerModel.get('keepAspect');
  54552. var pointer; // not exist icon type will be set 'rect'
  54553. if (pointerStr) {
  54554. pointer = createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect);
  54555. } else {
  54556. pointer = new PointerPath({
  54557. shape: {
  54558. angle: -Math.PI / 2,
  54559. width: pointerWidth,
  54560. r: pointerLength,
  54561. x: pointerOffsetX,
  54562. y: pointerOffsetY
  54563. }
  54564. });
  54565. }
  54566. pointer.rotation = -(angle + Math.PI / 2);
  54567. pointer.x = posInfo.cx;
  54568. pointer.y = posInfo.cy;
  54569. return pointer;
  54570. }
  54571. function createProgress(idx, endAngle) {
  54572. var roundCap = progressModel.get('roundCap');
  54573. var ProgressPath = roundCap ? SausagePath : Sector;
  54574. var isOverlap = progressModel.get('overlap');
  54575. var progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count();
  54576. var r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth;
  54577. var r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth;
  54578. var progress = new ProgressPath({
  54579. shape: {
  54580. startAngle: startAngle,
  54581. endAngle: endAngle,
  54582. cx: posInfo.cx,
  54583. cy: posInfo.cy,
  54584. clockwise: clockwise,
  54585. r0: r0,
  54586. r: r
  54587. }
  54588. });
  54589. isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal);
  54590. return progress;
  54591. }
  54592. if (showProgress || showPointer) {
  54593. data.diff(oldData).add(function (idx) {
  54594. var val = data.get(valueDim, idx);
  54595. if (showPointer) {
  54596. var pointer = createPointer(idx, startAngle); // TODO hide pointer on NaN value?
  54597. initProps(pointer, {
  54598. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54599. }, seriesModel);
  54600. group.add(pointer);
  54601. data.setItemGraphicEl(idx, pointer);
  54602. }
  54603. if (showProgress) {
  54604. var progress = createProgress(idx, startAngle);
  54605. var isClip = progressModel.get('clip');
  54606. initProps(progress, {
  54607. shape: {
  54608. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54609. }
  54610. }, seriesModel);
  54611. group.add(progress); // Add data index and series index for indexing the data by element
  54612. // Useful in tooltip
  54613. setCommonECData(seriesModel.seriesIndex, data.dataType, idx, progress);
  54614. progressList[idx] = progress;
  54615. }
  54616. }).update(function (newIdx, oldIdx) {
  54617. var val = data.get(valueDim, newIdx);
  54618. if (showPointer) {
  54619. var previousPointer = oldData.getItemGraphicEl(oldIdx);
  54620. var previousRotate = previousPointer ? previousPointer.rotation : startAngle;
  54621. var pointer = createPointer(newIdx, previousRotate);
  54622. pointer.rotation = previousRotate;
  54623. updateProps(pointer, {
  54624. rotation: -((isNaN(+val) ? angleExtent[0] : linearMap(val, valueExtent, angleExtent, true)) + Math.PI / 2)
  54625. }, seriesModel);
  54626. group.add(pointer);
  54627. data.setItemGraphicEl(newIdx, pointer);
  54628. }
  54629. if (showProgress) {
  54630. var previousProgress = oldProgressData[oldIdx];
  54631. var previousEndAngle = previousProgress ? previousProgress.shape.endAngle : startAngle;
  54632. var progress = createProgress(newIdx, previousEndAngle);
  54633. var isClip = progressModel.get('clip');
  54634. updateProps(progress, {
  54635. shape: {
  54636. endAngle: linearMap(val, valueExtent, angleExtent, isClip)
  54637. }
  54638. }, seriesModel);
  54639. group.add(progress); // Add data index and series index for indexing the data by element
  54640. // Useful in tooltip
  54641. setCommonECData(seriesModel.seriesIndex, data.dataType, newIdx, progress);
  54642. progressList[newIdx] = progress;
  54643. }
  54644. }).execute();
  54645. data.each(function (idx) {
  54646. var itemModel = data.getItemModel(idx);
  54647. var emphasisModel = itemModel.getModel('emphasis');
  54648. var focus = emphasisModel.get('focus');
  54649. var blurScope = emphasisModel.get('blurScope');
  54650. var emphasisDisabled = emphasisModel.get('disabled');
  54651. if (showPointer) {
  54652. var pointer = data.getItemGraphicEl(idx);
  54653. var symbolStyle = data.getItemVisual(idx, 'style');
  54654. var visualColor = symbolStyle.fill;
  54655. if (pointer instanceof ZRImage) {
  54656. var pathStyle = pointer.style;
  54657. pointer.useStyle(extend({
  54658. image: pathStyle.image,
  54659. x: pathStyle.x,
  54660. y: pathStyle.y,
  54661. width: pathStyle.width,
  54662. height: pathStyle.height
  54663. }, symbolStyle));
  54664. } else {
  54665. pointer.useStyle(symbolStyle);
  54666. pointer.type !== 'pointer' && pointer.setColor(visualColor);
  54667. }
  54668. pointer.setStyle(itemModel.getModel(['pointer', 'itemStyle']).getItemStyle());
  54669. if (pointer.style.fill === 'auto') {
  54670. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  54671. }
  54672. pointer.z2EmphasisLift = 0;
  54673. setStatesStylesFromModel(pointer, itemModel);
  54674. toggleHoverEmphasis(pointer, focus, blurScope, emphasisDisabled);
  54675. }
  54676. if (showProgress) {
  54677. var progress = progressList[idx];
  54678. progress.useStyle(data.getItemVisual(idx, 'style'));
  54679. progress.setStyle(itemModel.getModel(['progress', 'itemStyle']).getItemStyle());
  54680. progress.z2EmphasisLift = 0;
  54681. setStatesStylesFromModel(progress, itemModel);
  54682. toggleHoverEmphasis(progress, focus, blurScope, emphasisDisabled);
  54683. }
  54684. });
  54685. this._progressEls = progressList;
  54686. }
  54687. };
  54688. GaugeView.prototype._renderAnchor = function (seriesModel, posInfo) {
  54689. var anchorModel = seriesModel.getModel('anchor');
  54690. var showAnchor = anchorModel.get('show');
  54691. if (showAnchor) {
  54692. var anchorSize = anchorModel.get('size');
  54693. var anchorType = anchorModel.get('icon');
  54694. var offsetCenter = anchorModel.get('offsetCenter');
  54695. var anchorKeepAspect = anchorModel.get('keepAspect');
  54696. 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);
  54697. anchor.z2 = anchorModel.get('showAbove') ? 1 : 0;
  54698. anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle());
  54699. this.group.add(anchor);
  54700. }
  54701. };
  54702. GaugeView.prototype._renderTitleAndDetail = function (seriesModel, ecModel, api, getColor, posInfo) {
  54703. var _this = this;
  54704. var data = seriesModel.getData();
  54705. var valueDim = data.mapDimension('value');
  54706. var minVal = +seriesModel.get('min');
  54707. var maxVal = +seriesModel.get('max');
  54708. var contentGroup = new Group();
  54709. var newTitleEls = [];
  54710. var newDetailEls = [];
  54711. var hasAnimation = seriesModel.isAnimationEnabled();
  54712. var showPointerAbove = seriesModel.get(['pointer', 'showAbove']);
  54713. data.diff(this._data).add(function (idx) {
  54714. newTitleEls[idx] = new ZRText({
  54715. silent: true
  54716. });
  54717. newDetailEls[idx] = new ZRText({
  54718. silent: true
  54719. });
  54720. }).update(function (idx, oldIdx) {
  54721. newTitleEls[idx] = _this._titleEls[oldIdx];
  54722. newDetailEls[idx] = _this._detailEls[oldIdx];
  54723. }).execute();
  54724. data.each(function (idx) {
  54725. var itemModel = data.getItemModel(idx);
  54726. var value = data.get(valueDim, idx);
  54727. var itemGroup = new Group();
  54728. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  54729. var itemTitleModel = itemModel.getModel('title');
  54730. if (itemTitleModel.get('show')) {
  54731. var titleOffsetCenter = itemTitleModel.get('offsetCenter');
  54732. var titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r);
  54733. var titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r);
  54734. var labelEl = newTitleEls[idx];
  54735. labelEl.attr({
  54736. z2: showPointerAbove ? 0 : 2,
  54737. style: createTextStyle(itemTitleModel, {
  54738. x: titleX,
  54739. y: titleY,
  54740. text: data.getName(idx),
  54741. align: 'center',
  54742. verticalAlign: 'middle'
  54743. }, {
  54744. inheritColor: autoColor
  54745. })
  54746. });
  54747. itemGroup.add(labelEl);
  54748. }
  54749. var itemDetailModel = itemModel.getModel('detail');
  54750. if (itemDetailModel.get('show')) {
  54751. var detailOffsetCenter = itemDetailModel.get('offsetCenter');
  54752. var detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r);
  54753. var detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r);
  54754. var width = parsePercent$1(itemDetailModel.get('width'), posInfo.r);
  54755. var height = parsePercent$1(itemDetailModel.get('height'), posInfo.r);
  54756. var detailColor = seriesModel.get(['progress', 'show']) ? data.getItemVisual(idx, 'style').fill : autoColor;
  54757. var labelEl = newDetailEls[idx];
  54758. var formatter_1 = itemDetailModel.get('formatter');
  54759. labelEl.attr({
  54760. z2: showPointerAbove ? 0 : 2,
  54761. style: createTextStyle(itemDetailModel, {
  54762. x: detailX,
  54763. y: detailY,
  54764. text: formatLabel(value, formatter_1),
  54765. width: isNaN(width) ? null : width,
  54766. height: isNaN(height) ? null : height,
  54767. align: 'center',
  54768. verticalAlign: 'middle'
  54769. }, {
  54770. inheritColor: detailColor
  54771. })
  54772. });
  54773. setLabelValueAnimation(labelEl, {
  54774. normal: itemDetailModel
  54775. }, value, function (value) {
  54776. return formatLabel(value, formatter_1);
  54777. });
  54778. hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, {
  54779. getFormattedLabel: function (labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) {
  54780. return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1);
  54781. }
  54782. });
  54783. itemGroup.add(labelEl);
  54784. }
  54785. contentGroup.add(itemGroup);
  54786. });
  54787. this.group.add(contentGroup);
  54788. this._titleEls = newTitleEls;
  54789. this._detailEls = newDetailEls;
  54790. };
  54791. GaugeView.type = 'gauge';
  54792. return GaugeView;
  54793. }(ChartView);
  54794. var GaugeSeriesModel =
  54795. /** @class */
  54796. function (_super) {
  54797. __extends(GaugeSeriesModel, _super);
  54798. function GaugeSeriesModel() {
  54799. var _this = _super !== null && _super.apply(this, arguments) || this;
  54800. _this.type = GaugeSeriesModel.type;
  54801. _this.visualStyleAccessPath = 'itemStyle';
  54802. return _this;
  54803. }
  54804. GaugeSeriesModel.prototype.getInitialData = function (option, ecModel) {
  54805. return createSeriesDataSimply(this, ['value']);
  54806. };
  54807. GaugeSeriesModel.type = 'series.gauge';
  54808. GaugeSeriesModel.defaultOption = {
  54809. // zlevel: 0,
  54810. z: 2,
  54811. colorBy: 'data',
  54812. // 默认全局居中
  54813. center: ['50%', '50%'],
  54814. legendHoverLink: true,
  54815. radius: '75%',
  54816. startAngle: 225,
  54817. endAngle: -45,
  54818. clockwise: true,
  54819. // 最小值
  54820. min: 0,
  54821. // 最大值
  54822. max: 100,
  54823. // 分割段数,默认为10
  54824. splitNumber: 10,
  54825. // 坐标轴线
  54826. axisLine: {
  54827. // 默认显示,属性show控制显示与否
  54828. show: true,
  54829. roundCap: false,
  54830. lineStyle: {
  54831. color: [[1, '#E6EBF8']],
  54832. width: 10
  54833. }
  54834. },
  54835. // 坐标轴线
  54836. progress: {
  54837. // 默认显示,属性show控制显示与否
  54838. show: false,
  54839. overlap: true,
  54840. width: 10,
  54841. roundCap: false,
  54842. clip: true
  54843. },
  54844. // 分隔线
  54845. splitLine: {
  54846. // 默认显示,属性show控制显示与否
  54847. show: true,
  54848. // 属性length控制线长
  54849. length: 10,
  54850. distance: 10,
  54851. // 属性lineStyle(详见lineStyle)控制线条样式
  54852. lineStyle: {
  54853. color: '#63677A',
  54854. width: 3,
  54855. type: 'solid'
  54856. }
  54857. },
  54858. // 坐标轴小标记
  54859. axisTick: {
  54860. // 属性show控制显示与否,默认不显示
  54861. show: true,
  54862. // 每份split细分多少段
  54863. splitNumber: 5,
  54864. // 属性length控制线长
  54865. length: 6,
  54866. distance: 10,
  54867. // 属性lineStyle控制线条样式
  54868. lineStyle: {
  54869. color: '#63677A',
  54870. width: 1,
  54871. type: 'solid'
  54872. }
  54873. },
  54874. axisLabel: {
  54875. show: true,
  54876. distance: 15,
  54877. // formatter: null,
  54878. color: '#464646',
  54879. fontSize: 12,
  54880. rotate: 0
  54881. },
  54882. pointer: {
  54883. icon: null,
  54884. offsetCenter: [0, 0],
  54885. show: true,
  54886. showAbove: true,
  54887. length: '60%',
  54888. width: 6,
  54889. keepAspect: false
  54890. },
  54891. anchor: {
  54892. show: false,
  54893. showAbove: false,
  54894. size: 6,
  54895. icon: 'circle',
  54896. offsetCenter: [0, 0],
  54897. keepAspect: false,
  54898. itemStyle: {
  54899. color: '#fff',
  54900. borderWidth: 0,
  54901. borderColor: '#5470c6'
  54902. }
  54903. },
  54904. title: {
  54905. show: true,
  54906. // x, y,单位px
  54907. offsetCenter: [0, '20%'],
  54908. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54909. color: '#464646',
  54910. fontSize: 16,
  54911. valueAnimation: false
  54912. },
  54913. detail: {
  54914. show: true,
  54915. backgroundColor: 'rgba(0,0,0,0)',
  54916. borderWidth: 0,
  54917. borderColor: '#ccc',
  54918. width: 100,
  54919. height: null,
  54920. padding: [5, 10],
  54921. // x, y,单位px
  54922. offsetCenter: [0, '40%'],
  54923. // formatter: null,
  54924. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  54925. color: '#464646',
  54926. fontSize: 30,
  54927. fontWeight: 'bold',
  54928. lineHeight: 30,
  54929. valueAnimation: false
  54930. }
  54931. };
  54932. return GaugeSeriesModel;
  54933. }(SeriesModel);
  54934. function install$e(registers) {
  54935. registers.registerChartView(GaugeView);
  54936. registers.registerSeriesModel(GaugeSeriesModel);
  54937. }
  54938. var opacityAccessPath = ['itemStyle', 'opacity'];
  54939. /**
  54940. * Piece of pie including Sector, Label, LabelLine
  54941. */
  54942. var FunnelPiece =
  54943. /** @class */
  54944. function (_super) {
  54945. __extends(FunnelPiece, _super);
  54946. function FunnelPiece(data, idx) {
  54947. var _this = _super.call(this) || this;
  54948. var polygon = _this;
  54949. var labelLine = new Polyline();
  54950. var text = new ZRText();
  54951. polygon.setTextContent(text);
  54952. _this.setTextGuideLine(labelLine);
  54953. _this.updateData(data, idx, true);
  54954. return _this;
  54955. }
  54956. FunnelPiece.prototype.updateData = function (data, idx, firstCreate) {
  54957. var polygon = this;
  54958. var seriesModel = data.hostModel;
  54959. var itemModel = data.getItemModel(idx);
  54960. var layout = data.getItemLayout(idx);
  54961. var emphasisModel = itemModel.getModel('emphasis');
  54962. var opacity = itemModel.get(opacityAccessPath);
  54963. opacity = opacity == null ? 1 : opacity;
  54964. if (!firstCreate) {
  54965. saveOldStyle(polygon);
  54966. } // Update common style
  54967. polygon.useStyle(data.getItemVisual(idx, 'style'));
  54968. polygon.style.lineJoin = 'round';
  54969. if (firstCreate) {
  54970. polygon.setShape({
  54971. points: layout.points
  54972. });
  54973. polygon.style.opacity = 0;
  54974. initProps(polygon, {
  54975. style: {
  54976. opacity: opacity
  54977. }
  54978. }, seriesModel, idx);
  54979. } else {
  54980. updateProps(polygon, {
  54981. style: {
  54982. opacity: opacity
  54983. },
  54984. shape: {
  54985. points: layout.points
  54986. }
  54987. }, seriesModel, idx);
  54988. }
  54989. setStatesStylesFromModel(polygon, itemModel);
  54990. this._updateLabel(data, idx);
  54991. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  54992. };
  54993. FunnelPiece.prototype._updateLabel = function (data, idx) {
  54994. var polygon = this;
  54995. var labelLine = this.getTextGuideLine();
  54996. var labelText = polygon.getTextContent();
  54997. var seriesModel = data.hostModel;
  54998. var itemModel = data.getItemModel(idx);
  54999. var layout = data.getItemLayout(idx);
  55000. var labelLayout = layout.label;
  55001. var style = data.getItemVisual(idx, 'style');
  55002. var visualColor = style.fill;
  55003. setLabelStyle( // position will not be used in setLabelStyle
  55004. labelText, getLabelStatesModels(itemModel), {
  55005. labelFetcher: data.hostModel,
  55006. labelDataIndex: idx,
  55007. defaultOpacity: style.opacity,
  55008. defaultText: data.getName(idx)
  55009. }, {
  55010. normal: {
  55011. align: labelLayout.textAlign,
  55012. verticalAlign: labelLayout.verticalAlign
  55013. }
  55014. });
  55015. polygon.setTextConfig({
  55016. local: true,
  55017. inside: !!labelLayout.inside,
  55018. insideStroke: visualColor,
  55019. // insideFill: 'auto',
  55020. outsideFill: visualColor
  55021. });
  55022. var linePoints = labelLayout.linePoints;
  55023. labelLine.setShape({
  55024. points: linePoints
  55025. });
  55026. polygon.textGuideLineConfig = {
  55027. anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null
  55028. }; // Make sure update style on labelText after setLabelStyle.
  55029. // Because setLabelStyle will replace a new style on it.
  55030. updateProps(labelText, {
  55031. style: {
  55032. x: labelLayout.x,
  55033. y: labelLayout.y
  55034. }
  55035. }, seriesModel, idx);
  55036. labelText.attr({
  55037. rotation: labelLayout.rotation,
  55038. originX: labelLayout.x,
  55039. originY: labelLayout.y,
  55040. z2: 10
  55041. });
  55042. setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), {
  55043. // Default use item visual color
  55044. stroke: visualColor
  55045. });
  55046. };
  55047. return FunnelPiece;
  55048. }(Polygon);
  55049. var FunnelView =
  55050. /** @class */
  55051. function (_super) {
  55052. __extends(FunnelView, _super);
  55053. function FunnelView() {
  55054. var _this = _super !== null && _super.apply(this, arguments) || this;
  55055. _this.type = FunnelView.type;
  55056. _this.ignoreLabelLineUpdate = true;
  55057. return _this;
  55058. }
  55059. FunnelView.prototype.render = function (seriesModel, ecModel, api) {
  55060. var data = seriesModel.getData();
  55061. var oldData = this._data;
  55062. var group = this.group;
  55063. data.diff(oldData).add(function (idx) {
  55064. var funnelPiece = new FunnelPiece(data, idx);
  55065. data.setItemGraphicEl(idx, funnelPiece);
  55066. group.add(funnelPiece);
  55067. }).update(function (newIdx, oldIdx) {
  55068. var piece = oldData.getItemGraphicEl(oldIdx);
  55069. piece.updateData(data, newIdx);
  55070. group.add(piece);
  55071. data.setItemGraphicEl(newIdx, piece);
  55072. }).remove(function (idx) {
  55073. var piece = oldData.getItemGraphicEl(idx);
  55074. removeElementWithFadeOut(piece, seriesModel, idx);
  55075. }).execute();
  55076. this._data = data;
  55077. };
  55078. FunnelView.prototype.remove = function () {
  55079. this.group.removeAll();
  55080. this._data = null;
  55081. };
  55082. FunnelView.prototype.dispose = function () {};
  55083. FunnelView.type = 'funnel';
  55084. return FunnelView;
  55085. }(ChartView);
  55086. var FunnelSeriesModel =
  55087. /** @class */
  55088. function (_super) {
  55089. __extends(FunnelSeriesModel, _super);
  55090. function FunnelSeriesModel() {
  55091. var _this = _super !== null && _super.apply(this, arguments) || this;
  55092. _this.type = FunnelSeriesModel.type;
  55093. return _this;
  55094. }
  55095. FunnelSeriesModel.prototype.init = function (option) {
  55096. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  55097. // Use a function instead of direct access because data reference may changed
  55098. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  55099. this._defaultLabelLine(option);
  55100. };
  55101. FunnelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55102. return createSeriesDataSimply(this, {
  55103. coordDimensions: ['value'],
  55104. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  55105. });
  55106. };
  55107. FunnelSeriesModel.prototype._defaultLabelLine = function (option) {
  55108. // Extend labelLine emphasis
  55109. defaultEmphasis(option, 'labelLine', ['show']);
  55110. var labelLineNormalOpt = option.labelLine;
  55111. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  55112. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  55113. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  55114. }; // Overwrite
  55115. FunnelSeriesModel.prototype.getDataParams = function (dataIndex) {
  55116. var data = this.getData();
  55117. var params = _super.prototype.getDataParams.call(this, dataIndex);
  55118. var valueDim = data.mapDimension('value');
  55119. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  55120. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  55121. params.$vars.push('percent');
  55122. return params;
  55123. };
  55124. FunnelSeriesModel.type = 'series.funnel';
  55125. FunnelSeriesModel.defaultOption = {
  55126. // zlevel: 0, // 一级层叠
  55127. z: 2,
  55128. legendHoverLink: true,
  55129. colorBy: 'data',
  55130. left: 80,
  55131. top: 60,
  55132. right: 80,
  55133. bottom: 60,
  55134. // width: {totalWidth} - left - right,
  55135. // height: {totalHeight} - top - bottom,
  55136. // 默认取数据最小最大值
  55137. // min: 0,
  55138. // max: 100,
  55139. minSize: '0%',
  55140. maxSize: '100%',
  55141. sort: 'descending',
  55142. orient: 'vertical',
  55143. gap: 0,
  55144. funnelAlign: 'center',
  55145. label: {
  55146. show: true,
  55147. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  55148. },
  55149. labelLine: {
  55150. show: true,
  55151. length: 20,
  55152. lineStyle: {
  55153. // color: 各异,
  55154. width: 1
  55155. }
  55156. },
  55157. itemStyle: {
  55158. // color: 各异,
  55159. borderColor: '#fff',
  55160. borderWidth: 1
  55161. },
  55162. emphasis: {
  55163. label: {
  55164. show: true
  55165. }
  55166. },
  55167. select: {
  55168. itemStyle: {
  55169. borderColor: '#212121'
  55170. }
  55171. }
  55172. };
  55173. return FunnelSeriesModel;
  55174. }(SeriesModel);
  55175. function getViewRect$3(seriesModel, api) {
  55176. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  55177. width: api.getWidth(),
  55178. height: api.getHeight()
  55179. });
  55180. }
  55181. function getSortedIndices(data, sort) {
  55182. var valueDim = data.mapDimension('value');
  55183. var valueArr = data.mapArray(valueDim, function (val) {
  55184. return val;
  55185. });
  55186. var indices = [];
  55187. var isAscending = sort === 'ascending';
  55188. for (var i = 0, len = data.count(); i < len; i++) {
  55189. indices[i] = i;
  55190. } // Add custom sortable function & none sortable opetion by "options.sort"
  55191. if (isFunction(sort)) {
  55192. indices.sort(sort);
  55193. } else if (sort !== 'none') {
  55194. indices.sort(function (a, b) {
  55195. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  55196. });
  55197. }
  55198. return indices;
  55199. }
  55200. function labelLayout(data) {
  55201. var seriesModel = data.hostModel;
  55202. var orient = seriesModel.get('orient');
  55203. data.each(function (idx) {
  55204. var itemModel = data.getItemModel(idx);
  55205. var labelModel = itemModel.getModel('label');
  55206. var labelPosition = labelModel.get('position');
  55207. var labelLineModel = itemModel.getModel('labelLine');
  55208. var layout = data.getItemLayout(idx);
  55209. var points = layout.points;
  55210. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  55211. var textAlign;
  55212. var textX;
  55213. var textY;
  55214. var linePoints;
  55215. if (isLabelInside) {
  55216. if (labelPosition === 'insideLeft') {
  55217. textX = (points[0][0] + points[3][0]) / 2 + 5;
  55218. textY = (points[0][1] + points[3][1]) / 2;
  55219. textAlign = 'left';
  55220. } else if (labelPosition === 'insideRight') {
  55221. textX = (points[1][0] + points[2][0]) / 2 - 5;
  55222. textY = (points[1][1] + points[2][1]) / 2;
  55223. textAlign = 'right';
  55224. } else {
  55225. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  55226. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  55227. textAlign = 'center';
  55228. }
  55229. linePoints = [[textX, textY], [textX, textY]];
  55230. } else {
  55231. var x1 = void 0;
  55232. var y1 = void 0;
  55233. var x2 = void 0;
  55234. var y2 = void 0;
  55235. var labelLineLen = labelLineModel.get('length');
  55236. if ("development" !== 'production') {
  55237. if (orient === 'vertical' && ['top', 'bottom'].indexOf(labelPosition) > -1) {
  55238. labelPosition = 'left';
  55239. console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.');
  55240. }
  55241. if (orient === 'horizontal' && ['left', 'right'].indexOf(labelPosition) > -1) {
  55242. labelPosition = 'bottom';
  55243. console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.');
  55244. }
  55245. }
  55246. if (labelPosition === 'left') {
  55247. // Left side
  55248. x1 = (points[3][0] + points[0][0]) / 2;
  55249. y1 = (points[3][1] + points[0][1]) / 2;
  55250. x2 = x1 - labelLineLen;
  55251. textX = x2 - 5;
  55252. textAlign = 'right';
  55253. } else if (labelPosition === 'right') {
  55254. // Right side
  55255. x1 = (points[1][0] + points[2][0]) / 2;
  55256. y1 = (points[1][1] + points[2][1]) / 2;
  55257. x2 = x1 + labelLineLen;
  55258. textX = x2 + 5;
  55259. textAlign = 'left';
  55260. } else if (labelPosition === 'top') {
  55261. // Top side
  55262. x1 = (points[3][0] + points[0][0]) / 2;
  55263. y1 = (points[3][1] + points[0][1]) / 2;
  55264. y2 = y1 - labelLineLen;
  55265. textY = y2 - 5;
  55266. textAlign = 'center';
  55267. } else if (labelPosition === 'bottom') {
  55268. // Bottom side
  55269. x1 = (points[1][0] + points[2][0]) / 2;
  55270. y1 = (points[1][1] + points[2][1]) / 2;
  55271. y2 = y1 + labelLineLen;
  55272. textY = y2 + 5;
  55273. textAlign = 'center';
  55274. } else if (labelPosition === 'rightTop') {
  55275. // RightTop side
  55276. x1 = orient === 'horizontal' ? points[3][0] : points[1][0];
  55277. y1 = orient === 'horizontal' ? points[3][1] : points[1][1];
  55278. if (orient === 'horizontal') {
  55279. y2 = y1 - labelLineLen;
  55280. textY = y2 - 5;
  55281. textAlign = 'center';
  55282. } else {
  55283. x2 = x1 + labelLineLen;
  55284. textX = x2 + 5;
  55285. textAlign = 'top';
  55286. }
  55287. } else if (labelPosition === 'rightBottom') {
  55288. // RightBottom side
  55289. x1 = points[2][0];
  55290. y1 = points[2][1];
  55291. if (orient === 'horizontal') {
  55292. y2 = y1 + labelLineLen;
  55293. textY = y2 + 5;
  55294. textAlign = 'center';
  55295. } else {
  55296. x2 = x1 + labelLineLen;
  55297. textX = x2 + 5;
  55298. textAlign = 'bottom';
  55299. }
  55300. } else if (labelPosition === 'leftTop') {
  55301. // LeftTop side
  55302. x1 = points[0][0];
  55303. y1 = orient === 'horizontal' ? points[0][1] : points[1][1];
  55304. if (orient === 'horizontal') {
  55305. y2 = y1 - labelLineLen;
  55306. textY = y2 - 5;
  55307. textAlign = 'center';
  55308. } else {
  55309. x2 = x1 - labelLineLen;
  55310. textX = x2 - 5;
  55311. textAlign = 'right';
  55312. }
  55313. } else if (labelPosition === 'leftBottom') {
  55314. // LeftBottom side
  55315. x1 = orient === 'horizontal' ? points[1][0] : points[3][0];
  55316. y1 = orient === 'horizontal' ? points[1][1] : points[2][1];
  55317. if (orient === 'horizontal') {
  55318. y2 = y1 + labelLineLen;
  55319. textY = y2 + 5;
  55320. textAlign = 'center';
  55321. } else {
  55322. x2 = x1 - labelLineLen;
  55323. textX = x2 - 5;
  55324. textAlign = 'right';
  55325. }
  55326. } else {
  55327. // Right side or Bottom side
  55328. x1 = (points[1][0] + points[2][0]) / 2;
  55329. y1 = (points[1][1] + points[2][1]) / 2;
  55330. if (orient === 'horizontal') {
  55331. y2 = y1 + labelLineLen;
  55332. textY = y2 + 5;
  55333. textAlign = 'center';
  55334. } else {
  55335. x2 = x1 + labelLineLen;
  55336. textX = x2 + 5;
  55337. textAlign = 'left';
  55338. }
  55339. }
  55340. if (orient === 'horizontal') {
  55341. x2 = x1;
  55342. textX = x2;
  55343. } else {
  55344. y2 = y1;
  55345. textY = y2;
  55346. }
  55347. linePoints = [[x1, y1], [x2, y2]];
  55348. }
  55349. layout.label = {
  55350. linePoints: linePoints,
  55351. x: textX,
  55352. y: textY,
  55353. verticalAlign: 'middle',
  55354. textAlign: textAlign,
  55355. inside: isLabelInside
  55356. };
  55357. });
  55358. }
  55359. function funnelLayout(ecModel, api) {
  55360. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  55361. var data = seriesModel.getData();
  55362. var valueDim = data.mapDimension('value');
  55363. var sort = seriesModel.get('sort');
  55364. var viewRect = getViewRect$3(seriesModel, api);
  55365. var orient = seriesModel.get('orient');
  55366. var viewWidth = viewRect.width;
  55367. var viewHeight = viewRect.height;
  55368. var indices = getSortedIndices(data, sort);
  55369. var x = viewRect.x;
  55370. var y = viewRect.y;
  55371. 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)];
  55372. var dataExtent = data.getDataExtent(valueDim);
  55373. var min = seriesModel.get('min');
  55374. var max = seriesModel.get('max');
  55375. if (min == null) {
  55376. min = Math.min(dataExtent[0], 0);
  55377. }
  55378. if (max == null) {
  55379. max = dataExtent[1];
  55380. }
  55381. var funnelAlign = seriesModel.get('funnelAlign');
  55382. var gap = seriesModel.get('gap');
  55383. var viewSize = orient === 'horizontal' ? viewWidth : viewHeight;
  55384. var itemSize = (viewSize - gap * (data.count() - 1)) / data.count();
  55385. var getLinePoints = function (idx, offset) {
  55386. // End point index is data.count() and we assign it 0
  55387. if (orient === 'horizontal') {
  55388. var val_1 = data.get(valueDim, idx) || 0;
  55389. var itemHeight = linearMap(val_1, [min, max], sizeExtent, true);
  55390. var y0 = void 0;
  55391. switch (funnelAlign) {
  55392. case 'top':
  55393. y0 = y;
  55394. break;
  55395. case 'center':
  55396. y0 = y + (viewHeight - itemHeight) / 2;
  55397. break;
  55398. case 'bottom':
  55399. y0 = y + (viewHeight - itemHeight);
  55400. break;
  55401. }
  55402. return [[offset, y0], [offset, y0 + itemHeight]];
  55403. }
  55404. var val = data.get(valueDim, idx) || 0;
  55405. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  55406. var x0;
  55407. switch (funnelAlign) {
  55408. case 'left':
  55409. x0 = x;
  55410. break;
  55411. case 'center':
  55412. x0 = x + (viewWidth - itemWidth) / 2;
  55413. break;
  55414. case 'right':
  55415. x0 = x + viewWidth - itemWidth;
  55416. break;
  55417. }
  55418. return [[x0, offset], [x0 + itemWidth, offset]];
  55419. };
  55420. if (sort === 'ascending') {
  55421. // From bottom to top
  55422. itemSize = -itemSize;
  55423. gap = -gap;
  55424. if (orient === 'horizontal') {
  55425. x += viewWidth;
  55426. } else {
  55427. y += viewHeight;
  55428. }
  55429. indices = indices.reverse();
  55430. }
  55431. for (var i = 0; i < indices.length; i++) {
  55432. var idx = indices[i];
  55433. var nextIdx = indices[i + 1];
  55434. var itemModel = data.getItemModel(idx);
  55435. if (orient === 'horizontal') {
  55436. var width = itemModel.get(['itemStyle', 'width']);
  55437. if (width == null) {
  55438. width = itemSize;
  55439. } else {
  55440. width = parsePercent$1(width, viewWidth);
  55441. if (sort === 'ascending') {
  55442. width = -width;
  55443. }
  55444. }
  55445. var start = getLinePoints(idx, x);
  55446. var end = getLinePoints(nextIdx, x + width);
  55447. x += width + gap;
  55448. data.setItemLayout(idx, {
  55449. points: start.concat(end.slice().reverse())
  55450. });
  55451. } else {
  55452. var height = itemModel.get(['itemStyle', 'height']);
  55453. if (height == null) {
  55454. height = itemSize;
  55455. } else {
  55456. height = parsePercent$1(height, viewHeight);
  55457. if (sort === 'ascending') {
  55458. height = -height;
  55459. }
  55460. }
  55461. var start = getLinePoints(idx, y);
  55462. var end = getLinePoints(nextIdx, y + height);
  55463. y += height + gap;
  55464. data.setItemLayout(idx, {
  55465. points: start.concat(end.slice().reverse())
  55466. });
  55467. }
  55468. }
  55469. labelLayout(data);
  55470. });
  55471. }
  55472. function install$f(registers) {
  55473. registers.registerChartView(FunnelView);
  55474. registers.registerSeriesModel(FunnelSeriesModel);
  55475. registers.registerLayout(funnelLayout);
  55476. registers.registerProcessor(dataFilter('funnel'));
  55477. }
  55478. var DEFAULT_SMOOTH = 0.3;
  55479. var ParallelView =
  55480. /** @class */
  55481. function (_super) {
  55482. __extends(ParallelView, _super);
  55483. function ParallelView() {
  55484. var _this = _super !== null && _super.apply(this, arguments) || this;
  55485. _this.type = ParallelView.type;
  55486. _this._dataGroup = new Group();
  55487. _this._initialized = false;
  55488. return _this;
  55489. }
  55490. ParallelView.prototype.init = function () {
  55491. this.group.add(this._dataGroup);
  55492. };
  55493. /**
  55494. * @override
  55495. */
  55496. ParallelView.prototype.render = function (seriesModel, ecModel, api, payload) {
  55497. // Clear previously rendered progressive elements.
  55498. this._progressiveEls = null;
  55499. var dataGroup = this._dataGroup;
  55500. var data = seriesModel.getData();
  55501. var oldData = this._data;
  55502. var coordSys = seriesModel.coordinateSystem;
  55503. var dimensions = coordSys.dimensions;
  55504. var seriesScope = makeSeriesScope$2(seriesModel);
  55505. data.diff(oldData).add(add).update(update).remove(remove).execute();
  55506. function add(newDataIndex) {
  55507. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  55508. updateElCommon(line, data, newDataIndex, seriesScope);
  55509. }
  55510. function update(newDataIndex, oldDataIndex) {
  55511. var line = oldData.getItemGraphicEl(oldDataIndex);
  55512. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  55513. data.setItemGraphicEl(newDataIndex, line);
  55514. updateProps(line, {
  55515. shape: {
  55516. points: points
  55517. }
  55518. }, seriesModel, newDataIndex);
  55519. saveOldStyle(line);
  55520. updateElCommon(line, data, newDataIndex, seriesScope);
  55521. }
  55522. function remove(oldDataIndex) {
  55523. var line = oldData.getItemGraphicEl(oldDataIndex);
  55524. dataGroup.remove(line);
  55525. } // First create
  55526. if (!this._initialized) {
  55527. this._initialized = true;
  55528. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  55529. // Callback will be invoked immediately if there is no animation
  55530. setTimeout(function () {
  55531. dataGroup.removeClipPath();
  55532. });
  55533. });
  55534. dataGroup.setClipPath(clipPath);
  55535. }
  55536. this._data = data;
  55537. };
  55538. ParallelView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  55539. this._initialized = true;
  55540. this._data = null;
  55541. this._dataGroup.removeAll();
  55542. };
  55543. ParallelView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  55544. var data = seriesModel.getData();
  55545. var coordSys = seriesModel.coordinateSystem;
  55546. var dimensions = coordSys.dimensions;
  55547. var seriesScope = makeSeriesScope$2(seriesModel);
  55548. var progressiveEls = this._progressiveEls = [];
  55549. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  55550. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  55551. line.incremental = true;
  55552. updateElCommon(line, data, dataIndex, seriesScope);
  55553. progressiveEls.push(line);
  55554. }
  55555. };
  55556. ParallelView.prototype.remove = function () {
  55557. this._dataGroup && this._dataGroup.removeAll();
  55558. this._data = null;
  55559. };
  55560. ParallelView.type = 'parallel';
  55561. return ParallelView;
  55562. }(ChartView);
  55563. function createGridClipShape(coordSys, seriesModel, cb) {
  55564. var parallelModel = coordSys.model;
  55565. var rect = coordSys.getRect();
  55566. var rectEl = new Rect({
  55567. shape: {
  55568. x: rect.x,
  55569. y: rect.y,
  55570. width: rect.width,
  55571. height: rect.height
  55572. }
  55573. });
  55574. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  55575. rectEl.setShape(dim, 0);
  55576. initProps(rectEl, {
  55577. shape: {
  55578. width: rect.width,
  55579. height: rect.height
  55580. }
  55581. }, seriesModel, cb);
  55582. return rectEl;
  55583. }
  55584. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  55585. var points = [];
  55586. for (var i = 0; i < dimensions.length; i++) {
  55587. var dimName = dimensions[i];
  55588. var value = data.get(data.mapDimension(dimName), dataIndex);
  55589. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  55590. points.push(coordSys.dataToPoint(value, dimName));
  55591. }
  55592. }
  55593. return points;
  55594. }
  55595. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  55596. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  55597. var line = new Polyline({
  55598. shape: {
  55599. points: points
  55600. },
  55601. // silent: true,
  55602. z2: 10
  55603. });
  55604. dataGroup.add(line);
  55605. data.setItemGraphicEl(dataIndex, line);
  55606. return line;
  55607. }
  55608. function makeSeriesScope$2(seriesModel) {
  55609. var smooth = seriesModel.get('smooth', true);
  55610. smooth === true && (smooth = DEFAULT_SMOOTH);
  55611. smooth = numericToNumber(smooth);
  55612. eqNaN(smooth) && (smooth = 0);
  55613. return {
  55614. smooth: smooth
  55615. };
  55616. }
  55617. function updateElCommon(el, data, dataIndex, seriesScope) {
  55618. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  55619. el.style.fill = null;
  55620. el.setShape('smooth', seriesScope.smooth);
  55621. var itemModel = data.getItemModel(dataIndex);
  55622. var emphasisModel = itemModel.getModel('emphasis');
  55623. setStatesStylesFromModel(el, itemModel, 'lineStyle');
  55624. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  55625. } // function simpleDiff(oldData, newData, dimensions) {
  55626. // let oldLen;
  55627. // if (!oldData
  55628. // || !oldData.__plProgressive
  55629. // || (oldLen = oldData.count()) !== newData.count()
  55630. // ) {
  55631. // return true;
  55632. // }
  55633. // let dimLen = dimensions.length;
  55634. // for (let i = 0; i < oldLen; i++) {
  55635. // for (let j = 0; j < dimLen; j++) {
  55636. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  55637. // return true;
  55638. // }
  55639. // }
  55640. // }
  55641. // return false;
  55642. // }
  55643. // FIXME put in common util?
  55644. function isEmptyValue(val, axisType) {
  55645. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  55646. }
  55647. var ParallelSeriesModel =
  55648. /** @class */
  55649. function (_super) {
  55650. __extends(ParallelSeriesModel, _super);
  55651. function ParallelSeriesModel() {
  55652. var _this = _super !== null && _super.apply(this, arguments) || this;
  55653. _this.type = ParallelSeriesModel.type;
  55654. _this.visualStyleAccessPath = 'lineStyle';
  55655. _this.visualDrawType = 'stroke';
  55656. return _this;
  55657. }
  55658. ParallelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  55659. return createSeriesData(null, this, {
  55660. useEncodeDefaulter: bind(makeDefaultEncode, null, this)
  55661. });
  55662. };
  55663. /**
  55664. * User can get data raw indices on 'axisAreaSelected' event received.
  55665. *
  55666. * @return Raw indices
  55667. */
  55668. ParallelSeriesModel.prototype.getRawIndicesByActiveState = function (activeState) {
  55669. var coordSys = this.coordinateSystem;
  55670. var data = this.getData();
  55671. var indices = [];
  55672. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  55673. if (activeState === theActiveState) {
  55674. indices.push(data.getRawIndex(dataIndex));
  55675. }
  55676. });
  55677. return indices;
  55678. };
  55679. ParallelSeriesModel.type = 'series.parallel';
  55680. ParallelSeriesModel.dependencies = ['parallel'];
  55681. ParallelSeriesModel.defaultOption = {
  55682. // zlevel: 0,
  55683. z: 2,
  55684. coordinateSystem: 'parallel',
  55685. parallelIndex: 0,
  55686. label: {
  55687. show: false
  55688. },
  55689. inactiveOpacity: 0.05,
  55690. activeOpacity: 1,
  55691. lineStyle: {
  55692. width: 1,
  55693. opacity: 0.45,
  55694. type: 'solid'
  55695. },
  55696. emphasis: {
  55697. label: {
  55698. show: false
  55699. }
  55700. },
  55701. progressive: 500,
  55702. smooth: false,
  55703. animationEasing: 'linear'
  55704. };
  55705. return ParallelSeriesModel;
  55706. }(SeriesModel);
  55707. function makeDefaultEncode(seriesModel) {
  55708. // The mapping of parallelAxis dimension to data dimension can
  55709. // be specified in parallelAxis.option.dim. For example, if
  55710. // parallelAxis.option.dim is 'dim3', it mapping to the third
  55711. // dimension of data. But `data.encode` has higher priority.
  55712. // Moreover, parallelModel.dimension should not be regarded as data
  55713. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  55714. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  55715. if (!parallelModel) {
  55716. return;
  55717. }
  55718. var encodeDefine = {};
  55719. each(parallelModel.dimensions, function (axisDim) {
  55720. var dataDimIndex = convertDimNameToNumber(axisDim);
  55721. encodeDefine[axisDim] = dataDimIndex;
  55722. });
  55723. return encodeDefine;
  55724. }
  55725. function convertDimNameToNumber(dimName) {
  55726. return +dimName.replace('dim', '');
  55727. }
  55728. /*
  55729. * Licensed to the Apache Software Foundation (ASF) under one
  55730. * or more contributor license agreements. See the NOTICE file
  55731. * distributed with this work for additional information
  55732. * regarding copyright ownership. The ASF licenses this file
  55733. * to you under the Apache License, Version 2.0 (the
  55734. * "License"); you may not use this file except in compliance
  55735. * with the License. You may obtain a copy of the License at
  55736. *
  55737. * http://www.apache.org/licenses/LICENSE-2.0
  55738. *
  55739. * Unless required by applicable law or agreed to in writing,
  55740. * software distributed under the License is distributed on an
  55741. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55742. * KIND, either express or implied. See the License for the
  55743. * specific language governing permissions and limitations
  55744. * under the License.
  55745. */
  55746. /**
  55747. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55748. */
  55749. /*
  55750. * Licensed to the Apache Software Foundation (ASF) under one
  55751. * or more contributor license agreements. See the NOTICE file
  55752. * distributed with this work for additional information
  55753. * regarding copyright ownership. The ASF licenses this file
  55754. * to you under the Apache License, Version 2.0 (the
  55755. * "License"); you may not use this file except in compliance
  55756. * with the License. You may obtain a copy of the License at
  55757. *
  55758. * http://www.apache.org/licenses/LICENSE-2.0
  55759. *
  55760. * Unless required by applicable law or agreed to in writing,
  55761. * software distributed under the License is distributed on an
  55762. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55763. * KIND, either express or implied. See the License for the
  55764. * specific language governing permissions and limitations
  55765. * under the License.
  55766. */
  55767. var opacityAccessPath$1 = ['lineStyle', 'opacity'];
  55768. var parallelVisual = {
  55769. seriesType: 'parallel',
  55770. reset: function (seriesModel, ecModel) {
  55771. var coordSys = seriesModel.coordinateSystem;
  55772. var opacityMap = {
  55773. normal: seriesModel.get(['lineStyle', 'opacity']),
  55774. active: seriesModel.get('activeOpacity'),
  55775. inactive: seriesModel.get('inactiveOpacity')
  55776. };
  55777. return {
  55778. progress: function (params, data) {
  55779. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  55780. var opacity = opacityMap[activeState];
  55781. if (activeState === 'normal' && data.hasItemOption) {
  55782. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  55783. itemOpacity != null && (opacity = itemOpacity);
  55784. }
  55785. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  55786. existsStyle.opacity = opacity;
  55787. }, params.start, params.end);
  55788. }
  55789. };
  55790. }
  55791. };
  55792. function parallelPreprocessor(option) {
  55793. createParallelIfNeeded(option);
  55794. mergeAxisOptionFromParallel(option);
  55795. }
  55796. /**
  55797. * Create a parallel coordinate if not exists.
  55798. * @inner
  55799. */
  55800. function createParallelIfNeeded(option) {
  55801. if (option.parallel) {
  55802. return;
  55803. }
  55804. var hasParallelSeries = false;
  55805. each(option.series, function (seriesOpt) {
  55806. if (seriesOpt && seriesOpt.type === 'parallel') {
  55807. hasParallelSeries = true;
  55808. }
  55809. });
  55810. if (hasParallelSeries) {
  55811. option.parallel = [{}];
  55812. }
  55813. }
  55814. /**
  55815. * Merge aixs definition from parallel option (if exists) to axis option.
  55816. * @inner
  55817. */
  55818. function mergeAxisOptionFromParallel(option) {
  55819. var axes = normalizeToArray(option.parallelAxis);
  55820. each(axes, function (axisOption) {
  55821. if (!isObject(axisOption)) {
  55822. return;
  55823. }
  55824. var parallelIndex = axisOption.parallelIndex || 0;
  55825. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  55826. if (parallelOption && parallelOption.parallelAxisDefault) {
  55827. merge(axisOption, parallelOption.parallelAxisDefault, false);
  55828. }
  55829. });
  55830. }
  55831. var CLICK_THRESHOLD = 5; // > 4
  55832. var ParallelView$1 =
  55833. /** @class */
  55834. function (_super) {
  55835. __extends(ParallelView, _super);
  55836. function ParallelView() {
  55837. var _this = _super !== null && _super.apply(this, arguments) || this;
  55838. _this.type = ParallelView.type;
  55839. return _this;
  55840. }
  55841. ParallelView.prototype.render = function (parallelModel, ecModel, api) {
  55842. this._model = parallelModel;
  55843. this._api = api;
  55844. if (!this._handlers) {
  55845. this._handlers = {};
  55846. each(handlers, function (handler, eventName) {
  55847. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  55848. }, this);
  55849. }
  55850. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  55851. };
  55852. ParallelView.prototype.dispose = function (ecModel, api) {
  55853. clear(this, '_throttledDispatchExpand');
  55854. each(this._handlers, function (handler, eventName) {
  55855. api.getZr().off(eventName, handler);
  55856. });
  55857. this._handlers = null;
  55858. };
  55859. /**
  55860. * @internal
  55861. * @param {Object} [opt] If null, cancel the last action triggering for debounce.
  55862. */
  55863. ParallelView.prototype._throttledDispatchExpand = function (opt) {
  55864. this._dispatchExpand(opt);
  55865. };
  55866. /**
  55867. * @internal
  55868. */
  55869. ParallelView.prototype._dispatchExpand = function (opt) {
  55870. opt && this._api.dispatchAction(extend({
  55871. type: 'parallelAxisExpand'
  55872. }, opt));
  55873. };
  55874. ParallelView.type = 'parallel';
  55875. return ParallelView;
  55876. }(ComponentView);
  55877. var handlers = {
  55878. mousedown: function (e) {
  55879. if (checkTrigger(this, 'click')) {
  55880. this._mouseDownPoint = [e.offsetX, e.offsetY];
  55881. }
  55882. },
  55883. mouseup: function (e) {
  55884. var mouseDownPoint = this._mouseDownPoint;
  55885. if (checkTrigger(this, 'click') && mouseDownPoint) {
  55886. var point = [e.offsetX, e.offsetY];
  55887. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  55888. if (dist > CLICK_THRESHOLD) {
  55889. return;
  55890. }
  55891. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55892. result.behavior !== 'none' && this._dispatchExpand({
  55893. axisExpandWindow: result.axisExpandWindow
  55894. });
  55895. }
  55896. this._mouseDownPoint = null;
  55897. },
  55898. mousemove: function (e) {
  55899. // Should do nothing when brushing.
  55900. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  55901. return;
  55902. }
  55903. var model = this._model;
  55904. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  55905. var behavior = result.behavior;
  55906. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  55907. this._throttledDispatchExpand(behavior === 'none' ? null // Cancel the last trigger, in case that mouse slide out of the area quickly.
  55908. : {
  55909. axisExpandWindow: result.axisExpandWindow,
  55910. // Jumping uses animation, and sliding suppresses animation.
  55911. animation: behavior === 'jump' ? null : {
  55912. duration: 0 // Disable animation.
  55913. }
  55914. });
  55915. }
  55916. };
  55917. function checkTrigger(view, triggerOn) {
  55918. var model = view._model;
  55919. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  55920. }
  55921. var ParallelModel =
  55922. /** @class */
  55923. function (_super) {
  55924. __extends(ParallelModel, _super);
  55925. function ParallelModel() {
  55926. var _this = _super !== null && _super.apply(this, arguments) || this;
  55927. _this.type = ParallelModel.type;
  55928. return _this;
  55929. }
  55930. ParallelModel.prototype.init = function () {
  55931. _super.prototype.init.apply(this, arguments);
  55932. this.mergeOption({});
  55933. };
  55934. ParallelModel.prototype.mergeOption = function (newOption) {
  55935. var thisOption = this.option;
  55936. newOption && merge(thisOption, newOption, true);
  55937. this._initDimensions();
  55938. };
  55939. /**
  55940. * Whether series or axis is in this coordinate system.
  55941. */
  55942. ParallelModel.prototype.contains = function (model, ecModel) {
  55943. var parallelIndex = model.get('parallelIndex');
  55944. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  55945. };
  55946. ParallelModel.prototype.setAxisExpand = function (opt) {
  55947. each(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  55948. if (opt.hasOwnProperty(name)) {
  55949. // @ts-ignore FIXME: why "never" inferred in this.option[name]?
  55950. this.option[name] = opt[name];
  55951. }
  55952. }, this);
  55953. };
  55954. ParallelModel.prototype._initDimensions = function () {
  55955. var dimensions = this.dimensions = [];
  55956. var parallelAxisIndex = this.parallelAxisIndex = [];
  55957. var axisModels = filter(this.ecModel.queryComponents({
  55958. mainType: 'parallelAxis'
  55959. }), function (axisModel) {
  55960. // Can not use this.contains here, because
  55961. // initialization has not been completed yet.
  55962. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  55963. }, this);
  55964. each(axisModels, function (axisModel) {
  55965. dimensions.push('dim' + axisModel.get('dim'));
  55966. parallelAxisIndex.push(axisModel.componentIndex);
  55967. });
  55968. };
  55969. ParallelModel.type = 'parallel';
  55970. ParallelModel.dependencies = ['parallelAxis'];
  55971. ParallelModel.layoutMode = 'box';
  55972. ParallelModel.defaultOption = {
  55973. // zlevel: 0,
  55974. z: 0,
  55975. left: 80,
  55976. top: 60,
  55977. right: 80,
  55978. bottom: 60,
  55979. // width: {totalWidth} - left - right,
  55980. // height: {totalHeight} - top - bottom,
  55981. layout: 'horizontal',
  55982. // FIXME
  55983. // naming?
  55984. axisExpandable: false,
  55985. axisExpandCenter: null,
  55986. axisExpandCount: 0,
  55987. axisExpandWidth: 50,
  55988. axisExpandRate: 17,
  55989. axisExpandDebounce: 50,
  55990. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  55991. // Do not doc to user until necessary.
  55992. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  55993. axisExpandTriggerOn: 'click',
  55994. parallelAxisDefault: null
  55995. };
  55996. return ParallelModel;
  55997. }(ComponentModel);
  55998. var ParallelAxis =
  55999. /** @class */
  56000. function (_super) {
  56001. __extends(ParallelAxis, _super);
  56002. function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) {
  56003. var _this = _super.call(this, dim, scale, coordExtent) || this;
  56004. _this.type = axisType || 'value';
  56005. _this.axisIndex = axisIndex;
  56006. return _this;
  56007. }
  56008. ParallelAxis.prototype.isHorizontal = function () {
  56009. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  56010. };
  56011. return ParallelAxis;
  56012. }(Axis);
  56013. /*
  56014. * Licensed to the Apache Software Foundation (ASF) under one
  56015. * or more contributor license agreements. See the NOTICE file
  56016. * distributed with this work for additional information
  56017. * regarding copyright ownership. The ASF licenses this file
  56018. * to you under the Apache License, Version 2.0 (the
  56019. * "License"); you may not use this file except in compliance
  56020. * with the License. You may obtain a copy of the License at
  56021. *
  56022. * http://www.apache.org/licenses/LICENSE-2.0
  56023. *
  56024. * Unless required by applicable law or agreed to in writing,
  56025. * software distributed under the License is distributed on an
  56026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56027. * KIND, either express or implied. See the License for the
  56028. * specific language governing permissions and limitations
  56029. * under the License.
  56030. */
  56031. /**
  56032. * AUTO-GENERATED FILE. DO NOT MODIFY.
  56033. */
  56034. /*
  56035. * Licensed to the Apache Software Foundation (ASF) under one
  56036. * or more contributor license agreements. See the NOTICE file
  56037. * distributed with this work for additional information
  56038. * regarding copyright ownership. The ASF licenses this file
  56039. * to you under the Apache License, Version 2.0 (the
  56040. * "License"); you may not use this file except in compliance
  56041. * with the License. You may obtain a copy of the License at
  56042. *
  56043. * http://www.apache.org/licenses/LICENSE-2.0
  56044. *
  56045. * Unless required by applicable law or agreed to in writing,
  56046. * software distributed under the License is distributed on an
  56047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56048. * KIND, either express or implied. See the License for the
  56049. * specific language governing permissions and limitations
  56050. * under the License.
  56051. */
  56052. /**
  56053. * Calculate slider move result.
  56054. * Usage:
  56055. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  56056. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  56057. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  56058. *
  56059. * @param delta Move length.
  56060. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  56061. * handleEnds will be modified in this method.
  56062. * @param extent handleEnds is restricted by extent.
  56063. * extent[0] should less or equals than extent[1].
  56064. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  56065. * @param minSpan The range of dataZoom can not be smaller than that.
  56066. * If not set, handle0 and cross handle1. If set as a non-negative
  56067. * number (including `0`), handles will push each other when reaching
  56068. * the minSpan.
  56069. * @param maxSpan The range of dataZoom can not be larger than that.
  56070. * @return The input handleEnds.
  56071. */
  56072. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  56073. delta = delta || 0;
  56074. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  56075. if (minSpan != null) {
  56076. minSpan = restrict(minSpan, [0, extentSpan]);
  56077. }
  56078. if (maxSpan != null) {
  56079. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  56080. }
  56081. if (handleIndex === 'all') {
  56082. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  56083. handleSpan = restrict(handleSpan, [0, extentSpan]);
  56084. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  56085. handleIndex = 0;
  56086. }
  56087. handleEnds[0] = restrict(handleEnds[0], extent);
  56088. handleEnds[1] = restrict(handleEnds[1], extent);
  56089. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  56090. handleEnds[handleIndex] += delta; // Restrict in extent.
  56091. var extentMinSpan = minSpan || 0;
  56092. var realExtent = extent.slice();
  56093. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  56094. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  56095. var currDistSign;
  56096. currDistSign = getSpanSign(handleEnds, handleIndex);
  56097. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  56098. // If minSpan exists, 'cross' is forbidden.
  56099. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  56100. } // Shrink span.
  56101. currDistSign = getSpanSign(handleEnds, handleIndex);
  56102. if (maxSpan != null && currDistSign.span > maxSpan) {
  56103. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  56104. }
  56105. return handleEnds;
  56106. }
  56107. function getSpanSign(handleEnds, handleIndex) {
  56108. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  56109. // is at left of handleEnds[1] for non-cross case.
  56110. return {
  56111. span: Math.abs(dist),
  56112. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  56113. };
  56114. }
  56115. function restrict(value, extend) {
  56116. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  56117. }
  56118. var each$5 = each;
  56119. var mathMin$8 = Math.min;
  56120. var mathMax$8 = Math.max;
  56121. var mathFloor$1 = Math.floor;
  56122. var mathCeil$1 = Math.ceil;
  56123. var round$3 = round;
  56124. var PI$7 = Math.PI;
  56125. var Parallel =
  56126. /** @class */
  56127. function () {
  56128. function Parallel(parallelModel, ecModel, api) {
  56129. this.type = 'parallel';
  56130. /**
  56131. * key: dimension
  56132. */
  56133. this._axesMap = createHashMap();
  56134. /**
  56135. * key: dimension
  56136. * value: {position: [], rotation, }
  56137. */
  56138. this._axesLayout = {};
  56139. this.dimensions = parallelModel.dimensions;
  56140. this._model = parallelModel;
  56141. this._init(parallelModel, ecModel, api);
  56142. }
  56143. Parallel.prototype._init = function (parallelModel, ecModel, api) {
  56144. var dimensions = parallelModel.dimensions;
  56145. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  56146. each$5(dimensions, function (dim, idx) {
  56147. var axisIndex = parallelAxisIndex[idx];
  56148. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  56149. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  56150. var isCategory = axis.type === 'category';
  56151. axis.onBand = isCategory && axisModel.get('boundaryGap');
  56152. axis.inverse = axisModel.get('inverse'); // Injection
  56153. axisModel.axis = axis;
  56154. axis.model = axisModel;
  56155. axis.coordinateSystem = axisModel.coordinateSystem = this;
  56156. }, this);
  56157. };
  56158. /**
  56159. * Update axis scale after data processed
  56160. */
  56161. Parallel.prototype.update = function (ecModel, api) {
  56162. this._updateAxesFromSeries(this._model, ecModel);
  56163. };
  56164. Parallel.prototype.containPoint = function (point) {
  56165. var layoutInfo = this._makeLayoutInfo();
  56166. var axisBase = layoutInfo.axisBase;
  56167. var layoutBase = layoutInfo.layoutBase;
  56168. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56169. var pAxis = point[1 - pixelDimIndex];
  56170. var pLayout = point[pixelDimIndex];
  56171. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  56172. };
  56173. Parallel.prototype.getModel = function () {
  56174. return this._model;
  56175. };
  56176. /**
  56177. * Update properties from series
  56178. */
  56179. Parallel.prototype._updateAxesFromSeries = function (parallelModel, ecModel) {
  56180. ecModel.eachSeries(function (seriesModel) {
  56181. if (!parallelModel.contains(seriesModel, ecModel)) {
  56182. return;
  56183. }
  56184. var data = seriesModel.getData();
  56185. each$5(this.dimensions, function (dim) {
  56186. var axis = this._axesMap.get(dim);
  56187. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  56188. niceScaleExtent(axis.scale, axis.model);
  56189. }, this);
  56190. }, this);
  56191. };
  56192. /**
  56193. * Resize the parallel coordinate system.
  56194. */
  56195. Parallel.prototype.resize = function (parallelModel, api) {
  56196. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  56197. width: api.getWidth(),
  56198. height: api.getHeight()
  56199. });
  56200. this._layoutAxes();
  56201. };
  56202. Parallel.prototype.getRect = function () {
  56203. return this._rect;
  56204. };
  56205. Parallel.prototype._makeLayoutInfo = function () {
  56206. var parallelModel = this._model;
  56207. var rect = this._rect;
  56208. var xy = ['x', 'y'];
  56209. var wh = ['width', 'height'];
  56210. var layout = parallelModel.get('layout');
  56211. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  56212. var layoutLength = rect[wh[pixelDimIndex]];
  56213. var layoutExtent = [0, layoutLength];
  56214. var axisCount = this.dimensions.length;
  56215. var axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent);
  56216. var axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  56217. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  56218. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  56219. // where collapsed axes should be overlapped.
  56220. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  56221. var winSize;
  56222. if (!axisExpandWindow) {
  56223. winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  56224. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$1(axisCount / 2);
  56225. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  56226. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56227. } else {
  56228. winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  56229. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  56230. }
  56231. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  56232. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  56233. var winInnerIndices = [mathFloor$1(round$3(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round$3(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  56234. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  56235. return {
  56236. layout: layout,
  56237. pixelDimIndex: pixelDimIndex,
  56238. layoutBase: rect[xy[pixelDimIndex]],
  56239. layoutLength: layoutLength,
  56240. axisBase: rect[xy[1 - pixelDimIndex]],
  56241. axisLength: rect[wh[1 - pixelDimIndex]],
  56242. axisExpandable: axisExpandable,
  56243. axisExpandWidth: axisExpandWidth,
  56244. axisCollapseWidth: axisCollapseWidth,
  56245. axisExpandWindow: axisExpandWindow,
  56246. axisCount: axisCount,
  56247. winInnerIndices: winInnerIndices,
  56248. axisExpandWindow0Pos: axisExpandWindow0Pos
  56249. };
  56250. };
  56251. Parallel.prototype._layoutAxes = function () {
  56252. var rect = this._rect;
  56253. var axes = this._axesMap;
  56254. var dimensions = this.dimensions;
  56255. var layoutInfo = this._makeLayoutInfo();
  56256. var layout = layoutInfo.layout;
  56257. axes.each(function (axis) {
  56258. var axisExtent = [0, layoutInfo.axisLength];
  56259. var idx = axis.inverse ? 1 : 0;
  56260. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  56261. });
  56262. each$5(dimensions, function (dim, idx) {
  56263. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  56264. var positionTable = {
  56265. horizontal: {
  56266. x: posInfo.position,
  56267. y: layoutInfo.axisLength
  56268. },
  56269. vertical: {
  56270. x: 0,
  56271. y: posInfo.position
  56272. }
  56273. };
  56274. var rotationTable = {
  56275. horizontal: PI$7 / 2,
  56276. vertical: 0
  56277. };
  56278. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  56279. var rotation = rotationTable[layout];
  56280. var transform = create$1();
  56281. rotate(transform, transform, rotation);
  56282. translate(transform, transform, position); // TODO
  56283. // tick layout info
  56284. // TODO
  56285. // update dimensions info based on axis order.
  56286. this._axesLayout[dim] = {
  56287. position: position,
  56288. rotation: rotation,
  56289. transform: transform,
  56290. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  56291. axisLabelShow: posInfo.axisLabelShow,
  56292. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  56293. tickDirection: 1,
  56294. labelDirection: 1
  56295. };
  56296. }, this);
  56297. };
  56298. /**
  56299. * Get axis by dim.
  56300. */
  56301. Parallel.prototype.getAxis = function (dim) {
  56302. return this._axesMap.get(dim);
  56303. };
  56304. /**
  56305. * Convert a dim value of a single item of series data to Point.
  56306. */
  56307. Parallel.prototype.dataToPoint = function (value, dim) {
  56308. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  56309. };
  56310. /**
  56311. * Travel data for one time, get activeState of each data item.
  56312. * @param start the start dataIndex that travel from.
  56313. * @param end the next dataIndex of the last dataIndex will be travel.
  56314. */
  56315. Parallel.prototype.eachActiveState = function (data, callback, start, end) {
  56316. start == null && (start = 0);
  56317. end == null && (end = data.count());
  56318. var axesMap = this._axesMap;
  56319. var dimensions = this.dimensions;
  56320. var dataDimensions = [];
  56321. var axisModels = [];
  56322. each(dimensions, function (axisDim) {
  56323. dataDimensions.push(data.mapDimension(axisDim));
  56324. axisModels.push(axesMap.get(axisDim).model);
  56325. });
  56326. var hasActiveSet = this.hasAxisBrushed();
  56327. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  56328. var activeState = void 0;
  56329. if (!hasActiveSet) {
  56330. activeState = 'normal';
  56331. } else {
  56332. activeState = 'active';
  56333. var values = data.getValues(dataDimensions, dataIndex);
  56334. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56335. var state = axisModels[j].getActiveState(values[j]);
  56336. if (state === 'inactive') {
  56337. activeState = 'inactive';
  56338. break;
  56339. }
  56340. }
  56341. }
  56342. callback(activeState, dataIndex);
  56343. }
  56344. };
  56345. /**
  56346. * Whether has any activeSet.
  56347. */
  56348. Parallel.prototype.hasAxisBrushed = function () {
  56349. var dimensions = this.dimensions;
  56350. var axesMap = this._axesMap;
  56351. var hasActiveSet = false;
  56352. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  56353. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  56354. hasActiveSet = true;
  56355. }
  56356. }
  56357. return hasActiveSet;
  56358. };
  56359. /**
  56360. * Convert coords of each axis to Point.
  56361. * Return point. For example: [10, 20]
  56362. */
  56363. Parallel.prototype.axisCoordToPoint = function (coord, dim) {
  56364. var axisLayout = this._axesLayout[dim];
  56365. return applyTransform$1([coord, 0], axisLayout.transform);
  56366. };
  56367. /**
  56368. * Get axis layout.
  56369. */
  56370. Parallel.prototype.getAxisLayout = function (dim) {
  56371. return clone(this._axesLayout[dim]);
  56372. };
  56373. /**
  56374. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  56375. */
  56376. Parallel.prototype.getSlidedAxisExpandWindow = function (point) {
  56377. var layoutInfo = this._makeLayoutInfo();
  56378. var pixelDimIndex = layoutInfo.pixelDimIndex;
  56379. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  56380. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  56381. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  56382. if (!this.containPoint(point)) {
  56383. return {
  56384. behavior: 'none',
  56385. axisExpandWindow: axisExpandWindow
  56386. };
  56387. } // Convert the point from global to expand coordinates.
  56388. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  56389. // slided when mouse is the center area of the window.
  56390. var delta;
  56391. var behavior = 'slide';
  56392. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56393. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  56394. var useJump = triggerArea[0] != null;
  56395. if (axisCollapseWidth) {
  56396. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  56397. behavior = 'jump';
  56398. delta = pointCoord - winSize * triggerArea[2];
  56399. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  56400. behavior = 'jump';
  56401. delta = pointCoord - winSize * (1 - triggerArea[2]);
  56402. } else {
  56403. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  56404. }
  56405. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  56406. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  56407. : behavior = 'none';
  56408. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  56409. else {
  56410. var winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
  56411. var pos = extent[1] * pointCoord / winSize2;
  56412. axisExpandWindow = [mathMax$8(0, pos - winSize2 / 2)];
  56413. axisExpandWindow[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2);
  56414. axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
  56415. }
  56416. return {
  56417. axisExpandWindow: axisExpandWindow,
  56418. behavior: behavior
  56419. };
  56420. };
  56421. return Parallel;
  56422. }();
  56423. function restrict$1(len, extent) {
  56424. return mathMin$8(mathMax$8(len, extent[0]), extent[1]);
  56425. }
  56426. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  56427. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  56428. return {
  56429. position: step * axisIndex,
  56430. axisNameAvailableWidth: step,
  56431. axisLabelShow: true
  56432. };
  56433. }
  56434. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  56435. var layoutLength = layoutInfo.layoutLength;
  56436. var axisExpandWidth = layoutInfo.axisExpandWidth;
  56437. var axisCount = layoutInfo.axisCount;
  56438. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  56439. var winInnerIndices = layoutInfo.winInnerIndices;
  56440. var position;
  56441. var axisNameAvailableWidth = axisCollapseWidth;
  56442. var axisLabelShow = false;
  56443. var nameTruncateMaxWidth;
  56444. if (axisIndex < winInnerIndices[0]) {
  56445. position = axisIndex * axisCollapseWidth;
  56446. nameTruncateMaxWidth = axisCollapseWidth;
  56447. } else if (axisIndex <= winInnerIndices[1]) {
  56448. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  56449. axisNameAvailableWidth = axisExpandWidth;
  56450. axisLabelShow = true;
  56451. } else {
  56452. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  56453. nameTruncateMaxWidth = axisCollapseWidth;
  56454. }
  56455. return {
  56456. position: position,
  56457. axisNameAvailableWidth: axisNameAvailableWidth,
  56458. axisLabelShow: axisLabelShow,
  56459. nameTruncateMaxWidth: nameTruncateMaxWidth
  56460. };
  56461. }
  56462. function createParallelCoordSys(ecModel, api) {
  56463. var coordSysList = [];
  56464. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  56465. var coordSys = new Parallel(parallelModel, ecModel, api);
  56466. coordSys.name = 'parallel_' + idx;
  56467. coordSys.resize(parallelModel, api);
  56468. parallelModel.coordinateSystem = coordSys;
  56469. coordSys.model = parallelModel;
  56470. coordSysList.push(coordSys);
  56471. }); // Inject the coordinateSystems into seriesModel
  56472. ecModel.eachSeries(function (seriesModel) {
  56473. if (seriesModel.get('coordinateSystem') === 'parallel') {
  56474. var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0];
  56475. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  56476. }
  56477. });
  56478. return coordSysList;
  56479. }
  56480. var parallelCoordSysCreator = {
  56481. create: createParallelCoordSys
  56482. };
  56483. var ParallelAxisModel =
  56484. /** @class */
  56485. function (_super) {
  56486. __extends(ParallelAxisModel, _super);
  56487. function ParallelAxisModel() {
  56488. var _this = _super !== null && _super.apply(this, arguments) || this;
  56489. _this.type = ParallelAxisModel.type;
  56490. /**
  56491. * @readOnly
  56492. */
  56493. _this.activeIntervals = [];
  56494. return _this;
  56495. }
  56496. ParallelAxisModel.prototype.getAreaSelectStyle = function () {
  56497. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  56498. // So do not transfer decal directly.
  56499. ])(this.getModel('areaSelectStyle'));
  56500. };
  56501. /**
  56502. * The code of this feature is put on AxisModel but not ParallelAxis,
  56503. * because axisModel can be alive after echarts updating but instance of
  56504. * ParallelAxis having been disposed. this._activeInterval should be kept
  56505. * when action dispatched (i.e. legend click).
  56506. *
  56507. * @param intervals `interval.length === 0` means set all active.
  56508. */
  56509. ParallelAxisModel.prototype.setActiveIntervals = function (intervals) {
  56510. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  56511. if (activeIntervals) {
  56512. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  56513. asc(activeIntervals[i]);
  56514. }
  56515. }
  56516. };
  56517. /**
  56518. * @param value When only attempting detect whether 'no activeIntervals set',
  56519. * `value` is not needed to be input.
  56520. */
  56521. ParallelAxisModel.prototype.getActiveState = function (value) {
  56522. var activeIntervals = this.activeIntervals;
  56523. if (!activeIntervals.length) {
  56524. return 'normal';
  56525. }
  56526. if (value == null || isNaN(+value)) {
  56527. return 'inactive';
  56528. } // Simple optimization
  56529. if (activeIntervals.length === 1) {
  56530. var interval = activeIntervals[0];
  56531. if (interval[0] <= value && value <= interval[1]) {
  56532. return 'active';
  56533. }
  56534. } else {
  56535. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  56536. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  56537. return 'active';
  56538. }
  56539. }
  56540. }
  56541. return 'inactive';
  56542. };
  56543. return ParallelAxisModel;
  56544. }(ComponentModel);
  56545. mixin(ParallelAxisModel, AxisModelCommonMixin);
  56546. var BRUSH_PANEL_GLOBAL = true;
  56547. var mathMin$9 = Math.min;
  56548. var mathMax$9 = Math.max;
  56549. var mathPow$2 = Math.pow;
  56550. var COVER_Z = 10000;
  56551. var UNSELECT_THRESHOLD = 6;
  56552. var MIN_RESIZE_LINE_WIDTH = 6;
  56553. var MUTEX_RESOURCE_KEY = 'globalPan';
  56554. var DIRECTION_MAP = {
  56555. w: [0, 0],
  56556. e: [0, 1],
  56557. n: [1, 0],
  56558. s: [1, 1]
  56559. };
  56560. var CURSOR_MAP = {
  56561. w: 'ew',
  56562. e: 'ew',
  56563. n: 'ns',
  56564. s: 'ns',
  56565. ne: 'nesw',
  56566. sw: 'nesw',
  56567. nw: 'nwse',
  56568. se: 'nwse'
  56569. };
  56570. var DEFAULT_BRUSH_OPT = {
  56571. brushStyle: {
  56572. lineWidth: 2,
  56573. stroke: 'rgba(210,219,238,0.3)',
  56574. fill: '#D2DBEE'
  56575. },
  56576. transformable: true,
  56577. brushMode: 'single',
  56578. removeOnClick: false
  56579. };
  56580. var baseUID = 0;
  56581. /**
  56582. * params:
  56583. * areas: Array.<Array>, coord relates to container group,
  56584. * If no container specified, to global.
  56585. * opt {
  56586. * isEnd: boolean,
  56587. * removeOnClick: boolean
  56588. * }
  56589. */
  56590. var BrushController =
  56591. /** @class */
  56592. function (_super) {
  56593. __extends(BrushController, _super);
  56594. function BrushController(zr) {
  56595. var _this = _super.call(this) || this;
  56596. /**
  56597. * @internal
  56598. */
  56599. _this._track = [];
  56600. /**
  56601. * @internal
  56602. */
  56603. _this._covers = [];
  56604. _this._handlers = {};
  56605. if ("development" !== 'production') {
  56606. assert(zr);
  56607. }
  56608. _this._zr = zr;
  56609. _this.group = new Group();
  56610. _this._uid = 'brushController_' + baseUID++;
  56611. each(pointerHandlers, function (handler, eventName) {
  56612. this._handlers[eventName] = bind(handler, this);
  56613. }, _this);
  56614. return _this;
  56615. }
  56616. /**
  56617. * If set to `false`, select disabled.
  56618. */
  56619. BrushController.prototype.enableBrush = function (brushOption) {
  56620. if ("development" !== 'production') {
  56621. assert(this._mounted);
  56622. }
  56623. this._brushType && this._doDisableBrush();
  56624. brushOption.brushType && this._doEnableBrush(brushOption);
  56625. return this;
  56626. };
  56627. BrushController.prototype._doEnableBrush = function (brushOption) {
  56628. var zr = this._zr; // Consider roam, which takes globalPan too.
  56629. if (!this._enableGlobalPan) {
  56630. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  56631. }
  56632. each(this._handlers, function (handler, eventName) {
  56633. zr.on(eventName, handler);
  56634. });
  56635. this._brushType = brushOption.brushType;
  56636. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  56637. };
  56638. BrushController.prototype._doDisableBrush = function () {
  56639. var zr = this._zr;
  56640. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  56641. each(this._handlers, function (handler, eventName) {
  56642. zr.off(eventName, handler);
  56643. });
  56644. this._brushType = this._brushOption = null;
  56645. };
  56646. /**
  56647. * @param panelOpts If not pass, it is global brush.
  56648. */
  56649. BrushController.prototype.setPanels = function (panelOpts) {
  56650. if (panelOpts && panelOpts.length) {
  56651. var panels_1 = this._panels = {};
  56652. each(panelOpts, function (panelOpts) {
  56653. panels_1[panelOpts.panelId] = clone(panelOpts);
  56654. });
  56655. } else {
  56656. this._panels = null;
  56657. }
  56658. return this;
  56659. };
  56660. BrushController.prototype.mount = function (opt) {
  56661. opt = opt || {};
  56662. if ("development" !== 'production') {
  56663. this._mounted = true; // should be at first.
  56664. }
  56665. this._enableGlobalPan = opt.enableGlobalPan;
  56666. var thisGroup = this.group;
  56667. this._zr.add(thisGroup);
  56668. thisGroup.attr({
  56669. x: opt.x || 0,
  56670. y: opt.y || 0,
  56671. rotation: opt.rotation || 0,
  56672. scaleX: opt.scaleX || 1,
  56673. scaleY: opt.scaleY || 1
  56674. });
  56675. this._transform = thisGroup.getLocalTransform();
  56676. return this;
  56677. }; // eachCover(cb, context): void {
  56678. // each(this._covers, cb, context);
  56679. // }
  56680. /**
  56681. * Update covers.
  56682. * @param coverConfigList
  56683. * If coverConfigList is null/undefined, all covers removed.
  56684. */
  56685. BrushController.prototype.updateCovers = function (coverConfigList) {
  56686. if ("development" !== 'production') {
  56687. assert(this._mounted);
  56688. }
  56689. coverConfigList = map(coverConfigList, function (coverConfig) {
  56690. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  56691. });
  56692. var tmpIdPrefix = '\0-brush-index-';
  56693. var oldCovers = this._covers;
  56694. var newCovers = this._covers = [];
  56695. var controller = this;
  56696. var creatingCover = this._creatingCover;
  56697. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  56698. return this;
  56699. function getKey(brushOption, index) {
  56700. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  56701. }
  56702. function oldGetKey(cover, index) {
  56703. return getKey(cover.__brushOption, index);
  56704. }
  56705. function addOrUpdate(newIndex, oldIndex) {
  56706. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  56707. // where updating cover when creating should be forbidden.
  56708. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  56709. newCovers[newIndex] = oldCovers[oldIndex];
  56710. } else {
  56711. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  56712. updateCoverAfterCreation(controller, cover);
  56713. }
  56714. }
  56715. function remove(oldIndex) {
  56716. if (oldCovers[oldIndex] !== creatingCover) {
  56717. controller.group.remove(oldCovers[oldIndex]);
  56718. }
  56719. }
  56720. };
  56721. BrushController.prototype.unmount = function () {
  56722. if ("development" !== 'production') {
  56723. if (!this._mounted) {
  56724. return;
  56725. }
  56726. }
  56727. this.enableBrush(false); // container may 'removeAll' outside.
  56728. clearCovers(this);
  56729. this._zr.remove(this.group);
  56730. if ("development" !== 'production') {
  56731. this._mounted = false; // should be at last.
  56732. }
  56733. return this;
  56734. };
  56735. BrushController.prototype.dispose = function () {
  56736. this.unmount();
  56737. this.off();
  56738. };
  56739. return BrushController;
  56740. }(Eventful);
  56741. function createCover(controller, brushOption) {
  56742. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  56743. cover.__brushOption = brushOption;
  56744. updateZ(cover, brushOption);
  56745. controller.group.add(cover);
  56746. return cover;
  56747. }
  56748. function endCreating(controller, creatingCover) {
  56749. var coverRenderer = getCoverRenderer(creatingCover);
  56750. if (coverRenderer.endCreating) {
  56751. coverRenderer.endCreating(controller, creatingCover);
  56752. updateZ(creatingCover, creatingCover.__brushOption);
  56753. }
  56754. return creatingCover;
  56755. }
  56756. function updateCoverShape(controller, cover) {
  56757. var brushOption = cover.__brushOption;
  56758. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  56759. }
  56760. function updateZ(cover, brushOption) {
  56761. var z = brushOption.z;
  56762. z == null && (z = COVER_Z);
  56763. cover.traverse(function (el) {
  56764. el.z = z;
  56765. el.z2 = z; // Consider in given container.
  56766. });
  56767. }
  56768. function updateCoverAfterCreation(controller, cover) {
  56769. getCoverRenderer(cover).updateCommon(controller, cover);
  56770. updateCoverShape(controller, cover);
  56771. }
  56772. function getCoverRenderer(cover) {
  56773. return coverRenderers[cover.__brushOption.brushType];
  56774. } // return target panel or `true` (means global panel)
  56775. function getPanelByPoint(controller, e, localCursorPoint) {
  56776. var panels = controller._panels;
  56777. if (!panels) {
  56778. return BRUSH_PANEL_GLOBAL; // Global panel
  56779. }
  56780. var panel;
  56781. var transform = controller._transform;
  56782. each(panels, function (pn) {
  56783. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  56784. });
  56785. return panel;
  56786. } // Return a panel or true
  56787. function getPanelByCover(controller, cover) {
  56788. var panels = controller._panels;
  56789. if (!panels) {
  56790. return BRUSH_PANEL_GLOBAL; // Global panel
  56791. }
  56792. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  56793. // which is then treated as global panel.
  56794. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  56795. }
  56796. function clearCovers(controller) {
  56797. var covers = controller._covers;
  56798. var originalLength = covers.length;
  56799. each(covers, function (cover) {
  56800. controller.group.remove(cover);
  56801. }, controller);
  56802. covers.length = 0;
  56803. return !!originalLength;
  56804. }
  56805. function trigger$1(controller, opt) {
  56806. var areas = map(controller._covers, function (cover) {
  56807. var brushOption = cover.__brushOption;
  56808. var range = clone(brushOption.range);
  56809. return {
  56810. brushType: brushOption.brushType,
  56811. panelId: brushOption.panelId,
  56812. range: range
  56813. };
  56814. });
  56815. controller.trigger('brush', {
  56816. areas: areas,
  56817. isEnd: !!opt.isEnd,
  56818. removeOnClick: !!opt.removeOnClick
  56819. });
  56820. }
  56821. function shouldShowCover(controller) {
  56822. var track = controller._track;
  56823. if (!track.length) {
  56824. return false;
  56825. }
  56826. var p2 = track[track.length - 1];
  56827. var p1 = track[0];
  56828. var dx = p2[0] - p1[0];
  56829. var dy = p2[1] - p1[1];
  56830. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  56831. return dist > UNSELECT_THRESHOLD;
  56832. }
  56833. function getTrackEnds(track) {
  56834. var tail = track.length - 1;
  56835. tail < 0 && (tail = 0);
  56836. return [track[0], track[tail]];
  56837. }
  56838. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  56839. var cover = new Group();
  56840. cover.add(new Rect({
  56841. name: 'main',
  56842. style: makeStyle(brushOption),
  56843. silent: true,
  56844. draggable: true,
  56845. cursor: 'move',
  56846. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  56847. ondragend: curry(trigger$1, controller, {
  56848. isEnd: true
  56849. })
  56850. }));
  56851. each(edgeNameSequences, function (nameSequence) {
  56852. cover.add(new Rect({
  56853. name: nameSequence.join(''),
  56854. style: {
  56855. opacity: 0
  56856. },
  56857. draggable: true,
  56858. silent: true,
  56859. invisible: true,
  56860. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  56861. ondragend: curry(trigger$1, controller, {
  56862. isEnd: true
  56863. })
  56864. }));
  56865. });
  56866. return cover;
  56867. }
  56868. function updateBaseRect(controller, cover, localRange, brushOption) {
  56869. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  56870. var handleSize = mathMax$9(lineWidth, MIN_RESIZE_LINE_WIDTH);
  56871. var x = localRange[0][0];
  56872. var y = localRange[1][0];
  56873. var xa = x - lineWidth / 2;
  56874. var ya = y - lineWidth / 2;
  56875. var x2 = localRange[0][1];
  56876. var y2 = localRange[1][1];
  56877. var x2a = x2 - handleSize + lineWidth / 2;
  56878. var y2a = y2 - handleSize + lineWidth / 2;
  56879. var width = x2 - x;
  56880. var height = y2 - y;
  56881. var widtha = width + lineWidth;
  56882. var heighta = height + lineWidth;
  56883. updateRectShape(controller, cover, 'main', x, y, width, height);
  56884. if (brushOption.transformable) {
  56885. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  56886. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  56887. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  56888. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  56889. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  56890. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  56891. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  56892. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  56893. }
  56894. }
  56895. function updateCommon(controller, cover) {
  56896. var brushOption = cover.__brushOption;
  56897. var transformable = brushOption.transformable;
  56898. var mainEl = cover.childAt(0);
  56899. mainEl.useStyle(makeStyle(brushOption));
  56900. mainEl.attr({
  56901. silent: !transformable,
  56902. cursor: transformable ? 'move' : 'default'
  56903. });
  56904. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  56905. var el = cover.childOfName(nameSequence.join(''));
  56906. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  56907. el && el.attr({
  56908. silent: !transformable,
  56909. invisible: !transformable,
  56910. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  56911. });
  56912. });
  56913. }
  56914. function updateRectShape(controller, cover, name, x, y, w, h) {
  56915. var el = cover.childOfName(name);
  56916. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  56917. }
  56918. function makeStyle(brushOption) {
  56919. return defaults({
  56920. strokeNoScale: true
  56921. }, brushOption.brushStyle);
  56922. }
  56923. function formatRectRange(x, y, x2, y2) {
  56924. var min = [mathMin$9(x, x2), mathMin$9(y, y2)];
  56925. var max = [mathMax$9(x, x2), mathMax$9(y, y2)];
  56926. return [[min[0], max[0]], [min[1], max[1]] // y range
  56927. ];
  56928. }
  56929. function getTransform$1(controller) {
  56930. return getTransform(controller.group);
  56931. }
  56932. function getGlobalDirection1(controller, localDirName) {
  56933. var map = {
  56934. w: 'left',
  56935. e: 'right',
  56936. n: 'top',
  56937. s: 'bottom'
  56938. };
  56939. var inverseMap = {
  56940. left: 'w',
  56941. right: 'e',
  56942. top: 'n',
  56943. bottom: 's'
  56944. };
  56945. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  56946. return inverseMap[dir];
  56947. }
  56948. function getGlobalDirection2(controller, localDirNameSeq) {
  56949. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  56950. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  56951. return globalDir.join('');
  56952. }
  56953. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  56954. var brushOption = cover.__brushOption;
  56955. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  56956. var localDelta = toLocalDelta(controller, dx, dy);
  56957. each(dirNameSequence, function (dirName) {
  56958. var ind = DIRECTION_MAP[dirName];
  56959. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  56960. });
  56961. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  56962. updateCoverAfterCreation(controller, cover);
  56963. trigger$1(controller, {
  56964. isEnd: false
  56965. });
  56966. }
  56967. function driftPolygon(controller, cover, dx, dy) {
  56968. var range = cover.__brushOption.range;
  56969. var localDelta = toLocalDelta(controller, dx, dy);
  56970. each(range, function (point) {
  56971. point[0] += localDelta[0];
  56972. point[1] += localDelta[1];
  56973. });
  56974. updateCoverAfterCreation(controller, cover);
  56975. trigger$1(controller, {
  56976. isEnd: false
  56977. });
  56978. }
  56979. function toLocalDelta(controller, dx, dy) {
  56980. var thisGroup = controller.group;
  56981. var localD = thisGroup.transformCoordToLocal(dx, dy);
  56982. var localZero = thisGroup.transformCoordToLocal(0, 0);
  56983. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  56984. }
  56985. function clipByPanel(controller, cover, data) {
  56986. var panel = getPanelByCover(controller, cover);
  56987. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  56988. }
  56989. function pointsToRect(points) {
  56990. var xmin = mathMin$9(points[0][0], points[1][0]);
  56991. var ymin = mathMin$9(points[0][1], points[1][1]);
  56992. var xmax = mathMax$9(points[0][0], points[1][0]);
  56993. var ymax = mathMax$9(points[0][1], points[1][1]);
  56994. return {
  56995. x: xmin,
  56996. y: ymin,
  56997. width: xmax - xmin,
  56998. height: ymax - ymin
  56999. };
  57000. }
  57001. function resetCursor(controller, e, localCursorPoint) {
  57002. if ( // Check active
  57003. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  57004. // but not called when mouse is out of zr area to avoid bad influence
  57005. // if `mousemove`, `mouseup` are triggered from `document` event.
  57006. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  57007. return;
  57008. }
  57009. var zr = controller._zr;
  57010. var covers = controller._covers;
  57011. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  57012. if (!controller._dragging) {
  57013. for (var i = 0; i < covers.length; i++) {
  57014. var brushOption = covers[i].__brushOption;
  57015. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  57016. // Use cursor style set on cover.
  57017. return;
  57018. }
  57019. }
  57020. }
  57021. currPanel && zr.setCursorStyle('crosshair');
  57022. }
  57023. function preventDefault(e) {
  57024. var rawE = e.event;
  57025. rawE.preventDefault && rawE.preventDefault();
  57026. }
  57027. function mainShapeContain(cover, x, y) {
  57028. return cover.childOfName('main').contain(x, y);
  57029. }
  57030. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  57031. var creatingCover = controller._creatingCover;
  57032. var panel = controller._creatingPanel;
  57033. var thisBrushOption = controller._brushOption;
  57034. var eventParams;
  57035. controller._track.push(localCursorPoint.slice());
  57036. if (shouldShowCover(controller) || creatingCover) {
  57037. if (panel && !creatingCover) {
  57038. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  57039. var brushOption = clone(thisBrushOption);
  57040. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  57041. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  57042. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  57043. controller._covers.push(creatingCover);
  57044. }
  57045. if (creatingCover) {
  57046. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  57047. var coverBrushOption = creatingCover.__brushOption;
  57048. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  57049. if (isEnd) {
  57050. endCreating(controller, creatingCover);
  57051. coverRenderer.updateCommon(controller, creatingCover);
  57052. }
  57053. updateCoverShape(controller, creatingCover);
  57054. eventParams = {
  57055. isEnd: isEnd
  57056. };
  57057. }
  57058. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  57059. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  57060. // But a single click do not clear covers, because user may have casual
  57061. // clicks (for example, click on other component and do not expect covers
  57062. // disappear).
  57063. // Only some cover removed, trigger action, but not every click trigger action.
  57064. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  57065. eventParams = {
  57066. isEnd: isEnd,
  57067. removeOnClick: true
  57068. };
  57069. }
  57070. }
  57071. return eventParams;
  57072. }
  57073. function determineBrushType(brushType, panel) {
  57074. if (brushType === 'auto') {
  57075. if ("development" !== 'production') {
  57076. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  57077. }
  57078. return panel.defaultBrushType;
  57079. }
  57080. return brushType;
  57081. }
  57082. var pointerHandlers = {
  57083. mousedown: function (e) {
  57084. if (this._dragging) {
  57085. // In case some browser do not support globalOut,
  57086. // and release mouse out side the browser.
  57087. handleDragEnd(this, e);
  57088. } else if (!e.target || !e.target.draggable) {
  57089. preventDefault(e);
  57090. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  57091. this._creatingCover = null;
  57092. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  57093. if (panel) {
  57094. this._dragging = true;
  57095. this._track = [localCursorPoint.slice()];
  57096. }
  57097. }
  57098. },
  57099. mousemove: function (e) {
  57100. var x = e.offsetX;
  57101. var y = e.offsetY;
  57102. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  57103. resetCursor(this, e, localCursorPoint);
  57104. if (this._dragging) {
  57105. preventDefault(e);
  57106. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  57107. eventParams && trigger$1(this, eventParams);
  57108. }
  57109. },
  57110. mouseup: function (e) {
  57111. handleDragEnd(this, e);
  57112. }
  57113. };
  57114. function handleDragEnd(controller, e) {
  57115. if (controller._dragging) {
  57116. preventDefault(e);
  57117. var x = e.offsetX;
  57118. var y = e.offsetY;
  57119. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  57120. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  57121. controller._dragging = false;
  57122. controller._track = [];
  57123. controller._creatingCover = null; // trigger event should be at final, after procedure will be nested.
  57124. eventParams && trigger$1(controller, eventParams);
  57125. }
  57126. }
  57127. function isOutsideZrArea(controller, x, y) {
  57128. var zr = controller._zr;
  57129. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  57130. }
  57131. /**
  57132. * key: brushType
  57133. */
  57134. var coverRenderers = {
  57135. lineX: getLineRenderer(0),
  57136. lineY: getLineRenderer(1),
  57137. rect: {
  57138. createCover: function (controller, brushOption) {
  57139. function returnInput(range) {
  57140. return range;
  57141. }
  57142. return createBaseRectCover({
  57143. toRectRange: returnInput,
  57144. fromRectRange: returnInput
  57145. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  57146. },
  57147. getCreatingRange: function (localTrack) {
  57148. var ends = getTrackEnds(localTrack);
  57149. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  57150. },
  57151. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57152. updateBaseRect(controller, cover, localRange, brushOption);
  57153. },
  57154. updateCommon: updateCommon,
  57155. contain: mainShapeContain
  57156. },
  57157. polygon: {
  57158. createCover: function (controller, brushOption) {
  57159. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  57160. // border of the shape when drawing, which is a better experience for user.
  57161. cover.add(new Polyline({
  57162. name: 'main',
  57163. style: makeStyle(brushOption),
  57164. silent: true
  57165. }));
  57166. return cover;
  57167. },
  57168. getCreatingRange: function (localTrack) {
  57169. return localTrack;
  57170. },
  57171. endCreating: function (controller, cover) {
  57172. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  57173. cover.add(new Polygon({
  57174. name: 'main',
  57175. draggable: true,
  57176. drift: curry(driftPolygon, controller, cover),
  57177. ondragend: curry(trigger$1, controller, {
  57178. isEnd: true
  57179. })
  57180. }));
  57181. },
  57182. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57183. cover.childAt(0).setShape({
  57184. points: clipByPanel(controller, cover, localRange)
  57185. });
  57186. },
  57187. updateCommon: updateCommon,
  57188. contain: mainShapeContain
  57189. }
  57190. };
  57191. function getLineRenderer(xyIndex) {
  57192. return {
  57193. createCover: function (controller, brushOption) {
  57194. return createBaseRectCover({
  57195. toRectRange: function (range) {
  57196. var rectRange = [range, [0, 100]];
  57197. xyIndex && rectRange.reverse();
  57198. return rectRange;
  57199. },
  57200. fromRectRange: function (rectRange) {
  57201. return rectRange[xyIndex];
  57202. }
  57203. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  57204. },
  57205. getCreatingRange: function (localTrack) {
  57206. var ends = getTrackEnds(localTrack);
  57207. var min = mathMin$9(ends[0][xyIndex], ends[1][xyIndex]);
  57208. var max = mathMax$9(ends[0][xyIndex], ends[1][xyIndex]);
  57209. return [min, max];
  57210. },
  57211. updateCoverShape: function (controller, cover, localRange, brushOption) {
  57212. var otherExtent; // If brushWidth not specified, fit the panel.
  57213. var panel = getPanelByCover(controller, cover);
  57214. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  57215. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  57216. } else {
  57217. var zr = controller._zr;
  57218. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  57219. }
  57220. var rectRange = [localRange, otherExtent];
  57221. xyIndex && rectRange.reverse();
  57222. updateBaseRect(controller, cover, rectRange, brushOption);
  57223. },
  57224. updateCommon: updateCommon,
  57225. contain: mainShapeContain
  57226. };
  57227. }
  57228. function makeRectPanelClipPath(rect) {
  57229. rect = normalizeRect(rect);
  57230. return function (localPoints) {
  57231. return clipPointsByRect(localPoints, rect);
  57232. };
  57233. }
  57234. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  57235. rect = normalizeRect(rect);
  57236. return function (xyIndex) {
  57237. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  57238. var brushWidth = idx ? rect.width : rect.height;
  57239. var base = idx ? rect.x : rect.y;
  57240. return [base, base + (brushWidth || 0)];
  57241. };
  57242. }
  57243. function makeRectIsTargetByCursor(rect, api, targetModel) {
  57244. var boundingRect = normalizeRect(rect);
  57245. return function (e, localCursorPoint) {
  57246. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  57247. };
  57248. } // Consider width/height is negative.
  57249. function normalizeRect(rect) {
  57250. return BoundingRect.create(rect);
  57251. }
  57252. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  57253. var ParallelAxisView =
  57254. /** @class */
  57255. function (_super) {
  57256. __extends(ParallelAxisView, _super);
  57257. function ParallelAxisView() {
  57258. var _this = _super !== null && _super.apply(this, arguments) || this;
  57259. _this.type = ParallelAxisView.type;
  57260. return _this;
  57261. }
  57262. ParallelAxisView.prototype.init = function (ecModel, api) {
  57263. _super.prototype.init.apply(this, arguments);
  57264. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  57265. };
  57266. ParallelAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  57267. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  57268. return;
  57269. }
  57270. this.axisModel = axisModel;
  57271. this.api = api;
  57272. this.group.removeAll();
  57273. var oldAxisGroup = this._axisGroup;
  57274. this._axisGroup = new Group();
  57275. this.group.add(this._axisGroup);
  57276. if (!axisModel.get('show')) {
  57277. return;
  57278. }
  57279. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  57280. var coordSys = coordSysModel.coordinateSystem;
  57281. var areaSelectStyle = axisModel.getAreaSelectStyle();
  57282. var areaWidth = areaSelectStyle.width;
  57283. var dim = axisModel.axis.dim;
  57284. var axisLayout = coordSys.getAxisLayout(dim);
  57285. var builderOpt = extend({
  57286. strokeContainThreshold: areaWidth
  57287. }, axisLayout);
  57288. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  57289. each(elementList, axisBuilder.add, axisBuilder);
  57290. this._axisGroup.add(axisBuilder.getGroup());
  57291. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  57292. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  57293. }; // /**
  57294. // * @override
  57295. // */
  57296. // updateVisual(axisModel, ecModel, api, payload) {
  57297. // this._brushController && this._brushController
  57298. // .updateCovers(getCoverInfoList(axisModel));
  57299. // }
  57300. ParallelAxisView.prototype._refreshBrushController = function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  57301. // After filtering, axis may change, select area needs to be update.
  57302. var extent = axisModel.axis.getExtent();
  57303. var extentLen = extent[1] - extent[0];
  57304. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  57305. // width/height might be negative, which will be
  57306. // normalized in BoundingRect.
  57307. var rect = BoundingRect.create({
  57308. x: extent[0],
  57309. y: -areaWidth / 2,
  57310. width: extentLen,
  57311. height: areaWidth
  57312. });
  57313. rect.x -= extra;
  57314. rect.width += 2 * extra;
  57315. this._brushController.mount({
  57316. enableGlobalPan: true,
  57317. rotation: builderOpt.rotation,
  57318. x: builderOpt.position[0],
  57319. y: builderOpt.position[1]
  57320. }).setPanels([{
  57321. panelId: 'pl',
  57322. clipPath: makeRectPanelClipPath(rect),
  57323. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  57324. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  57325. }]).enableBrush({
  57326. brushType: 'lineX',
  57327. brushStyle: areaSelectStyle,
  57328. removeOnClick: true
  57329. }).updateCovers(getCoverInfoList(axisModel));
  57330. };
  57331. ParallelAxisView.prototype._onBrush = function (eventParam) {
  57332. var coverInfoList = eventParam.areas; // Do not cache these object, because the mey be changed.
  57333. var axisModel = this.axisModel;
  57334. var axis = axisModel.axis;
  57335. var intervals = map(coverInfoList, function (coverInfo) {
  57336. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  57337. }); // If realtime is true, action is not dispatched on drag end, because
  57338. // the drag end emits the same params with the last drag move event,
  57339. // and may have some delay when using touch pad.
  57340. if (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) {
  57341. // jshint ignore:line
  57342. this.api.dispatchAction({
  57343. type: 'axisAreaSelect',
  57344. parallelAxisId: axisModel.id,
  57345. intervals: intervals
  57346. });
  57347. }
  57348. };
  57349. ParallelAxisView.prototype.dispose = function () {
  57350. this._brushController.dispose();
  57351. };
  57352. ParallelAxisView.type = 'parallelAxis';
  57353. return ParallelAxisView;
  57354. }(ComponentView);
  57355. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  57356. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  57357. mainType: 'parallelAxis',
  57358. query: payload
  57359. })[0] === axisModel;
  57360. }
  57361. function getCoverInfoList(axisModel) {
  57362. var axis = axisModel.axis;
  57363. return map(axisModel.activeIntervals, function (interval) {
  57364. return {
  57365. brushType: 'lineX',
  57366. panelId: 'pl',
  57367. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  57368. };
  57369. });
  57370. }
  57371. function getCoordSysModel(axisModel, ecModel) {
  57372. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  57373. }
  57374. /*
  57375. * Licensed to the Apache Software Foundation (ASF) under one
  57376. * or more contributor license agreements. See the NOTICE file
  57377. * distributed with this work for additional information
  57378. * regarding copyright ownership. The ASF licenses this file
  57379. * to you under the Apache License, Version 2.0 (the
  57380. * "License"); you may not use this file except in compliance
  57381. * with the License. You may obtain a copy of the License at
  57382. *
  57383. * http://www.apache.org/licenses/LICENSE-2.0
  57384. *
  57385. * Unless required by applicable law or agreed to in writing,
  57386. * software distributed under the License is distributed on an
  57387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57388. * KIND, either express or implied. See the License for the
  57389. * specific language governing permissions and limitations
  57390. * under the License.
  57391. */
  57392. /**
  57393. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57394. */
  57395. /*
  57396. * Licensed to the Apache Software Foundation (ASF) under one
  57397. * or more contributor license agreements. See the NOTICE file
  57398. * distributed with this work for additional information
  57399. * regarding copyright ownership. The ASF licenses this file
  57400. * to you under the Apache License, Version 2.0 (the
  57401. * "License"); you may not use this file except in compliance
  57402. * with the License. You may obtain a copy of the License at
  57403. *
  57404. * http://www.apache.org/licenses/LICENSE-2.0
  57405. *
  57406. * Unless required by applicable law or agreed to in writing,
  57407. * software distributed under the License is distributed on an
  57408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57409. * KIND, either express or implied. See the License for the
  57410. * specific language governing permissions and limitations
  57411. * under the License.
  57412. */
  57413. var actionInfo$1 = {
  57414. type: 'axisAreaSelect',
  57415. event: 'axisAreaSelected' // update: 'updateVisual'
  57416. };
  57417. function installParallelActions(registers) {
  57418. registers.registerAction(actionInfo$1, function (payload, ecModel) {
  57419. ecModel.eachComponent({
  57420. mainType: 'parallelAxis',
  57421. query: payload
  57422. }, function (parallelAxisModel) {
  57423. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  57424. });
  57425. });
  57426. /**
  57427. * @payload
  57428. */
  57429. registers.registerAction('parallelAxisExpand', function (payload, ecModel) {
  57430. ecModel.eachComponent({
  57431. mainType: 'parallel',
  57432. query: payload
  57433. }, function (parallelModel) {
  57434. parallelModel.setAxisExpand(payload);
  57435. });
  57436. });
  57437. }
  57438. var defaultAxisOption = {
  57439. type: 'value',
  57440. areaSelectStyle: {
  57441. width: 20,
  57442. borderWidth: 1,
  57443. borderColor: 'rgba(160,197,232)',
  57444. color: 'rgba(160,197,232)',
  57445. opacity: 0.3
  57446. },
  57447. realtime: true,
  57448. z: 10
  57449. };
  57450. function install$g(registers) {
  57451. registers.registerComponentView(ParallelView$1);
  57452. registers.registerComponentModel(ParallelModel);
  57453. registers.registerCoordinateSystem('parallel', parallelCoordSysCreator);
  57454. registers.registerPreprocessor(parallelPreprocessor);
  57455. registers.registerComponentModel(ParallelAxisModel);
  57456. registers.registerComponentView(ParallelAxisView);
  57457. axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption);
  57458. installParallelActions(registers);
  57459. }
  57460. function install$h(registers) {
  57461. use(install$g);
  57462. registers.registerChartView(ParallelView);
  57463. registers.registerSeriesModel(ParallelSeriesModel);
  57464. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual);
  57465. }
  57466. var SankeyPathShape =
  57467. /** @class */
  57468. function () {
  57469. function SankeyPathShape() {
  57470. this.x1 = 0;
  57471. this.y1 = 0;
  57472. this.x2 = 0;
  57473. this.y2 = 0;
  57474. this.cpx1 = 0;
  57475. this.cpy1 = 0;
  57476. this.cpx2 = 0;
  57477. this.cpy2 = 0;
  57478. this.extent = 0;
  57479. }
  57480. return SankeyPathShape;
  57481. }();
  57482. var SankeyPath =
  57483. /** @class */
  57484. function (_super) {
  57485. __extends(SankeyPath, _super);
  57486. function SankeyPath(opts) {
  57487. return _super.call(this, opts) || this;
  57488. }
  57489. SankeyPath.prototype.getDefaultShape = function () {
  57490. return new SankeyPathShape();
  57491. };
  57492. SankeyPath.prototype.buildPath = function (ctx, shape) {
  57493. var extent = shape.extent;
  57494. ctx.moveTo(shape.x1, shape.y1);
  57495. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  57496. if (shape.orient === 'vertical') {
  57497. ctx.lineTo(shape.x2 + extent, shape.y2);
  57498. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  57499. } else {
  57500. ctx.lineTo(shape.x2, shape.y2 + extent);
  57501. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  57502. }
  57503. ctx.closePath();
  57504. };
  57505. SankeyPath.prototype.highlight = function () {
  57506. enterEmphasis(this);
  57507. };
  57508. SankeyPath.prototype.downplay = function () {
  57509. leaveEmphasis(this);
  57510. };
  57511. return SankeyPath;
  57512. }(Path);
  57513. var SankeyView =
  57514. /** @class */
  57515. function (_super) {
  57516. __extends(SankeyView, _super);
  57517. function SankeyView() {
  57518. var _this = _super !== null && _super.apply(this, arguments) || this;
  57519. _this.type = SankeyView.type;
  57520. _this._focusAdjacencyDisabled = false;
  57521. return _this;
  57522. }
  57523. SankeyView.prototype.render = function (seriesModel, ecModel, api) {
  57524. var sankeyView = this;
  57525. var graph = seriesModel.getGraph();
  57526. var group = this.group;
  57527. var layoutInfo = seriesModel.layoutInfo; // view width
  57528. var width = layoutInfo.width; // view height
  57529. var height = layoutInfo.height;
  57530. var nodeData = seriesModel.getData();
  57531. var edgeData = seriesModel.getData('edge');
  57532. var orient = seriesModel.get('orient');
  57533. this._model = seriesModel;
  57534. group.removeAll();
  57535. group.x = layoutInfo.x;
  57536. group.y = layoutInfo.y; // generate a bezire Curve for each edge
  57537. graph.eachEdge(function (edge) {
  57538. var curve = new SankeyPath();
  57539. var ecData = getECData(curve);
  57540. ecData.dataIndex = edge.dataIndex;
  57541. ecData.seriesIndex = seriesModel.seriesIndex;
  57542. ecData.dataType = 'edge';
  57543. var edgeModel = edge.getModel();
  57544. var lineStyleModel = edgeModel.getModel('lineStyle');
  57545. var curvature = lineStyleModel.get('curveness');
  57546. var n1Layout = edge.node1.getLayout();
  57547. var node1Model = edge.node1.getModel();
  57548. var dragX1 = node1Model.get('localX');
  57549. var dragY1 = node1Model.get('localY');
  57550. var n2Layout = edge.node2.getLayout();
  57551. var node2Model = edge.node2.getModel();
  57552. var dragX2 = node2Model.get('localX');
  57553. var dragY2 = node2Model.get('localY');
  57554. var edgeLayout = edge.getLayout();
  57555. var x1;
  57556. var y1;
  57557. var x2;
  57558. var y2;
  57559. var cpx1;
  57560. var cpy1;
  57561. var cpx2;
  57562. var cpy2;
  57563. curve.shape.extent = Math.max(1, edgeLayout.dy);
  57564. curve.shape.orient = orient;
  57565. if (orient === 'vertical') {
  57566. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  57567. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  57568. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  57569. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  57570. cpx1 = x1;
  57571. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  57572. cpx2 = x2;
  57573. cpy2 = y1 * curvature + y2 * (1 - curvature);
  57574. } else {
  57575. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  57576. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  57577. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  57578. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  57579. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  57580. cpy1 = y1;
  57581. cpx2 = x1 * curvature + x2 * (1 - curvature);
  57582. cpy2 = y2;
  57583. }
  57584. curve.setShape({
  57585. x1: x1,
  57586. y1: y1,
  57587. x2: x2,
  57588. y2: y2,
  57589. cpx1: cpx1,
  57590. cpy1: cpy1,
  57591. cpx2: cpx2,
  57592. cpy2: cpy2
  57593. });
  57594. curve.useStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  57595. applyCurveStyle(curve.style, orient, edge);
  57596. var defaultEdgeLabelText = "" + edgeModel.get('value');
  57597. var edgeLabelStateModels = getLabelStatesModels(edgeModel, 'edgeLabel');
  57598. setLabelStyle(curve, edgeLabelStateModels, {
  57599. labelFetcher: {
  57600. getFormattedLabel: function (dataIndex, stateName, dataType, labelDimIndex, formatter, extendParams) {
  57601. return seriesModel.getFormattedLabel(dataIndex, stateName, 'edge', labelDimIndex, // ensure edgeLabel formatter is provided
  57602. // to prevent the inheritance from `label.formatter` of the series
  57603. retrieve3(formatter, edgeLabelStateModels.normal && edgeLabelStateModels.normal.get('formatter'), defaultEdgeLabelText), extendParams);
  57604. }
  57605. },
  57606. labelDataIndex: edge.dataIndex,
  57607. defaultText: defaultEdgeLabelText
  57608. });
  57609. curve.setTextConfig({
  57610. position: 'inside'
  57611. });
  57612. var emphasisModel = edgeModel.getModel('emphasis');
  57613. setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function (model) {
  57614. var style = model.getItemStyle();
  57615. applyCurveStyle(style, orient, edge);
  57616. return style;
  57617. });
  57618. group.add(curve);
  57619. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  57620. var focus = emphasisModel.get('focus');
  57621. toggleHoverEmphasis(curve, focus === 'adjacency' ? edge.getAdjacentDataIndices() : focus === 'trajectory' ? edge.getTrajectoryDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57622. }); // Generate a rect for each node
  57623. graph.eachNode(function (node) {
  57624. var layout = node.getLayout();
  57625. var itemModel = node.getModel();
  57626. var dragX = itemModel.get('localX');
  57627. var dragY = itemModel.get('localY');
  57628. var emphasisModel = itemModel.getModel('emphasis');
  57629. var rect = new Rect({
  57630. shape: {
  57631. x: dragX != null ? dragX * width : layout.x,
  57632. y: dragY != null ? dragY * height : layout.y,
  57633. width: layout.dx,
  57634. height: layout.dy
  57635. },
  57636. style: itemModel.getModel('itemStyle').getItemStyle(),
  57637. z2: 10
  57638. });
  57639. setLabelStyle(rect, getLabelStatesModels(itemModel), {
  57640. labelFetcher: {
  57641. getFormattedLabel: function (dataIndex, stateName) {
  57642. return seriesModel.getFormattedLabel(dataIndex, stateName, 'node');
  57643. }
  57644. },
  57645. labelDataIndex: node.dataIndex,
  57646. defaultText: node.id
  57647. });
  57648. rect.disableLabelAnimation = true;
  57649. rect.setStyle('fill', node.getVisual('color'));
  57650. rect.setStyle('decal', node.getVisual('style').decal);
  57651. setStatesStylesFromModel(rect, itemModel);
  57652. group.add(rect);
  57653. nodeData.setItemGraphicEl(node.dataIndex, rect);
  57654. getECData(rect).dataType = 'node';
  57655. var focus = emphasisModel.get('focus');
  57656. toggleHoverEmphasis(rect, focus === 'adjacency' ? node.getAdjacentDataIndices() : focus === 'trajectory' ? node.getTrajectoryDataIndices() : focus, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  57657. });
  57658. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  57659. var itemModel = nodeData.getItemModel(dataIndex);
  57660. if (itemModel.get('draggable')) {
  57661. el.drift = function (dx, dy) {
  57662. sankeyView._focusAdjacencyDisabled = true;
  57663. this.shape.x += dx;
  57664. this.shape.y += dy;
  57665. this.dirty();
  57666. api.dispatchAction({
  57667. type: 'dragNode',
  57668. seriesId: seriesModel.id,
  57669. dataIndex: nodeData.getRawIndex(dataIndex),
  57670. localX: this.shape.x / width,
  57671. localY: this.shape.y / height
  57672. });
  57673. };
  57674. el.ondragend = function () {
  57675. sankeyView._focusAdjacencyDisabled = false;
  57676. };
  57677. el.draggable = true;
  57678. el.cursor = 'move';
  57679. }
  57680. });
  57681. if (!this._data && seriesModel.isAnimationEnabled()) {
  57682. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  57683. group.removeClipPath();
  57684. }));
  57685. }
  57686. this._data = seriesModel.getData();
  57687. };
  57688. SankeyView.prototype.dispose = function () {};
  57689. SankeyView.type = 'sankey';
  57690. return SankeyView;
  57691. }(ChartView);
  57692. /**
  57693. * Special color, use source node color or target node color
  57694. * @param curveProps curve's style to parse
  57695. * @param orient direction
  57696. * @param edge current curve data
  57697. */
  57698. function applyCurveStyle(curveProps, orient, edge) {
  57699. switch (curveProps.fill) {
  57700. case 'source':
  57701. curveProps.fill = edge.node1.getVisual('color');
  57702. curveProps.decal = edge.node1.getVisual('style').decal;
  57703. break;
  57704. case 'target':
  57705. curveProps.fill = edge.node2.getVisual('color');
  57706. curveProps.decal = edge.node2.getVisual('style').decal;
  57707. break;
  57708. case 'gradient':
  57709. var sourceColor = edge.node1.getVisual('color');
  57710. var targetColor = edge.node2.getVisual('color');
  57711. if (isString(sourceColor) && isString(targetColor)) {
  57712. curveProps.fill = new LinearGradient(0, 0, +(orient === 'horizontal'), +(orient === 'vertical'), [{
  57713. color: sourceColor,
  57714. offset: 0
  57715. }, {
  57716. color: targetColor,
  57717. offset: 1
  57718. }]);
  57719. }
  57720. }
  57721. } // Add animation to the view
  57722. function createGridClipShape$1(rect, seriesModel, cb) {
  57723. var rectEl = new Rect({
  57724. shape: {
  57725. x: rect.x - 10,
  57726. y: rect.y - 10,
  57727. width: 0,
  57728. height: rect.height + 20
  57729. }
  57730. });
  57731. initProps(rectEl, {
  57732. shape: {
  57733. width: rect.width + 20
  57734. }
  57735. }, seriesModel, cb);
  57736. return rectEl;
  57737. }
  57738. var SankeySeriesModel =
  57739. /** @class */
  57740. function (_super) {
  57741. __extends(SankeySeriesModel, _super);
  57742. function SankeySeriesModel() {
  57743. var _this = _super !== null && _super.apply(this, arguments) || this;
  57744. _this.type = SankeySeriesModel.type;
  57745. return _this;
  57746. }
  57747. /**
  57748. * Init a graph data structure from data in option series
  57749. */
  57750. SankeySeriesModel.prototype.getInitialData = function (option, ecModel) {
  57751. var links = option.edges || option.links;
  57752. var nodes = option.data || option.nodes;
  57753. var levels = option.levels;
  57754. this.levelModels = [];
  57755. var levelModels = this.levelModels;
  57756. for (var i = 0; i < levels.length; i++) {
  57757. if (levels[i].depth != null && levels[i].depth >= 0) {
  57758. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  57759. } else {
  57760. if ("development" !== 'production') {
  57761. throw new Error('levels[i].depth is mandatory and should be natural number');
  57762. }
  57763. }
  57764. }
  57765. if (nodes && links) {
  57766. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  57767. return graph.data;
  57768. }
  57769. function beforeLink(nodeData, edgeData) {
  57770. nodeData.wrapMethod('getItemModel', function (model, idx) {
  57771. var seriesModel = model.parentModel;
  57772. var layout = seriesModel.getData().getItemLayout(idx);
  57773. if (layout) {
  57774. var nodeDepth = layout.depth;
  57775. var levelModel = seriesModel.levelModels[nodeDepth];
  57776. if (levelModel) {
  57777. model.parentModel = levelModel;
  57778. }
  57779. }
  57780. return model;
  57781. });
  57782. edgeData.wrapMethod('getItemModel', function (model, idx) {
  57783. var seriesModel = model.parentModel;
  57784. var edge = seriesModel.getGraph().getEdgeByIndex(idx);
  57785. var layout = edge.node1.getLayout();
  57786. if (layout) {
  57787. var depth = layout.depth;
  57788. var levelModel = seriesModel.levelModels[depth];
  57789. if (levelModel) {
  57790. model.parentModel = levelModel;
  57791. }
  57792. }
  57793. return model;
  57794. });
  57795. }
  57796. };
  57797. SankeySeriesModel.prototype.setNodePosition = function (dataIndex, localPosition) {
  57798. var nodes = this.option.data || this.option.nodes;
  57799. var dataItem = nodes[dataIndex];
  57800. dataItem.localX = localPosition[0];
  57801. dataItem.localY = localPosition[1];
  57802. };
  57803. /**
  57804. * Return the graphic data structure
  57805. *
  57806. * @return graphic data structure
  57807. */
  57808. SankeySeriesModel.prototype.getGraph = function () {
  57809. return this.getData().graph;
  57810. };
  57811. /**
  57812. * Get edge data of graphic data structure
  57813. *
  57814. * @return data structure of list
  57815. */
  57816. SankeySeriesModel.prototype.getEdgeData = function () {
  57817. return this.getGraph().edgeData;
  57818. };
  57819. SankeySeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  57820. function noValue(val) {
  57821. return isNaN(val) || val == null;
  57822. } // dataType === 'node' or empty do not show tooltip by default
  57823. if (dataType === 'edge') {
  57824. var params = this.getDataParams(dataIndex, dataType);
  57825. var rawDataOpt = params.data;
  57826. var edgeValue = params.value;
  57827. var edgeName = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  57828. return createTooltipMarkup('nameValue', {
  57829. name: edgeName,
  57830. value: edgeValue,
  57831. noValue: noValue(edgeValue)
  57832. });
  57833. } // dataType === 'node'
  57834. else {
  57835. var node = this.getGraph().getNodeByIndex(dataIndex);
  57836. var value = node.getLayout().value;
  57837. var name_1 = this.getDataParams(dataIndex, dataType).data.name;
  57838. return createTooltipMarkup('nameValue', {
  57839. name: name_1 != null ? name_1 + '' : null,
  57840. value: value,
  57841. noValue: noValue(value)
  57842. });
  57843. }
  57844. };
  57845. SankeySeriesModel.prototype.optionUpdated = function () {}; // Override Series.getDataParams()
  57846. SankeySeriesModel.prototype.getDataParams = function (dataIndex, dataType) {
  57847. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  57848. if (params.value == null && dataType === 'node') {
  57849. var node = this.getGraph().getNodeByIndex(dataIndex);
  57850. var nodeValue = node.getLayout().value;
  57851. params.value = nodeValue;
  57852. }
  57853. return params;
  57854. };
  57855. SankeySeriesModel.type = 'series.sankey';
  57856. SankeySeriesModel.defaultOption = {
  57857. // zlevel: 0,
  57858. z: 2,
  57859. coordinateSystem: 'view',
  57860. left: '5%',
  57861. top: '5%',
  57862. right: '20%',
  57863. bottom: '5%',
  57864. orient: 'horizontal',
  57865. nodeWidth: 20,
  57866. nodeGap: 8,
  57867. draggable: true,
  57868. layoutIterations: 32,
  57869. label: {
  57870. show: true,
  57871. position: 'right',
  57872. fontSize: 12
  57873. },
  57874. edgeLabel: {
  57875. show: false,
  57876. fontSize: 12
  57877. },
  57878. levels: [],
  57879. nodeAlign: 'justify',
  57880. lineStyle: {
  57881. color: '#314656',
  57882. opacity: 0.2,
  57883. curveness: 0.5
  57884. },
  57885. emphasis: {
  57886. label: {
  57887. show: true
  57888. },
  57889. lineStyle: {
  57890. opacity: 0.5
  57891. }
  57892. },
  57893. select: {
  57894. itemStyle: {
  57895. borderColor: '#212121'
  57896. }
  57897. },
  57898. animationEasing: 'linear',
  57899. animationDuration: 1000
  57900. };
  57901. return SankeySeriesModel;
  57902. }(SeriesModel);
  57903. function sankeyLayout(ecModel, api) {
  57904. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  57905. var nodeWidth = seriesModel.get('nodeWidth');
  57906. var nodeGap = seriesModel.get('nodeGap');
  57907. var layoutInfo = getViewRect$4(seriesModel, api);
  57908. seriesModel.layoutInfo = layoutInfo;
  57909. var width = layoutInfo.width;
  57910. var height = layoutInfo.height;
  57911. var graph = seriesModel.getGraph();
  57912. var nodes = graph.nodes;
  57913. var edges = graph.edges;
  57914. computeNodeValues(nodes);
  57915. var filteredNodes = filter(nodes, function (node) {
  57916. return node.getLayout().value === 0;
  57917. });
  57918. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  57919. var orient = seriesModel.get('orient');
  57920. var nodeAlign = seriesModel.get('nodeAlign');
  57921. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  57922. });
  57923. }
  57924. /**
  57925. * Get the layout position of the whole view
  57926. */
  57927. function getViewRect$4(seriesModel, api) {
  57928. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  57929. width: api.getWidth(),
  57930. height: api.getHeight()
  57931. });
  57932. }
  57933. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  57934. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  57935. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  57936. computeEdgeDepths(nodes, orient);
  57937. }
  57938. /**
  57939. * Compute the value of each node by summing the associated edge's value
  57940. */
  57941. function computeNodeValues(nodes) {
  57942. each(nodes, function (node) {
  57943. var value1 = sum(node.outEdges, getEdgeValue);
  57944. var value2 = sum(node.inEdges, getEdgeValue);
  57945. var nodeRawValue = node.getValue() || 0;
  57946. var value = Math.max(value1, value2, nodeRawValue);
  57947. node.setLayout({
  57948. value: value
  57949. }, true);
  57950. });
  57951. }
  57952. /**
  57953. * Compute the x-position for each node.
  57954. *
  57955. * Here we use Kahn algorithm to detect cycle when we traverse
  57956. * the node to computer the initial x position.
  57957. */
  57958. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  57959. // Used to mark whether the edge is deleted. if it is deleted,
  57960. // the value is 0, otherwise it is 1.
  57961. var remainEdges = []; // Storage each node's indegree.
  57962. var indegreeArr = []; // Used to storage the node with indegree is equal to 0.
  57963. var zeroIndegrees = [];
  57964. var nextTargetNode = [];
  57965. var x = 0; // let kx = 0;
  57966. for (var i = 0; i < edges.length; i++) {
  57967. remainEdges[i] = 1;
  57968. }
  57969. for (var i = 0; i < nodes.length; i++) {
  57970. indegreeArr[i] = nodes[i].inEdges.length;
  57971. if (indegreeArr[i] === 0) {
  57972. zeroIndegrees.push(nodes[i]);
  57973. }
  57974. }
  57975. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  57976. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  57977. // position of the nodes.
  57978. while (zeroIndegrees.length) {
  57979. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  57980. var node = zeroIndegrees[idx];
  57981. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  57982. var isItemDepth = item.depth != null && item.depth >= 0;
  57983. if (isItemDepth && item.depth > maxNodeDepth) {
  57984. maxNodeDepth = item.depth;
  57985. }
  57986. node.setLayout({
  57987. depth: isItemDepth ? item.depth : x
  57988. }, true);
  57989. orient === 'vertical' ? node.setLayout({
  57990. dy: nodeWidth
  57991. }, true) : node.setLayout({
  57992. dx: nodeWidth
  57993. }, true);
  57994. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  57995. var edge = node.outEdges[edgeIdx];
  57996. var indexEdge = edges.indexOf(edge);
  57997. remainEdges[indexEdge] = 0;
  57998. var targetNode = edge.node2;
  57999. var nodeIndex = nodes.indexOf(targetNode);
  58000. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  58001. nextTargetNode.push(targetNode);
  58002. }
  58003. }
  58004. }
  58005. ++x;
  58006. zeroIndegrees = nextTargetNode;
  58007. nextTargetNode = [];
  58008. }
  58009. for (var i = 0; i < remainEdges.length; i++) {
  58010. if (remainEdges[i] === 1) {
  58011. throw new Error('Sankey is a DAG, the original data has cycle!');
  58012. }
  58013. }
  58014. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  58015. if (nodeAlign && nodeAlign !== 'left') {
  58016. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  58017. }
  58018. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  58019. scaleNodeBreadths(nodes, kx, orient);
  58020. }
  58021. function isNodeDepth(node) {
  58022. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  58023. return item.depth != null && item.depth >= 0;
  58024. }
  58025. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  58026. if (nodeAlign === 'right') {
  58027. var nextSourceNode = [];
  58028. var remainNodes = nodes;
  58029. var nodeHeight = 0;
  58030. while (remainNodes.length) {
  58031. for (var i = 0; i < remainNodes.length; i++) {
  58032. var node = remainNodes[i];
  58033. node.setLayout({
  58034. skNodeHeight: nodeHeight
  58035. }, true);
  58036. for (var j = 0; j < node.inEdges.length; j++) {
  58037. var edge = node.inEdges[j];
  58038. if (nextSourceNode.indexOf(edge.node1) < 0) {
  58039. nextSourceNode.push(edge.node1);
  58040. }
  58041. }
  58042. }
  58043. remainNodes = nextSourceNode;
  58044. nextSourceNode = [];
  58045. ++nodeHeight;
  58046. }
  58047. each(nodes, function (node) {
  58048. if (!isNodeDepth(node)) {
  58049. node.setLayout({
  58050. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  58051. }, true);
  58052. }
  58053. });
  58054. } else if (nodeAlign === 'justify') {
  58055. moveSinksRight(nodes, maxDepth);
  58056. }
  58057. }
  58058. /**
  58059. * All the node without outEgdes are assigned maximum x-position and
  58060. * be aligned in the last column.
  58061. *
  58062. * @param nodes. node of sankey view.
  58063. * @param maxDepth. use to assign to node without outEdges as x-position.
  58064. */
  58065. function moveSinksRight(nodes, maxDepth) {
  58066. each(nodes, function (node) {
  58067. if (!isNodeDepth(node) && !node.outEdges.length) {
  58068. node.setLayout({
  58069. depth: maxDepth
  58070. }, true);
  58071. }
  58072. });
  58073. }
  58074. /**
  58075. * Scale node x-position to the width
  58076. *
  58077. * @param nodes node of sankey view
  58078. * @param kx multiple used to scale nodes
  58079. */
  58080. function scaleNodeBreadths(nodes, kx, orient) {
  58081. each(nodes, function (node) {
  58082. var nodeDepth = node.getLayout().depth * kx;
  58083. orient === 'vertical' ? node.setLayout({
  58084. y: nodeDepth
  58085. }, true) : node.setLayout({
  58086. x: nodeDepth
  58087. }, true);
  58088. });
  58089. }
  58090. /**
  58091. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  58092. *
  58093. * @param nodes node of sankey view
  58094. * @param edges edge of sankey view
  58095. * @param height the whole height of the area to draw the view
  58096. * @param nodeGap the vertical distance between two nodes
  58097. * in the same column.
  58098. * @param iterations the number of iterations for the algorithm
  58099. */
  58100. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  58101. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  58102. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  58103. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  58104. for (var alpha = 1; iterations > 0; iterations--) {
  58105. // 0.99 is a experience parameter, ensure that each iterations of
  58106. // changes as small as possible.
  58107. alpha *= 0.99;
  58108. relaxRightToLeft(nodesByBreadth, alpha, orient);
  58109. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  58110. relaxLeftToRight(nodesByBreadth, alpha, orient);
  58111. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  58112. }
  58113. }
  58114. function prepareNodesByBreadth(nodes, orient) {
  58115. var nodesByBreadth = [];
  58116. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  58117. var groupResult = groupData(nodes, function (node) {
  58118. return node.getLayout()[keyAttr];
  58119. });
  58120. groupResult.keys.sort(function (a, b) {
  58121. return a - b;
  58122. });
  58123. each(groupResult.keys, function (key) {
  58124. nodesByBreadth.push(groupResult.buckets.get(key));
  58125. });
  58126. return nodesByBreadth;
  58127. }
  58128. /**
  58129. * Compute the original y-position for each node
  58130. */
  58131. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  58132. var minKy = Infinity;
  58133. each(nodesByBreadth, function (nodes) {
  58134. var n = nodes.length;
  58135. var sum = 0;
  58136. each(nodes, function (node) {
  58137. sum += node.getLayout().value;
  58138. });
  58139. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  58140. if (ky < minKy) {
  58141. minKy = ky;
  58142. }
  58143. });
  58144. each(nodesByBreadth, function (nodes) {
  58145. each(nodes, function (node, i) {
  58146. var nodeDy = node.getLayout().value * minKy;
  58147. if (orient === 'vertical') {
  58148. node.setLayout({
  58149. x: i
  58150. }, true);
  58151. node.setLayout({
  58152. dx: nodeDy
  58153. }, true);
  58154. } else {
  58155. node.setLayout({
  58156. y: i
  58157. }, true);
  58158. node.setLayout({
  58159. dy: nodeDy
  58160. }, true);
  58161. }
  58162. });
  58163. });
  58164. each(edges, function (edge) {
  58165. var edgeDy = +edge.getValue() * minKy;
  58166. edge.setLayout({
  58167. dy: edgeDy
  58168. }, true);
  58169. });
  58170. }
  58171. /**
  58172. * Resolve the collision of initialized depth (y-position)
  58173. */
  58174. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  58175. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58176. each(nodesByBreadth, function (nodes) {
  58177. nodes.sort(function (a, b) {
  58178. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  58179. });
  58180. var nodeX;
  58181. var node;
  58182. var dy;
  58183. var y0 = 0;
  58184. var n = nodes.length;
  58185. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  58186. for (var i = 0; i < n; i++) {
  58187. node = nodes[i];
  58188. dy = y0 - node.getLayout()[keyAttr];
  58189. if (dy > 0) {
  58190. nodeX = node.getLayout()[keyAttr] + dy;
  58191. orient === 'vertical' ? node.setLayout({
  58192. x: nodeX
  58193. }, true) : node.setLayout({
  58194. y: nodeX
  58195. }, true);
  58196. }
  58197. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  58198. }
  58199. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  58200. dy = y0 - nodeGap - viewWidth;
  58201. if (dy > 0) {
  58202. nodeX = node.getLayout()[keyAttr] - dy;
  58203. orient === 'vertical' ? node.setLayout({
  58204. x: nodeX
  58205. }, true) : node.setLayout({
  58206. y: nodeX
  58207. }, true);
  58208. y0 = nodeX;
  58209. for (var i = n - 2; i >= 0; --i) {
  58210. node = nodes[i];
  58211. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  58212. if (dy > 0) {
  58213. nodeX = node.getLayout()[keyAttr] - dy;
  58214. orient === 'vertical' ? node.setLayout({
  58215. x: nodeX
  58216. }, true) : node.setLayout({
  58217. y: nodeX
  58218. }, true);
  58219. }
  58220. y0 = node.getLayout()[keyAttr];
  58221. }
  58222. }
  58223. });
  58224. }
  58225. /**
  58226. * Change the y-position of the nodes, except most the right side nodes
  58227. * @param nodesByBreadth
  58228. * @param alpha parameter used to adjust the nodes y-position
  58229. */
  58230. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  58231. each(nodesByBreadth.slice().reverse(), function (nodes) {
  58232. each(nodes, function (node) {
  58233. if (node.outEdges.length) {
  58234. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue);
  58235. if (isNaN(y)) {
  58236. var len = node.outEdges.length;
  58237. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  58238. }
  58239. if (orient === 'vertical') {
  58240. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58241. node.setLayout({
  58242. x: nodeX
  58243. }, true);
  58244. } else {
  58245. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58246. node.setLayout({
  58247. y: nodeY
  58248. }, true);
  58249. }
  58250. }
  58251. });
  58252. });
  58253. }
  58254. function weightedTarget(edge, orient) {
  58255. return center$1(edge.node2, orient) * edge.getValue();
  58256. }
  58257. function centerTarget(edge, orient) {
  58258. return center$1(edge.node2, orient);
  58259. }
  58260. function weightedSource(edge, orient) {
  58261. return center$1(edge.node1, orient) * edge.getValue();
  58262. }
  58263. function centerSource(edge, orient) {
  58264. return center$1(edge.node1, orient);
  58265. }
  58266. function center$1(node, orient) {
  58267. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  58268. }
  58269. function getEdgeValue(edge) {
  58270. return edge.getValue();
  58271. }
  58272. function sum(array, cb, orient) {
  58273. var sum = 0;
  58274. var len = array.length;
  58275. var i = -1;
  58276. while (++i < len) {
  58277. var value = +cb(array[i], orient);
  58278. if (!isNaN(value)) {
  58279. sum += value;
  58280. }
  58281. }
  58282. return sum;
  58283. }
  58284. /**
  58285. * Change the y-position of the nodes, except most the left side nodes
  58286. */
  58287. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  58288. each(nodesByBreadth, function (nodes) {
  58289. each(nodes, function (node) {
  58290. if (node.inEdges.length) {
  58291. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue);
  58292. if (isNaN(y)) {
  58293. var len = node.inEdges.length;
  58294. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  58295. }
  58296. if (orient === 'vertical') {
  58297. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  58298. node.setLayout({
  58299. x: nodeX
  58300. }, true);
  58301. } else {
  58302. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  58303. node.setLayout({
  58304. y: nodeY
  58305. }, true);
  58306. }
  58307. }
  58308. });
  58309. });
  58310. }
  58311. /**
  58312. * Compute the depth(y-position) of each edge
  58313. */
  58314. function computeEdgeDepths(nodes, orient) {
  58315. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  58316. each(nodes, function (node) {
  58317. node.outEdges.sort(function (a, b) {
  58318. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  58319. });
  58320. node.inEdges.sort(function (a, b) {
  58321. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  58322. });
  58323. });
  58324. each(nodes, function (node) {
  58325. var sy = 0;
  58326. var ty = 0;
  58327. each(node.outEdges, function (edge) {
  58328. edge.setLayout({
  58329. sy: sy
  58330. }, true);
  58331. sy += edge.getLayout().dy;
  58332. });
  58333. each(node.inEdges, function (edge) {
  58334. edge.setLayout({
  58335. ty: ty
  58336. }, true);
  58337. ty += edge.getLayout().dy;
  58338. });
  58339. });
  58340. }
  58341. function sankeyVisual(ecModel) {
  58342. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  58343. var graph = seriesModel.getGraph();
  58344. var nodes = graph.nodes;
  58345. var edges = graph.edges;
  58346. if (nodes.length) {
  58347. var minValue_1 = Infinity;
  58348. var maxValue_1 = -Infinity;
  58349. each(nodes, function (node) {
  58350. var nodeValue = node.getLayout().value;
  58351. if (nodeValue < minValue_1) {
  58352. minValue_1 = nodeValue;
  58353. }
  58354. if (nodeValue > maxValue_1) {
  58355. maxValue_1 = nodeValue;
  58356. }
  58357. });
  58358. each(nodes, function (node) {
  58359. var mapping = new VisualMapping({
  58360. type: 'color',
  58361. mappingMethod: 'linear',
  58362. dataExtent: [minValue_1, maxValue_1],
  58363. visual: seriesModel.get('color')
  58364. });
  58365. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  58366. var customColor = node.getModel().get(['itemStyle', 'color']);
  58367. if (customColor != null) {
  58368. node.setVisual('color', customColor);
  58369. node.setVisual('style', {
  58370. fill: customColor
  58371. });
  58372. } else {
  58373. node.setVisual('color', mapValueToColor);
  58374. node.setVisual('style', {
  58375. fill: mapValueToColor
  58376. });
  58377. }
  58378. });
  58379. }
  58380. if (edges.length) {
  58381. each(edges, function (edge) {
  58382. var edgeStyle = edge.getModel().get('lineStyle');
  58383. edge.setVisual('style', edgeStyle);
  58384. });
  58385. }
  58386. });
  58387. }
  58388. function install$i(registers) {
  58389. registers.registerChartView(SankeyView);
  58390. registers.registerSeriesModel(SankeySeriesModel);
  58391. registers.registerLayout(sankeyLayout);
  58392. registers.registerVisual(sankeyVisual);
  58393. registers.registerAction({
  58394. type: 'dragNode',
  58395. event: 'dragnode',
  58396. // here can only use 'update' now, other value is not support in echarts.
  58397. update: 'update'
  58398. }, function (payload, ecModel) {
  58399. ecModel.eachComponent({
  58400. mainType: 'series',
  58401. subType: 'sankey',
  58402. query: payload
  58403. }, function (seriesModel) {
  58404. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  58405. });
  58406. });
  58407. }
  58408. var WhiskerBoxCommonMixin =
  58409. /** @class */
  58410. function () {
  58411. function WhiskerBoxCommonMixin() {}
  58412. /**
  58413. * @override
  58414. */
  58415. WhiskerBoxCommonMixin.prototype.getInitialData = function (option, ecModel) {
  58416. // When both types of xAxis and yAxis are 'value', layout is
  58417. // needed to be specified by user. Otherwise, layout can be
  58418. // judged by which axis is category.
  58419. var ordinalMeta;
  58420. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  58421. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  58422. var xAxisType = xAxisModel.get('type');
  58423. var yAxisType = yAxisModel.get('type');
  58424. var addOrdinal; // FIXME
  58425. // Consider time axis.
  58426. if (xAxisType === 'category') {
  58427. option.layout = 'horizontal';
  58428. ordinalMeta = xAxisModel.getOrdinalMeta();
  58429. addOrdinal = true;
  58430. } else if (yAxisType === 'category') {
  58431. option.layout = 'vertical';
  58432. ordinalMeta = yAxisModel.getOrdinalMeta();
  58433. addOrdinal = true;
  58434. } else {
  58435. option.layout = option.layout || 'horizontal';
  58436. }
  58437. var coordDims = ['x', 'y'];
  58438. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  58439. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  58440. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  58441. var axisModels = [xAxisModel, yAxisModel];
  58442. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  58443. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  58444. var data = option.data; // Clone a new data for next setOption({}) usage.
  58445. // Avoid modifying current data will affect further update.
  58446. if (data && addOrdinal) {
  58447. var newOptionData_1 = [];
  58448. each(data, function (item, index) {
  58449. var newItem;
  58450. if (isArray(item)) {
  58451. newItem = item.slice(); // Modify current using data.
  58452. item.unshift(index);
  58453. } else if (isArray(item.value)) {
  58454. newItem = extend({}, item);
  58455. newItem.value = newItem.value.slice(); // Modify current using data.
  58456. item.value.unshift(index);
  58457. } else {
  58458. newItem = item;
  58459. }
  58460. newOptionData_1.push(newItem);
  58461. });
  58462. option.data = newOptionData_1;
  58463. }
  58464. var defaultValueDimensions = this.defaultValueDimensions;
  58465. var coordDimensions = [{
  58466. name: baseAxisDim,
  58467. type: getDimensionTypeByAxis(baseAxisType),
  58468. ordinalMeta: ordinalMeta,
  58469. otherDims: {
  58470. tooltip: false,
  58471. itemName: 0
  58472. },
  58473. dimsDef: ['base']
  58474. }, {
  58475. name: otherAxisDim,
  58476. type: getDimensionTypeByAxis(otherAxisType),
  58477. dimsDef: defaultValueDimensions.slice()
  58478. }];
  58479. return createSeriesDataSimply(this, {
  58480. coordDimensions: coordDimensions,
  58481. dimensionsCount: defaultValueDimensions.length + 1,
  58482. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  58483. });
  58484. };
  58485. /**
  58486. * If horizontal, base axis is x, otherwise y.
  58487. * @override
  58488. */
  58489. WhiskerBoxCommonMixin.prototype.getBaseAxis = function () {
  58490. var dim = this._baseAxisDim;
  58491. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  58492. };
  58493. return WhiskerBoxCommonMixin;
  58494. }();
  58495. var BoxplotSeriesModel =
  58496. /** @class */
  58497. function (_super) {
  58498. __extends(BoxplotSeriesModel, _super);
  58499. function BoxplotSeriesModel() {
  58500. var _this = _super !== null && _super.apply(this, arguments) || this;
  58501. _this.type = BoxplotSeriesModel.type; // TODO
  58502. // box width represents group size, so dimension should have 'size'.
  58503. /**
  58504. * @see <https://en.wikipedia.org/wiki/Box_plot>
  58505. * The meanings of 'min' and 'max' depend on user,
  58506. * and echarts do not need to know it.
  58507. * @readOnly
  58508. */
  58509. _this.defaultValueDimensions = [{
  58510. name: 'min',
  58511. defaultTooltip: true
  58512. }, {
  58513. name: 'Q1',
  58514. defaultTooltip: true
  58515. }, {
  58516. name: 'median',
  58517. defaultTooltip: true
  58518. }, {
  58519. name: 'Q3',
  58520. defaultTooltip: true
  58521. }, {
  58522. name: 'max',
  58523. defaultTooltip: true
  58524. }];
  58525. _this.visualDrawType = 'stroke';
  58526. return _this;
  58527. }
  58528. BoxplotSeriesModel.type = 'series.boxplot';
  58529. BoxplotSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  58530. BoxplotSeriesModel.defaultOption = {
  58531. // zlevel: 0,
  58532. z: 2,
  58533. coordinateSystem: 'cartesian2d',
  58534. legendHoverLink: true,
  58535. layout: null,
  58536. boxWidth: [7, 50],
  58537. itemStyle: {
  58538. color: '#fff',
  58539. borderWidth: 1
  58540. },
  58541. emphasis: {
  58542. scale: true,
  58543. itemStyle: {
  58544. borderWidth: 2,
  58545. shadowBlur: 5,
  58546. shadowOffsetX: 1,
  58547. shadowOffsetY: 1,
  58548. shadowColor: 'rgba(0,0,0,0.2)'
  58549. }
  58550. },
  58551. animationDuration: 800
  58552. };
  58553. return BoxplotSeriesModel;
  58554. }(SeriesModel);
  58555. mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, true);
  58556. var BoxplotView =
  58557. /** @class */
  58558. function (_super) {
  58559. __extends(BoxplotView, _super);
  58560. function BoxplotView() {
  58561. var _this = _super !== null && _super.apply(this, arguments) || this;
  58562. _this.type = BoxplotView.type;
  58563. return _this;
  58564. }
  58565. BoxplotView.prototype.render = function (seriesModel, ecModel, api) {
  58566. var data = seriesModel.getData();
  58567. var group = this.group;
  58568. var oldData = this._data; // There is no old data only when first rendering or switching from
  58569. // stream mode to normal mode, where previous elements should be removed.
  58570. if (!this._data) {
  58571. group.removeAll();
  58572. }
  58573. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  58574. data.diff(oldData).add(function (newIdx) {
  58575. if (data.hasValue(newIdx)) {
  58576. var itemLayout = data.getItemLayout(newIdx);
  58577. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  58578. data.setItemGraphicEl(newIdx, symbolEl);
  58579. group.add(symbolEl);
  58580. }
  58581. }).update(function (newIdx, oldIdx) {
  58582. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  58583. if (!data.hasValue(newIdx)) {
  58584. group.remove(symbolEl);
  58585. return;
  58586. }
  58587. var itemLayout = data.getItemLayout(newIdx);
  58588. if (!symbolEl) {
  58589. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  58590. } else {
  58591. saveOldStyle(symbolEl);
  58592. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  58593. }
  58594. group.add(symbolEl);
  58595. data.setItemGraphicEl(newIdx, symbolEl);
  58596. }).remove(function (oldIdx) {
  58597. var el = oldData.getItemGraphicEl(oldIdx);
  58598. el && group.remove(el);
  58599. }).execute();
  58600. this._data = data;
  58601. };
  58602. BoxplotView.prototype.remove = function (ecModel) {
  58603. var group = this.group;
  58604. var data = this._data;
  58605. this._data = null;
  58606. data && data.eachItemGraphicEl(function (el) {
  58607. el && group.remove(el);
  58608. });
  58609. };
  58610. BoxplotView.type = 'boxplot';
  58611. return BoxplotView;
  58612. }(ChartView);
  58613. var BoxPathShape =
  58614. /** @class */
  58615. function () {
  58616. function BoxPathShape() {}
  58617. return BoxPathShape;
  58618. }();
  58619. var BoxPath =
  58620. /** @class */
  58621. function (_super) {
  58622. __extends(BoxPath, _super);
  58623. function BoxPath(opts) {
  58624. var _this = _super.call(this, opts) || this;
  58625. _this.type = 'boxplotBoxPath';
  58626. return _this;
  58627. }
  58628. BoxPath.prototype.getDefaultShape = function () {
  58629. return new BoxPathShape();
  58630. };
  58631. BoxPath.prototype.buildPath = function (ctx, shape) {
  58632. var ends = shape.points;
  58633. var i = 0;
  58634. ctx.moveTo(ends[i][0], ends[i][1]);
  58635. i++;
  58636. for (; i < 4; i++) {
  58637. ctx.lineTo(ends[i][0], ends[i][1]);
  58638. }
  58639. ctx.closePath();
  58640. for (; i < ends.length; i++) {
  58641. ctx.moveTo(ends[i][0], ends[i][1]);
  58642. i++;
  58643. ctx.lineTo(ends[i][0], ends[i][1]);
  58644. }
  58645. };
  58646. return BoxPath;
  58647. }(Path);
  58648. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  58649. var ends = itemLayout.ends;
  58650. var el = new BoxPath({
  58651. shape: {
  58652. points: isInit ? transInit(ends, constDim, itemLayout) : ends
  58653. }
  58654. });
  58655. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  58656. return el;
  58657. }
  58658. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  58659. var seriesModel = data.hostModel;
  58660. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  58661. updateMethod(el, {
  58662. shape: {
  58663. points: itemLayout.ends
  58664. }
  58665. }, seriesModel, dataIndex);
  58666. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  58667. el.style.strokeNoScale = true;
  58668. el.z2 = 100;
  58669. var itemModel = data.getItemModel(dataIndex);
  58670. var emphasisModel = itemModel.getModel('emphasis');
  58671. setStatesStylesFromModel(el, itemModel);
  58672. toggleHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  58673. }
  58674. function transInit(points, dim, itemLayout) {
  58675. return map(points, function (point) {
  58676. point = point.slice();
  58677. point[dim] = itemLayout.initBaseline;
  58678. return point;
  58679. });
  58680. }
  58681. var each$6 = each;
  58682. function boxplotLayout(ecModel) {
  58683. var groupResult = groupSeriesByAxis(ecModel);
  58684. each$6(groupResult, function (groupItem) {
  58685. var seriesModels = groupItem.seriesModels;
  58686. if (!seriesModels.length) {
  58687. return;
  58688. }
  58689. calculateBase(groupItem);
  58690. each$6(seriesModels, function (seriesModel, idx) {
  58691. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  58692. });
  58693. });
  58694. }
  58695. /**
  58696. * Group series by axis.
  58697. */
  58698. function groupSeriesByAxis(ecModel) {
  58699. var result = [];
  58700. var axisList = [];
  58701. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  58702. var baseAxis = seriesModel.getBaseAxis();
  58703. var idx = indexOf(axisList, baseAxis);
  58704. if (idx < 0) {
  58705. idx = axisList.length;
  58706. axisList[idx] = baseAxis;
  58707. result[idx] = {
  58708. axis: baseAxis,
  58709. seriesModels: []
  58710. };
  58711. }
  58712. result[idx].seriesModels.push(seriesModel);
  58713. });
  58714. return result;
  58715. }
  58716. /**
  58717. * Calculate offset and box width for each series.
  58718. */
  58719. function calculateBase(groupItem) {
  58720. var baseAxis = groupItem.axis;
  58721. var seriesModels = groupItem.seriesModels;
  58722. var seriesCount = seriesModels.length;
  58723. var boxWidthList = groupItem.boxWidthList = [];
  58724. var boxOffsetList = groupItem.boxOffsetList = [];
  58725. var boundList = [];
  58726. var bandWidth;
  58727. if (baseAxis.type === 'category') {
  58728. bandWidth = baseAxis.getBandWidth();
  58729. } else {
  58730. var maxDataCount_1 = 0;
  58731. each$6(seriesModels, function (seriesModel) {
  58732. maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count());
  58733. });
  58734. var extent = baseAxis.getExtent();
  58735. bandWidth = Math.abs(extent[1] - extent[0]) / maxDataCount_1;
  58736. }
  58737. each$6(seriesModels, function (seriesModel) {
  58738. var boxWidthBound = seriesModel.get('boxWidth');
  58739. if (!isArray(boxWidthBound)) {
  58740. boxWidthBound = [boxWidthBound, boxWidthBound];
  58741. }
  58742. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  58743. });
  58744. var availableWidth = bandWidth * 0.8 - 2;
  58745. var boxGap = availableWidth / seriesCount * 0.3;
  58746. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  58747. var base = boxWidth / 2 - availableWidth / 2;
  58748. each$6(seriesModels, function (seriesModel, idx) {
  58749. boxOffsetList.push(base);
  58750. base += boxGap + boxWidth;
  58751. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  58752. });
  58753. }
  58754. /**
  58755. * Calculate points location for each series.
  58756. */
  58757. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  58758. var coordSys = seriesModel.coordinateSystem;
  58759. var data = seriesModel.getData();
  58760. var halfWidth = boxWidth / 2;
  58761. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  58762. var vDimIdx = 1 - cDimIdx;
  58763. var coordDims = ['x', 'y'];
  58764. var cDim = data.mapDimension(coordDims[cDimIdx]);
  58765. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  58766. if (cDim == null || vDims.length < 5) {
  58767. return;
  58768. }
  58769. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  58770. var axisDimVal = data.get(cDim, dataIndex);
  58771. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  58772. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  58773. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  58774. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  58775. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  58776. var ends = [];
  58777. addBodyEnd(ends, end2, false);
  58778. addBodyEnd(ends, end4, true);
  58779. ends.push(end1, end2, end5, end4);
  58780. layEndLine(ends, end1);
  58781. layEndLine(ends, end5);
  58782. layEndLine(ends, median);
  58783. data.setItemLayout(dataIndex, {
  58784. initBaseline: median[vDimIdx],
  58785. ends: ends
  58786. });
  58787. }
  58788. function getPoint(axisDimVal, dim, dataIndex) {
  58789. var val = data.get(dim, dataIndex);
  58790. var p = [];
  58791. p[cDimIdx] = axisDimVal;
  58792. p[vDimIdx] = val;
  58793. var point;
  58794. if (isNaN(axisDimVal) || isNaN(val)) {
  58795. point = [NaN, NaN];
  58796. } else {
  58797. point = coordSys.dataToPoint(p);
  58798. point[cDimIdx] += offset;
  58799. }
  58800. return point;
  58801. }
  58802. function addBodyEnd(ends, point, start) {
  58803. var point1 = point.slice();
  58804. var point2 = point.slice();
  58805. point1[cDimIdx] += halfWidth;
  58806. point2[cDimIdx] -= halfWidth;
  58807. start ? ends.push(point1, point2) : ends.push(point2, point1);
  58808. }
  58809. function layEndLine(ends, endCenter) {
  58810. var from = endCenter.slice();
  58811. var to = endCenter.slice();
  58812. from[cDimIdx] -= halfWidth;
  58813. to[cDimIdx] += halfWidth;
  58814. ends.push(from, to);
  58815. }
  58816. }
  58817. /**
  58818. * See:
  58819. * <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
  58820. * <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
  58821. *
  58822. * Helper method for preparing data.
  58823. *
  58824. * @param rawData like
  58825. * [
  58826. * [12,232,443], (raw data set for the first box)
  58827. * [3843,5545,1232], (raw data set for the second box)
  58828. * ...
  58829. * ]
  58830. * @param opt.boundIQR=1.5 Data less than min bound is outlier.
  58831. * default 1.5, means Q1 - 1.5 * (Q3 - Q1).
  58832. * If 'none'/0 passed, min bound will not be used.
  58833. */
  58834. function prepareBoxplotData(rawData, opt) {
  58835. opt = opt || {};
  58836. var boxData = [];
  58837. var outliers = [];
  58838. var boundIQR = opt.boundIQR;
  58839. var useExtreme = boundIQR === 'none' || boundIQR === 0;
  58840. for (var i = 0; i < rawData.length; i++) {
  58841. var ascList = asc(rawData[i].slice());
  58842. var Q1 = quantile(ascList, 0.25);
  58843. var Q2 = quantile(ascList, 0.5);
  58844. var Q3 = quantile(ascList, 0.75);
  58845. var min = ascList[0];
  58846. var max = ascList[ascList.length - 1];
  58847. var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
  58848. var low = useExtreme ? min : Math.max(min, Q1 - bound);
  58849. var high = useExtreme ? max : Math.min(max, Q3 + bound);
  58850. var itemNameFormatter = opt.itemNameFormatter;
  58851. var itemName = isFunction(itemNameFormatter) ? itemNameFormatter({
  58852. value: i
  58853. }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + '';
  58854. boxData.push([itemName, low, Q1, Q2, Q3, high]);
  58855. for (var j = 0; j < ascList.length; j++) {
  58856. var dataItem = ascList[j];
  58857. if (dataItem < low || dataItem > high) {
  58858. var outlier = [itemName, dataItem];
  58859. outliers.push(outlier);
  58860. }
  58861. }
  58862. }
  58863. return {
  58864. boxData: boxData,
  58865. outliers: outliers
  58866. };
  58867. }
  58868. var boxplotTransform = {
  58869. type: 'echarts:boxplot',
  58870. transform: function transform(params) {
  58871. var upstream = params.upstream;
  58872. if (upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS) {
  58873. var errMsg = '';
  58874. if ("development" !== 'production') {
  58875. errMsg = makePrintable('source data is not applicable for this boxplot transform. Expect number[][].');
  58876. }
  58877. throwError(errMsg);
  58878. }
  58879. var result = prepareBoxplotData(upstream.getRawData(), params.config);
  58880. return [{
  58881. dimensions: ['ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High'],
  58882. data: result.boxData
  58883. }, {
  58884. data: result.outliers
  58885. }];
  58886. }
  58887. };
  58888. function install$j(registers) {
  58889. registers.registerSeriesModel(BoxplotSeriesModel);
  58890. registers.registerChartView(BoxplotView);
  58891. registers.registerLayout(boxplotLayout);
  58892. registers.registerTransform(boxplotTransform);
  58893. }
  58894. var SKIP_PROPS = ['color', 'borderColor'];
  58895. var CandlestickView =
  58896. /** @class */
  58897. function (_super) {
  58898. __extends(CandlestickView, _super);
  58899. function CandlestickView() {
  58900. var _this = _super !== null && _super.apply(this, arguments) || this;
  58901. _this.type = CandlestickView.type;
  58902. return _this;
  58903. }
  58904. CandlestickView.prototype.render = function (seriesModel, ecModel, api) {
  58905. // If there is clipPath created in large mode. Remove it.
  58906. this.group.removeClipPath(); // Clear previously rendered progressive elements.
  58907. this._progressiveEls = null;
  58908. this._updateDrawMode(seriesModel);
  58909. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  58910. };
  58911. CandlestickView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  58912. this._clear();
  58913. this._updateDrawMode(seriesModel);
  58914. };
  58915. CandlestickView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  58916. this._progressiveEls = [];
  58917. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  58918. };
  58919. CandlestickView.prototype.eachRendered = function (cb) {
  58920. traverseElements(this._progressiveEls || this.group, cb);
  58921. };
  58922. CandlestickView.prototype._updateDrawMode = function (seriesModel) {
  58923. var isLargeDraw = seriesModel.pipelineContext.large;
  58924. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  58925. this._isLargeDraw = isLargeDraw;
  58926. this._clear();
  58927. }
  58928. };
  58929. CandlestickView.prototype._renderNormal = function (seriesModel) {
  58930. var data = seriesModel.getData();
  58931. var oldData = this._data;
  58932. var group = this.group;
  58933. var isSimpleBox = data.getLayout('isSimpleBox');
  58934. var needsClip = seriesModel.get('clip', true);
  58935. var coord = seriesModel.coordinateSystem;
  58936. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  58937. // stream mode to normal mode, where previous elements should be removed.
  58938. if (!this._data) {
  58939. group.removeAll();
  58940. }
  58941. data.diff(oldData).add(function (newIdx) {
  58942. if (data.hasValue(newIdx)) {
  58943. var itemLayout = data.getItemLayout(newIdx);
  58944. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58945. return;
  58946. }
  58947. var el = createNormalBox$1(itemLayout, newIdx, true);
  58948. initProps(el, {
  58949. shape: {
  58950. points: itemLayout.ends
  58951. }
  58952. }, seriesModel, newIdx);
  58953. setBoxCommon(el, data, newIdx, isSimpleBox);
  58954. group.add(el);
  58955. data.setItemGraphicEl(newIdx, el);
  58956. }
  58957. }).update(function (newIdx, oldIdx) {
  58958. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  58959. if (!data.hasValue(newIdx)) {
  58960. group.remove(el);
  58961. return;
  58962. }
  58963. var itemLayout = data.getItemLayout(newIdx);
  58964. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  58965. group.remove(el);
  58966. return;
  58967. }
  58968. if (!el) {
  58969. el = createNormalBox$1(itemLayout);
  58970. } else {
  58971. updateProps(el, {
  58972. shape: {
  58973. points: itemLayout.ends
  58974. }
  58975. }, seriesModel, newIdx);
  58976. saveOldStyle(el);
  58977. }
  58978. setBoxCommon(el, data, newIdx, isSimpleBox);
  58979. group.add(el);
  58980. data.setItemGraphicEl(newIdx, el);
  58981. }).remove(function (oldIdx) {
  58982. var el = oldData.getItemGraphicEl(oldIdx);
  58983. el && group.remove(el);
  58984. }).execute();
  58985. this._data = data;
  58986. };
  58987. CandlestickView.prototype._renderLarge = function (seriesModel) {
  58988. this._clear();
  58989. createLarge$1(seriesModel, this.group);
  58990. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  58991. if (clipPath) {
  58992. this.group.setClipPath(clipPath);
  58993. } else {
  58994. this.group.removeClipPath();
  58995. }
  58996. };
  58997. CandlestickView.prototype._incrementalRenderNormal = function (params, seriesModel) {
  58998. var data = seriesModel.getData();
  58999. var isSimpleBox = data.getLayout('isSimpleBox');
  59000. var dataIndex;
  59001. while ((dataIndex = params.next()) != null) {
  59002. var itemLayout = data.getItemLayout(dataIndex);
  59003. var el = createNormalBox$1(itemLayout);
  59004. setBoxCommon(el, data, dataIndex, isSimpleBox);
  59005. el.incremental = true;
  59006. this.group.add(el);
  59007. this._progressiveEls.push(el);
  59008. }
  59009. };
  59010. CandlestickView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  59011. createLarge$1(seriesModel, this.group, this._progressiveEls, true);
  59012. };
  59013. CandlestickView.prototype.remove = function (ecModel) {
  59014. this._clear();
  59015. };
  59016. CandlestickView.prototype._clear = function () {
  59017. this.group.removeAll();
  59018. this._data = null;
  59019. };
  59020. CandlestickView.type = 'candlestick';
  59021. return CandlestickView;
  59022. }(ChartView);
  59023. var NormalBoxPathShape =
  59024. /** @class */
  59025. function () {
  59026. function NormalBoxPathShape() {}
  59027. return NormalBoxPathShape;
  59028. }();
  59029. var NormalBoxPath =
  59030. /** @class */
  59031. function (_super) {
  59032. __extends(NormalBoxPath, _super);
  59033. function NormalBoxPath(opts) {
  59034. var _this = _super.call(this, opts) || this;
  59035. _this.type = 'normalCandlestickBox';
  59036. return _this;
  59037. }
  59038. NormalBoxPath.prototype.getDefaultShape = function () {
  59039. return new NormalBoxPathShape();
  59040. };
  59041. NormalBoxPath.prototype.buildPath = function (ctx, shape) {
  59042. var ends = shape.points;
  59043. if (this.__simpleBox) {
  59044. ctx.moveTo(ends[4][0], ends[4][1]);
  59045. ctx.lineTo(ends[6][0], ends[6][1]);
  59046. } else {
  59047. ctx.moveTo(ends[0][0], ends[0][1]);
  59048. ctx.lineTo(ends[1][0], ends[1][1]);
  59049. ctx.lineTo(ends[2][0], ends[2][1]);
  59050. ctx.lineTo(ends[3][0], ends[3][1]);
  59051. ctx.closePath();
  59052. ctx.moveTo(ends[4][0], ends[4][1]);
  59053. ctx.lineTo(ends[5][0], ends[5][1]);
  59054. ctx.moveTo(ends[6][0], ends[6][1]);
  59055. ctx.lineTo(ends[7][0], ends[7][1]);
  59056. }
  59057. };
  59058. return NormalBoxPath;
  59059. }(Path);
  59060. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  59061. var ends = itemLayout.ends;
  59062. return new NormalBoxPath({
  59063. shape: {
  59064. points: isInit ? transInit$1(ends, itemLayout) : ends
  59065. },
  59066. z2: 100
  59067. });
  59068. }
  59069. function isNormalBoxClipped(clipArea, itemLayout) {
  59070. var clipped = true;
  59071. for (var i = 0; i < itemLayout.ends.length; i++) {
  59072. // If any point are in the region.
  59073. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  59074. clipped = false;
  59075. break;
  59076. }
  59077. }
  59078. return clipped;
  59079. }
  59080. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  59081. var itemModel = data.getItemModel(dataIndex);
  59082. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  59083. el.style.strokeNoScale = true;
  59084. el.__simpleBox = isSimpleBox;
  59085. setStatesStylesFromModel(el, itemModel);
  59086. }
  59087. function transInit$1(points, itemLayout) {
  59088. return map(points, function (point) {
  59089. point = point.slice();
  59090. point[1] = itemLayout.initBaseline;
  59091. return point;
  59092. });
  59093. }
  59094. var LargeBoxPathShape =
  59095. /** @class */
  59096. function () {
  59097. function LargeBoxPathShape() {}
  59098. return LargeBoxPathShape;
  59099. }();
  59100. var LargeBoxPath =
  59101. /** @class */
  59102. function (_super) {
  59103. __extends(LargeBoxPath, _super);
  59104. function LargeBoxPath(opts) {
  59105. var _this = _super.call(this, opts) || this;
  59106. _this.type = 'largeCandlestickBox';
  59107. return _this;
  59108. }
  59109. LargeBoxPath.prototype.getDefaultShape = function () {
  59110. return new LargeBoxPathShape();
  59111. };
  59112. LargeBoxPath.prototype.buildPath = function (ctx, shape) {
  59113. // Drawing lines is more efficient than drawing
  59114. // a whole line or drawing rects.
  59115. var points = shape.points;
  59116. for (var i = 0; i < points.length;) {
  59117. if (this.__sign === points[i++]) {
  59118. var x = points[i++];
  59119. ctx.moveTo(x, points[i++]);
  59120. ctx.lineTo(x, points[i++]);
  59121. } else {
  59122. i += 3;
  59123. }
  59124. }
  59125. };
  59126. return LargeBoxPath;
  59127. }(Path);
  59128. function createLarge$1(seriesModel, group, progressiveEls, incremental) {
  59129. var data = seriesModel.getData();
  59130. var largePoints = data.getLayout('largePoints');
  59131. var elP = new LargeBoxPath({
  59132. shape: {
  59133. points: largePoints
  59134. },
  59135. __sign: 1,
  59136. ignoreCoarsePointer: true
  59137. });
  59138. group.add(elP);
  59139. var elN = new LargeBoxPath({
  59140. shape: {
  59141. points: largePoints
  59142. },
  59143. __sign: -1,
  59144. ignoreCoarsePointer: true
  59145. });
  59146. group.add(elN);
  59147. var elDoji = new LargeBoxPath({
  59148. shape: {
  59149. points: largePoints
  59150. },
  59151. __sign: 0,
  59152. ignoreCoarsePointer: true
  59153. });
  59154. group.add(elDoji);
  59155. setLargeStyle(1, elP, seriesModel);
  59156. setLargeStyle(-1, elN, seriesModel);
  59157. setLargeStyle(0, elDoji, seriesModel);
  59158. if (incremental) {
  59159. elP.incremental = true;
  59160. elN.incremental = true;
  59161. }
  59162. if (progressiveEls) {
  59163. progressiveEls.push(elP, elN);
  59164. }
  59165. }
  59166. function setLargeStyle(sign, el, seriesModel, data) {
  59167. // TODO put in visual?
  59168. var borderColor = seriesModel.get(['itemStyle', sign > 0 ? 'borderColor' : 'borderColor0']) // Use color for border color by default.
  59169. || seriesModel.get(['itemStyle', sign > 0 ? 'color' : 'color0']);
  59170. if (sign === 0) {
  59171. borderColor = seriesModel.get(['itemStyle', 'borderColorDoji']);
  59172. } // Color must be excluded.
  59173. // Because symbol provide setColor individually to set fill and stroke
  59174. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS);
  59175. el.useStyle(itemStyle);
  59176. el.style.fill = null;
  59177. el.style.stroke = borderColor;
  59178. }
  59179. var CandlestickSeriesModel =
  59180. /** @class */
  59181. function (_super) {
  59182. __extends(CandlestickSeriesModel, _super);
  59183. function CandlestickSeriesModel() {
  59184. var _this = _super !== null && _super.apply(this, arguments) || this;
  59185. _this.type = CandlestickSeriesModel.type;
  59186. _this.defaultValueDimensions = [{
  59187. name: 'open',
  59188. defaultTooltip: true
  59189. }, {
  59190. name: 'close',
  59191. defaultTooltip: true
  59192. }, {
  59193. name: 'lowest',
  59194. defaultTooltip: true
  59195. }, {
  59196. name: 'highest',
  59197. defaultTooltip: true
  59198. }];
  59199. return _this;
  59200. }
  59201. /**
  59202. * Get dimension for shadow in dataZoom
  59203. * @return dimension name
  59204. */
  59205. CandlestickSeriesModel.prototype.getShadowDim = function () {
  59206. return 'open';
  59207. };
  59208. CandlestickSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59209. var itemLayout = data.getItemLayout(dataIndex);
  59210. return itemLayout && selectors.rect(itemLayout.brushRect);
  59211. };
  59212. CandlestickSeriesModel.type = 'series.candlestick';
  59213. CandlestickSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  59214. CandlestickSeriesModel.defaultOption = {
  59215. // zlevel: 0,
  59216. z: 2,
  59217. coordinateSystem: 'cartesian2d',
  59218. legendHoverLink: true,
  59219. // xAxisIndex: 0,
  59220. // yAxisIndex: 0,
  59221. layout: null,
  59222. clip: true,
  59223. itemStyle: {
  59224. color: '#eb5454',
  59225. color0: '#47b262',
  59226. borderColor: '#eb5454',
  59227. borderColor0: '#47b262',
  59228. borderColorDoji: null,
  59229. // borderColor: '#d24040',
  59230. // borderColor0: '#398f4f',
  59231. borderWidth: 1
  59232. },
  59233. emphasis: {
  59234. scale: true,
  59235. itemStyle: {
  59236. borderWidth: 2
  59237. }
  59238. },
  59239. barMaxWidth: null,
  59240. barMinWidth: null,
  59241. barWidth: null,
  59242. large: true,
  59243. largeThreshold: 600,
  59244. progressive: 3e3,
  59245. progressiveThreshold: 1e4,
  59246. progressiveChunkMode: 'mod',
  59247. animationEasing: 'linear',
  59248. animationDuration: 300
  59249. };
  59250. return CandlestickSeriesModel;
  59251. }(SeriesModel);
  59252. mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, true);
  59253. function candlestickPreprocessor(option) {
  59254. if (!option || !isArray(option.series)) {
  59255. return;
  59256. } // Translate 'k' to 'candlestick'.
  59257. each(option.series, function (seriesItem) {
  59258. if (isObject(seriesItem) && seriesItem.type === 'k') {
  59259. seriesItem.type = 'candlestick';
  59260. }
  59261. });
  59262. }
  59263. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  59264. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  59265. var dojiBorderColorQuery = ['itemStyle', 'borderColorDoji'];
  59266. var positiveColorQuery = ['itemStyle', 'color'];
  59267. var negativeColorQuery = ['itemStyle', 'color0'];
  59268. var candlestickVisual = {
  59269. seriesType: 'candlestick',
  59270. plan: createRenderPlanner(),
  59271. // For legend.
  59272. performRawSeries: true,
  59273. reset: function (seriesModel, ecModel) {
  59274. function getColor(sign, model) {
  59275. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  59276. }
  59277. function getBorderColor(sign, model) {
  59278. return model.get(sign === 0 ? dojiBorderColorQuery : sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  59279. } // Only visible series has each data be visual encoded
  59280. if (ecModel.isSeriesFiltered(seriesModel)) {
  59281. return;
  59282. }
  59283. var isLargeRender = seriesModel.pipelineContext.large;
  59284. return !isLargeRender && {
  59285. progress: function (params, data) {
  59286. var dataIndex;
  59287. while ((dataIndex = params.next()) != null) {
  59288. var itemModel = data.getItemModel(dataIndex);
  59289. var sign = data.getItemLayout(dataIndex).sign;
  59290. var style = itemModel.getItemStyle();
  59291. style.fill = getColor(sign, itemModel);
  59292. style.stroke = getBorderColor(sign, itemModel) || style.fill;
  59293. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  59294. extend(existsStyle, style);
  59295. }
  59296. }
  59297. };
  59298. }
  59299. };
  59300. var candlestickLayout = {
  59301. seriesType: 'candlestick',
  59302. plan: createRenderPlanner(),
  59303. reset: function (seriesModel) {
  59304. var coordSys = seriesModel.coordinateSystem;
  59305. var data = seriesModel.getData();
  59306. var candleWidth = calculateCandleWidth(seriesModel, data);
  59307. var cDimIdx = 0;
  59308. var vDimIdx = 1;
  59309. var coordDims = ['x', 'y'];
  59310. var cDimI = data.getDimensionIndex(data.mapDimension(coordDims[cDimIdx]));
  59311. var vDimsI = map(data.mapDimensionsAll(coordDims[vDimIdx]), data.getDimensionIndex, data);
  59312. var openDimI = vDimsI[0];
  59313. var closeDimI = vDimsI[1];
  59314. var lowestDimI = vDimsI[2];
  59315. var highestDimI = vDimsI[3];
  59316. data.setLayout({
  59317. candleWidth: candleWidth,
  59318. // The value is experimented visually.
  59319. isSimpleBox: candleWidth <= 1.3
  59320. });
  59321. if (cDimI < 0 || vDimsI.length < 4) {
  59322. return;
  59323. }
  59324. return {
  59325. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  59326. };
  59327. function normalProgress(params, data) {
  59328. var dataIndex;
  59329. var store = data.getStore();
  59330. while ((dataIndex = params.next()) != null) {
  59331. var axisDimVal = store.get(cDimI, dataIndex);
  59332. var openVal = store.get(openDimI, dataIndex);
  59333. var closeVal = store.get(closeDimI, dataIndex);
  59334. var lowestVal = store.get(lowestDimI, dataIndex);
  59335. var highestVal = store.get(highestDimI, dataIndex);
  59336. var ocLow = Math.min(openVal, closeVal);
  59337. var ocHigh = Math.max(openVal, closeVal);
  59338. var ocLowPoint = getPoint(ocLow, axisDimVal);
  59339. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  59340. var lowestPoint = getPoint(lowestVal, axisDimVal);
  59341. var highestPoint = getPoint(highestVal, axisDimVal);
  59342. var ends = [];
  59343. addBodyEnd(ends, ocHighPoint, 0);
  59344. addBodyEnd(ends, ocLowPoint, 1);
  59345. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  59346. var itemModel = data.getItemModel(dataIndex);
  59347. var hasDojiColor = !!itemModel.get(['itemStyle', 'borderColorDoji']);
  59348. data.setItemLayout(dataIndex, {
  59349. sign: getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor),
  59350. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  59351. ends: ends,
  59352. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  59353. });
  59354. }
  59355. function getPoint(val, axisDimVal) {
  59356. var p = [];
  59357. p[cDimIdx] = axisDimVal;
  59358. p[vDimIdx] = val;
  59359. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  59360. }
  59361. function addBodyEnd(ends, point, start) {
  59362. var point1 = point.slice();
  59363. var point2 = point.slice();
  59364. point1[cDimIdx] = subPixelOptimize$1(point1[cDimIdx] + candleWidth / 2, 1, false);
  59365. point2[cDimIdx] = subPixelOptimize$1(point2[cDimIdx] - candleWidth / 2, 1, true);
  59366. start ? ends.push(point1, point2) : ends.push(point2, point1);
  59367. }
  59368. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  59369. var pmin = getPoint(lowestVal, axisDimVal);
  59370. var pmax = getPoint(highestVal, axisDimVal);
  59371. pmin[cDimIdx] -= candleWidth / 2;
  59372. pmax[cDimIdx] -= candleWidth / 2;
  59373. return {
  59374. x: pmin[0],
  59375. y: pmin[1],
  59376. width: candleWidth ,
  59377. height: pmax[1] - pmin[1]
  59378. };
  59379. }
  59380. function subPixelOptimizePoint(point) {
  59381. point[cDimIdx] = subPixelOptimize$1(point[cDimIdx], 1);
  59382. return point;
  59383. }
  59384. }
  59385. function largeProgress(params, data) {
  59386. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  59387. var points = createFloat32Array(params.count * 4);
  59388. var offset = 0;
  59389. var point;
  59390. var tmpIn = [];
  59391. var tmpOut = [];
  59392. var dataIndex;
  59393. var store = data.getStore();
  59394. var hasDojiColor = !!seriesModel.get(['itemStyle', 'borderColorDoji']);
  59395. while ((dataIndex = params.next()) != null) {
  59396. var axisDimVal = store.get(cDimI, dataIndex);
  59397. var openVal = store.get(openDimI, dataIndex);
  59398. var closeVal = store.get(closeDimI, dataIndex);
  59399. var lowestVal = store.get(lowestDimI, dataIndex);
  59400. var highestVal = store.get(highestDimI, dataIndex);
  59401. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  59402. points[offset++] = NaN;
  59403. offset += 3;
  59404. continue;
  59405. }
  59406. points[offset++] = getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor);
  59407. tmpIn[cDimIdx] = axisDimVal;
  59408. tmpIn[vDimIdx] = lowestVal;
  59409. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59410. points[offset++] = point ? point[0] : NaN;
  59411. points[offset++] = point ? point[1] : NaN;
  59412. tmpIn[vDimIdx] = highestVal;
  59413. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  59414. points[offset++] = point ? point[1] : NaN;
  59415. }
  59416. data.setLayout('largePoints', points);
  59417. }
  59418. }
  59419. };
  59420. /**
  59421. * Get the sign of a single data.
  59422. *
  59423. * @returns 0 for doji with hasDojiColor: true,
  59424. * 1 for positive,
  59425. * -1 for negative.
  59426. */
  59427. function getSign(store, dataIndex, openVal, closeVal, closeDimI, hasDojiColor) {
  59428. var sign;
  59429. if (openVal > closeVal) {
  59430. sign = -1;
  59431. } else if (openVal < closeVal) {
  59432. sign = 1;
  59433. } else {
  59434. sign = hasDojiColor // When doji color is set, use it instead of color/color0.
  59435. ? 0 : dataIndex > 0 // If close === open, compare with close of last record
  59436. ? store.get(closeDimI, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  59437. 1;
  59438. }
  59439. return sign;
  59440. }
  59441. function calculateCandleWidth(seriesModel, data) {
  59442. var baseAxis = seriesModel.getBaseAxis();
  59443. var extent;
  59444. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  59445. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  59446. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  59447. var barWidth = seriesModel.get('barWidth');
  59448. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  59449. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  59450. }
  59451. function install$k(registers) {
  59452. registers.registerChartView(CandlestickView);
  59453. registers.registerSeriesModel(CandlestickSeriesModel);
  59454. registers.registerPreprocessor(candlestickPreprocessor);
  59455. registers.registerVisual(candlestickVisual);
  59456. registers.registerLayout(candlestickLayout);
  59457. }
  59458. function updateRipplePath(rippleGroup, effectCfg) {
  59459. var color = effectCfg.rippleEffectColor || effectCfg.color;
  59460. rippleGroup.eachChild(function (ripplePath) {
  59461. ripplePath.attr({
  59462. z: effectCfg.z,
  59463. zlevel: effectCfg.zlevel,
  59464. style: {
  59465. stroke: effectCfg.brushType === 'stroke' ? color : null,
  59466. fill: effectCfg.brushType === 'fill' ? color : null
  59467. }
  59468. });
  59469. });
  59470. }
  59471. var EffectSymbol =
  59472. /** @class */
  59473. function (_super) {
  59474. __extends(EffectSymbol, _super);
  59475. function EffectSymbol(data, idx) {
  59476. var _this = _super.call(this) || this;
  59477. var symbol = new Symbol(data, idx);
  59478. var rippleGroup = new Group();
  59479. _this.add(symbol);
  59480. _this.add(rippleGroup);
  59481. _this.updateData(data, idx);
  59482. return _this;
  59483. }
  59484. EffectSymbol.prototype.stopEffectAnimation = function () {
  59485. this.childAt(1).removeAll();
  59486. };
  59487. EffectSymbol.prototype.startEffectAnimation = function (effectCfg) {
  59488. var symbolType = effectCfg.symbolType;
  59489. var color = effectCfg.color;
  59490. var rippleNumber = effectCfg.rippleNumber;
  59491. var rippleGroup = this.childAt(1);
  59492. for (var i = 0; i < rippleNumber; i++) {
  59493. // If width/height are set too small (e.g., set to 1) on ios10
  59494. // and macOS Sierra, a circle stroke become a rect, no matter what
  59495. // the scale is set. So we set width/height as 2. See #4136.
  59496. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  59497. ripplePath.attr({
  59498. style: {
  59499. strokeNoScale: true
  59500. },
  59501. z2: 99,
  59502. silent: true,
  59503. scaleX: 0.5,
  59504. scaleY: 0.5
  59505. });
  59506. var delay = -i / rippleNumber * effectCfg.period + effectCfg.effectOffset;
  59507. ripplePath.animate('', true).when(effectCfg.period, {
  59508. scaleX: effectCfg.rippleScale / 2,
  59509. scaleY: effectCfg.rippleScale / 2
  59510. }).delay(delay).start();
  59511. ripplePath.animateStyle(true).when(effectCfg.period, {
  59512. opacity: 0
  59513. }).delay(delay).start();
  59514. rippleGroup.add(ripplePath);
  59515. }
  59516. updateRipplePath(rippleGroup, effectCfg);
  59517. };
  59518. /**
  59519. * Update effect symbol
  59520. */
  59521. EffectSymbol.prototype.updateEffectAnimation = function (effectCfg) {
  59522. var oldEffectCfg = this._effectCfg;
  59523. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  59524. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale', 'rippleNumber'];
  59525. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  59526. var propName = DIFFICULT_PROPS[i];
  59527. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  59528. this.stopEffectAnimation();
  59529. this.startEffectAnimation(effectCfg);
  59530. return;
  59531. }
  59532. }
  59533. updateRipplePath(rippleGroup, effectCfg);
  59534. };
  59535. /**
  59536. * Highlight symbol
  59537. */
  59538. EffectSymbol.prototype.highlight = function () {
  59539. enterEmphasis(this);
  59540. };
  59541. /**
  59542. * Downplay symbol
  59543. */
  59544. EffectSymbol.prototype.downplay = function () {
  59545. leaveEmphasis(this);
  59546. };
  59547. EffectSymbol.prototype.getSymbolType = function () {
  59548. var symbol = this.childAt(0);
  59549. return symbol && symbol.getSymbolType();
  59550. };
  59551. /**
  59552. * Update symbol properties
  59553. */
  59554. EffectSymbol.prototype.updateData = function (data, idx) {
  59555. var _this = this;
  59556. var seriesModel = data.hostModel;
  59557. this.childAt(0).updateData(data, idx);
  59558. var rippleGroup = this.childAt(1);
  59559. var itemModel = data.getItemModel(idx);
  59560. var symbolType = data.getItemVisual(idx, 'symbol');
  59561. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  59562. var symbolStyle = data.getItemVisual(idx, 'style');
  59563. var color = symbolStyle && symbolStyle.fill;
  59564. var emphasisModel = itemModel.getModel('emphasis');
  59565. rippleGroup.setScale(symbolSize);
  59566. rippleGroup.traverse(function (ripplePath) {
  59567. ripplePath.setStyle('fill', color);
  59568. });
  59569. var symbolOffset = normalizeSymbolOffset(data.getItemVisual(idx, 'symbolOffset'), symbolSize);
  59570. if (symbolOffset) {
  59571. rippleGroup.x = symbolOffset[0];
  59572. rippleGroup.y = symbolOffset[1];
  59573. }
  59574. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  59575. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  59576. var effectCfg = {};
  59577. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  59578. effectCfg.rippleScale = itemModel.get(['rippleEffect', 'scale']);
  59579. effectCfg.brushType = itemModel.get(['rippleEffect', 'brushType']);
  59580. effectCfg.period = itemModel.get(['rippleEffect', 'period']) * 1000;
  59581. effectCfg.effectOffset = idx / data.count();
  59582. effectCfg.z = seriesModel.getShallow('z') || 0;
  59583. effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0;
  59584. effectCfg.symbolType = symbolType;
  59585. effectCfg.color = color;
  59586. effectCfg.rippleEffectColor = itemModel.get(['rippleEffect', 'color']);
  59587. effectCfg.rippleNumber = itemModel.get(['rippleEffect', 'number']);
  59588. if (effectCfg.showEffectOn === 'render') {
  59589. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  59590. this._effectCfg = effectCfg;
  59591. } else {
  59592. // Not keep old effect config
  59593. this._effectCfg = null;
  59594. this.stopEffectAnimation();
  59595. this.onHoverStateChange = function (toState) {
  59596. if (toState === 'emphasis') {
  59597. if (effectCfg.showEffectOn !== 'render') {
  59598. _this.startEffectAnimation(effectCfg);
  59599. }
  59600. } else if (toState === 'normal') {
  59601. if (effectCfg.showEffectOn !== 'render') {
  59602. _this.stopEffectAnimation();
  59603. }
  59604. }
  59605. };
  59606. }
  59607. this._effectCfg = effectCfg;
  59608. toggleHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  59609. };
  59610. EffectSymbol.prototype.fadeOut = function (cb) {
  59611. cb && cb();
  59612. };
  59613. return EffectSymbol;
  59614. }(Group);
  59615. var EffectScatterView =
  59616. /** @class */
  59617. function (_super) {
  59618. __extends(EffectScatterView, _super);
  59619. function EffectScatterView() {
  59620. var _this = _super !== null && _super.apply(this, arguments) || this;
  59621. _this.type = EffectScatterView.type;
  59622. return _this;
  59623. }
  59624. EffectScatterView.prototype.init = function () {
  59625. this._symbolDraw = new SymbolDraw(EffectSymbol);
  59626. };
  59627. EffectScatterView.prototype.render = function (seriesModel, ecModel, api) {
  59628. var data = seriesModel.getData();
  59629. var effectSymbolDraw = this._symbolDraw;
  59630. effectSymbolDraw.updateData(data, {
  59631. clipShape: this._getClipShape(seriesModel)
  59632. });
  59633. this.group.add(effectSymbolDraw.group);
  59634. };
  59635. EffectScatterView.prototype._getClipShape = function (seriesModel) {
  59636. var coordSys = seriesModel.coordinateSystem;
  59637. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  59638. return seriesModel.get('clip', true) ? clipArea : null;
  59639. };
  59640. EffectScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  59641. var data = seriesModel.getData();
  59642. this.group.dirty();
  59643. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  59644. if (res.progress) {
  59645. res.progress({
  59646. start: 0,
  59647. end: data.count(),
  59648. count: data.count()
  59649. }, data);
  59650. }
  59651. this._symbolDraw.updateLayout();
  59652. };
  59653. EffectScatterView.prototype._updateGroupTransform = function (seriesModel) {
  59654. var coordSys = seriesModel.coordinateSystem;
  59655. if (coordSys && coordSys.getRoamTransform) {
  59656. this.group.transform = clone$2(coordSys.getRoamTransform());
  59657. this.group.decomposeTransform();
  59658. }
  59659. };
  59660. EffectScatterView.prototype.remove = function (ecModel, api) {
  59661. this._symbolDraw && this._symbolDraw.remove(true);
  59662. };
  59663. EffectScatterView.type = 'effectScatter';
  59664. return EffectScatterView;
  59665. }(ChartView);
  59666. var EffectScatterSeriesModel =
  59667. /** @class */
  59668. function (_super) {
  59669. __extends(EffectScatterSeriesModel, _super);
  59670. function EffectScatterSeriesModel() {
  59671. var _this = _super !== null && _super.apply(this, arguments) || this;
  59672. _this.type = EffectScatterSeriesModel.type;
  59673. _this.hasSymbolVisual = true;
  59674. return _this;
  59675. }
  59676. EffectScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59677. return createSeriesData(null, this, {
  59678. useEncodeDefaulter: true
  59679. });
  59680. };
  59681. EffectScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  59682. return selectors.point(data.getItemLayout(dataIndex));
  59683. };
  59684. EffectScatterSeriesModel.type = 'series.effectScatter';
  59685. EffectScatterSeriesModel.dependencies = ['grid', 'polar'];
  59686. EffectScatterSeriesModel.defaultOption = {
  59687. coordinateSystem: 'cartesian2d',
  59688. // zlevel: 0,
  59689. z: 2,
  59690. legendHoverLink: true,
  59691. effectType: 'ripple',
  59692. progressive: 0,
  59693. // When to show the effect, option: 'render'|'emphasis'
  59694. showEffectOn: 'render',
  59695. clip: true,
  59696. // Ripple effect config
  59697. rippleEffect: {
  59698. period: 4,
  59699. // Scale of ripple
  59700. scale: 2.5,
  59701. // Brush type can be fill or stroke
  59702. brushType: 'fill',
  59703. // Ripple number
  59704. number: 3
  59705. },
  59706. universalTransition: {
  59707. divideShape: 'clone'
  59708. },
  59709. // Cartesian coordinate system
  59710. // xAxisIndex: 0,
  59711. // yAxisIndex: 0,
  59712. // Polar coordinate system
  59713. // polarIndex: 0,
  59714. // Geo coordinate system
  59715. // geoIndex: 0,
  59716. // symbol: null, // 图形类型
  59717. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  59718. // symbolRotate: null, // 图形旋转控制
  59719. // itemStyle: {
  59720. // opacity: 1
  59721. // }
  59722. };
  59723. return EffectScatterSeriesModel;
  59724. }(SeriesModel);
  59725. function install$l(registers) {
  59726. registers.registerChartView(EffectScatterView);
  59727. registers.registerSeriesModel(EffectScatterSeriesModel);
  59728. registers.registerLayout(pointsLayout('effectScatter'));
  59729. }
  59730. var EffectLine =
  59731. /** @class */
  59732. function (_super) {
  59733. __extends(EffectLine, _super);
  59734. function EffectLine(lineData, idx, seriesScope) {
  59735. var _this = _super.call(this) || this;
  59736. _this.add(_this.createLine(lineData, idx, seriesScope));
  59737. _this._updateEffectSymbol(lineData, idx);
  59738. return _this;
  59739. }
  59740. EffectLine.prototype.createLine = function (lineData, idx, seriesScope) {
  59741. return new Line$1(lineData, idx, seriesScope);
  59742. };
  59743. EffectLine.prototype._updateEffectSymbol = function (lineData, idx) {
  59744. var itemModel = lineData.getItemModel(idx);
  59745. var effectModel = itemModel.getModel('effect');
  59746. var size = effectModel.get('symbolSize');
  59747. var symbolType = effectModel.get('symbol');
  59748. if (!isArray(size)) {
  59749. size = [size, size];
  59750. }
  59751. var lineStyle = lineData.getItemVisual(idx, 'style');
  59752. var color = effectModel.get('color') || lineStyle && lineStyle.stroke;
  59753. var symbol = this.childAt(1);
  59754. if (this._symbolType !== symbolType) {
  59755. // Remove previous
  59756. this.remove(symbol);
  59757. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  59758. symbol.z2 = 100;
  59759. symbol.culling = true;
  59760. this.add(symbol);
  59761. } // Symbol may be removed if loop is false
  59762. if (!symbol) {
  59763. return;
  59764. } // Shadow color is same with color in default
  59765. symbol.setStyle('shadowColor', color);
  59766. symbol.setStyle(effectModel.getItemStyle(['color']));
  59767. symbol.scaleX = size[0];
  59768. symbol.scaleY = size[1];
  59769. symbol.setColor(color);
  59770. this._symbolType = symbolType;
  59771. this._symbolScale = size;
  59772. this._updateEffectAnimation(lineData, effectModel, idx);
  59773. };
  59774. EffectLine.prototype._updateEffectAnimation = function (lineData, effectModel, idx) {
  59775. var symbol = this.childAt(1);
  59776. if (!symbol) {
  59777. return;
  59778. }
  59779. var points = lineData.getItemLayout(idx);
  59780. var period = effectModel.get('period') * 1000;
  59781. var loop = effectModel.get('loop');
  59782. var roundTrip = effectModel.get('roundTrip');
  59783. var constantSpeed = effectModel.get('constantSpeed');
  59784. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  59785. return idx / lineData.count() * period / 3;
  59786. }); // Ignore when updating
  59787. symbol.ignore = true;
  59788. this._updateAnimationPoints(symbol, points);
  59789. if (constantSpeed > 0) {
  59790. period = this._getLineLength(symbol) / constantSpeed * 1000;
  59791. }
  59792. if (period !== this._period || loop !== this._loop || roundTrip !== this._roundTrip) {
  59793. symbol.stopAnimation();
  59794. var delayNum = void 0;
  59795. if (isFunction(delayExpr)) {
  59796. delayNum = delayExpr(idx);
  59797. } else {
  59798. delayNum = delayExpr;
  59799. }
  59800. if (symbol.__t > 0) {
  59801. delayNum = -period * symbol.__t;
  59802. }
  59803. this._animateSymbol(symbol, period, delayNum, loop, roundTrip);
  59804. }
  59805. this._period = period;
  59806. this._loop = loop;
  59807. this._roundTrip = roundTrip;
  59808. };
  59809. EffectLine.prototype._animateSymbol = function (symbol, period, delayNum, loop, roundTrip) {
  59810. if (period > 0) {
  59811. symbol.__t = 0;
  59812. var self_1 = this;
  59813. var animator = symbol.animate('', loop).when(roundTrip ? period * 2 : period, {
  59814. __t: roundTrip ? 2 : 1
  59815. }).delay(delayNum).during(function () {
  59816. self_1._updateSymbolPosition(symbol);
  59817. });
  59818. if (!loop) {
  59819. animator.done(function () {
  59820. self_1.remove(symbol);
  59821. });
  59822. }
  59823. animator.start();
  59824. }
  59825. };
  59826. EffectLine.prototype._getLineLength = function (symbol) {
  59827. // Not so accurate
  59828. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  59829. };
  59830. EffectLine.prototype._updateAnimationPoints = function (symbol, points) {
  59831. symbol.__p1 = points[0];
  59832. symbol.__p2 = points[1];
  59833. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  59834. };
  59835. EffectLine.prototype.updateData = function (lineData, idx, seriesScope) {
  59836. this.childAt(0).updateData(lineData, idx, seriesScope);
  59837. this._updateEffectSymbol(lineData, idx);
  59838. };
  59839. EffectLine.prototype._updateSymbolPosition = function (symbol) {
  59840. var p1 = symbol.__p1;
  59841. var p2 = symbol.__p2;
  59842. var cp1 = symbol.__cp1;
  59843. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59844. var pos = [symbol.x, symbol.y];
  59845. var lastPos = pos.slice();
  59846. var quadraticAt$1 = quadraticAt;
  59847. var quadraticDerivativeAt$1 = quadraticDerivativeAt;
  59848. pos[0] = quadraticAt$1(p1[0], cp1[0], p2[0], t);
  59849. pos[1] = quadraticAt$1(p1[1], cp1[1], p2[1], t); // Tangent
  59850. var tx = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[0], cp1[0], p2[0], t) : quadraticDerivativeAt$1(p2[0], cp1[0], p1[0], 1 - t);
  59851. var ty = symbol.__t < 1 ? quadraticDerivativeAt$1(p1[1], cp1[1], p2[1], t) : quadraticDerivativeAt$1(p2[1], cp1[1], p1[1], 1 - t);
  59852. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  59853. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  59854. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  59855. symbol.scaleY = dist(lastPos, pos) * 1.05; // make sure the last segment render within endPoint
  59856. if (t === 1) {
  59857. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  59858. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  59859. }
  59860. } else if (symbol.__lastT === 1) {
  59861. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  59862. symbol.scaleY = 2 * dist(p1, pos);
  59863. } else {
  59864. symbol.scaleY = this._symbolScale[1];
  59865. }
  59866. }
  59867. symbol.__lastT = symbol.__t;
  59868. symbol.ignore = false;
  59869. symbol.x = pos[0];
  59870. symbol.y = pos[1];
  59871. };
  59872. EffectLine.prototype.updateLayout = function (lineData, idx) {
  59873. this.childAt(0).updateLayout(lineData, idx);
  59874. var effectModel = lineData.getItemModel(idx).getModel('effect');
  59875. this._updateEffectAnimation(lineData, effectModel, idx);
  59876. };
  59877. return EffectLine;
  59878. }(Group);
  59879. var Polyline$1 =
  59880. /** @class */
  59881. function (_super) {
  59882. __extends(Polyline$1, _super);
  59883. function Polyline$1(lineData, idx, seriesScope) {
  59884. var _this = _super.call(this) || this;
  59885. _this._createPolyline(lineData, idx, seriesScope);
  59886. return _this;
  59887. }
  59888. Polyline$1.prototype._createPolyline = function (lineData, idx, seriesScope) {
  59889. // let seriesModel = lineData.hostModel;
  59890. var points = lineData.getItemLayout(idx);
  59891. var line = new Polyline({
  59892. shape: {
  59893. points: points
  59894. }
  59895. });
  59896. this.add(line);
  59897. this._updateCommonStl(lineData, idx, seriesScope);
  59898. };
  59899. Polyline$1.prototype.updateData = function (lineData, idx, seriesScope) {
  59900. var seriesModel = lineData.hostModel;
  59901. var line = this.childAt(0);
  59902. var target = {
  59903. shape: {
  59904. points: lineData.getItemLayout(idx)
  59905. }
  59906. };
  59907. updateProps(line, target, seriesModel, idx);
  59908. this._updateCommonStl(lineData, idx, seriesScope);
  59909. };
  59910. Polyline$1.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  59911. var line = this.childAt(0);
  59912. var itemModel = lineData.getItemModel(idx);
  59913. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  59914. var focus = seriesScope && seriesScope.focus;
  59915. var blurScope = seriesScope && seriesScope.blurScope;
  59916. var emphasisDisabled = seriesScope && seriesScope.emphasisDisabled;
  59917. if (!seriesScope || lineData.hasItemOption) {
  59918. var emphasisModel = itemModel.getModel('emphasis');
  59919. emphasisLineStyle = emphasisModel.getModel('lineStyle').getLineStyle();
  59920. emphasisDisabled = emphasisModel.get('disabled');
  59921. focus = emphasisModel.get('focus');
  59922. blurScope = emphasisModel.get('blurScope');
  59923. }
  59924. line.useStyle(lineData.getItemVisual(idx, 'style'));
  59925. line.style.fill = null;
  59926. line.style.strokeNoScale = true;
  59927. var lineEmphasisState = line.ensureState('emphasis');
  59928. lineEmphasisState.style = emphasisLineStyle;
  59929. toggleHoverEmphasis(this, focus, blurScope, emphasisDisabled);
  59930. };
  59931. Polyline$1.prototype.updateLayout = function (lineData, idx) {
  59932. var polyline = this.childAt(0);
  59933. polyline.setShape('points', lineData.getItemLayout(idx));
  59934. };
  59935. return Polyline$1;
  59936. }(Group);
  59937. var EffectPolyline =
  59938. /** @class */
  59939. function (_super) {
  59940. __extends(EffectPolyline, _super);
  59941. function EffectPolyline() {
  59942. var _this = _super !== null && _super.apply(this, arguments) || this;
  59943. _this._lastFrame = 0;
  59944. _this._lastFramePercent = 0;
  59945. return _this;
  59946. } // Override
  59947. EffectPolyline.prototype.createLine = function (lineData, idx, seriesScope) {
  59948. return new Polyline$1(lineData, idx, seriesScope);
  59949. };
  59950. EffectPolyline.prototype._updateAnimationPoints = function (symbol, points) {
  59951. this._points = points;
  59952. var accLenArr = [0];
  59953. var len = 0;
  59954. for (var i = 1; i < points.length; i++) {
  59955. var p1 = points[i - 1];
  59956. var p2 = points[i];
  59957. len += dist(p1, p2);
  59958. accLenArr.push(len);
  59959. }
  59960. if (len === 0) {
  59961. this._length = 0;
  59962. return;
  59963. }
  59964. for (var i = 0; i < accLenArr.length; i++) {
  59965. accLenArr[i] /= len;
  59966. }
  59967. this._offsets = accLenArr;
  59968. this._length = len;
  59969. };
  59970. EffectPolyline.prototype._getLineLength = function () {
  59971. return this._length;
  59972. };
  59973. EffectPolyline.prototype._updateSymbolPosition = function (symbol) {
  59974. var t = symbol.__t < 1 ? symbol.__t : 2 - symbol.__t;
  59975. var points = this._points;
  59976. var offsets = this._offsets;
  59977. var len = points.length;
  59978. if (!offsets) {
  59979. // Has length 0
  59980. return;
  59981. }
  59982. var lastFrame = this._lastFrame;
  59983. var frame;
  59984. if (t < this._lastFramePercent) {
  59985. // Start from the next frame
  59986. // PENDING start from lastFrame ?
  59987. var start = Math.min(lastFrame + 1, len - 1);
  59988. for (frame = start; frame >= 0; frame--) {
  59989. if (offsets[frame] <= t) {
  59990. break;
  59991. }
  59992. } // PENDING really need to do this ?
  59993. frame = Math.min(frame, len - 2);
  59994. } else {
  59995. for (frame = lastFrame; frame < len; frame++) {
  59996. if (offsets[frame] > t) {
  59997. break;
  59998. }
  59999. }
  60000. frame = Math.min(frame - 1, len - 2);
  60001. }
  60002. var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]);
  60003. var p0 = points[frame];
  60004. var p1 = points[frame + 1];
  60005. symbol.x = p0[0] * (1 - p) + p * p1[0];
  60006. symbol.y = p0[1] * (1 - p) + p * p1[1];
  60007. var tx = symbol.__t < 1 ? p1[0] - p0[0] : p0[0] - p1[0];
  60008. var ty = symbol.__t < 1 ? p1[1] - p0[1] : p0[1] - p1[1];
  60009. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  60010. this._lastFrame = frame;
  60011. this._lastFramePercent = t;
  60012. symbol.ignore = false;
  60013. };
  60014. return EffectPolyline;
  60015. }(EffectLine);
  60016. var LargeLinesPathShape =
  60017. /** @class */
  60018. function () {
  60019. function LargeLinesPathShape() {
  60020. this.polyline = false;
  60021. this.curveness = 0;
  60022. this.segs = [];
  60023. }
  60024. return LargeLinesPathShape;
  60025. }();
  60026. var LargeLinesPath =
  60027. /** @class */
  60028. function (_super) {
  60029. __extends(LargeLinesPath, _super);
  60030. function LargeLinesPath(opts) {
  60031. var _this = _super.call(this, opts) || this;
  60032. _this._off = 0;
  60033. _this.hoverDataIdx = -1;
  60034. return _this;
  60035. }
  60036. LargeLinesPath.prototype.reset = function () {
  60037. this.notClear = false;
  60038. this._off = 0;
  60039. };
  60040. LargeLinesPath.prototype.getDefaultStyle = function () {
  60041. return {
  60042. stroke: '#000',
  60043. fill: null
  60044. };
  60045. };
  60046. LargeLinesPath.prototype.getDefaultShape = function () {
  60047. return new LargeLinesPathShape();
  60048. };
  60049. LargeLinesPath.prototype.buildPath = function (ctx, shape) {
  60050. var segs = shape.segs;
  60051. var curveness = shape.curveness;
  60052. var i;
  60053. if (shape.polyline) {
  60054. for (i = this._off; i < segs.length;) {
  60055. var count = segs[i++];
  60056. if (count > 0) {
  60057. ctx.moveTo(segs[i++], segs[i++]);
  60058. for (var k = 1; k < count; k++) {
  60059. ctx.lineTo(segs[i++], segs[i++]);
  60060. }
  60061. }
  60062. }
  60063. } else {
  60064. for (i = this._off; i < segs.length;) {
  60065. var x0 = segs[i++];
  60066. var y0 = segs[i++];
  60067. var x1 = segs[i++];
  60068. var y1 = segs[i++];
  60069. ctx.moveTo(x0, y0);
  60070. if (curveness > 0) {
  60071. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  60072. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  60073. ctx.quadraticCurveTo(x2, y2, x1, y1);
  60074. } else {
  60075. ctx.lineTo(x1, y1);
  60076. }
  60077. }
  60078. }
  60079. if (this.incremental) {
  60080. this._off = i;
  60081. this.notClear = true;
  60082. }
  60083. };
  60084. LargeLinesPath.prototype.findDataIndex = function (x, y) {
  60085. var shape = this.shape;
  60086. var segs = shape.segs;
  60087. var curveness = shape.curveness;
  60088. var lineWidth = this.style.lineWidth;
  60089. if (shape.polyline) {
  60090. var dataIndex = 0;
  60091. for (var i = 0; i < segs.length;) {
  60092. var count = segs[i++];
  60093. if (count > 0) {
  60094. var x0 = segs[i++];
  60095. var y0 = segs[i++];
  60096. for (var k = 1; k < count; k++) {
  60097. var x1 = segs[i++];
  60098. var y1 = segs[i++];
  60099. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  60100. return dataIndex;
  60101. }
  60102. }
  60103. }
  60104. dataIndex++;
  60105. }
  60106. } else {
  60107. var dataIndex = 0;
  60108. for (var i = 0; i < segs.length;) {
  60109. var x0 = segs[i++];
  60110. var y0 = segs[i++];
  60111. var x1 = segs[i++];
  60112. var y1 = segs[i++];
  60113. if (curveness > 0) {
  60114. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  60115. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  60116. if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) {
  60117. return dataIndex;
  60118. }
  60119. } else {
  60120. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  60121. return dataIndex;
  60122. }
  60123. }
  60124. dataIndex++;
  60125. }
  60126. }
  60127. return -1;
  60128. };
  60129. LargeLinesPath.prototype.contain = function (x, y) {
  60130. var localPos = this.transformCoordToLocal(x, y);
  60131. var rect = this.getBoundingRect();
  60132. x = localPos[0];
  60133. y = localPos[1];
  60134. if (rect.contain(x, y)) {
  60135. // Cache found data index.
  60136. var dataIdx = this.hoverDataIdx = this.findDataIndex(x, y);
  60137. return dataIdx >= 0;
  60138. }
  60139. this.hoverDataIdx = -1;
  60140. return false;
  60141. };
  60142. LargeLinesPath.prototype.getBoundingRect = function () {
  60143. // Ignore stroke for large symbol draw.
  60144. var rect = this._rect;
  60145. if (!rect) {
  60146. var shape = this.shape;
  60147. var points = shape.segs;
  60148. var minX = Infinity;
  60149. var minY = Infinity;
  60150. var maxX = -Infinity;
  60151. var maxY = -Infinity;
  60152. for (var i = 0; i < points.length;) {
  60153. var x = points[i++];
  60154. var y = points[i++];
  60155. minX = Math.min(x, minX);
  60156. maxX = Math.max(x, maxX);
  60157. minY = Math.min(y, minY);
  60158. maxY = Math.max(y, maxY);
  60159. }
  60160. rect = this._rect = new BoundingRect(minX, minY, maxX, maxY);
  60161. }
  60162. return rect;
  60163. };
  60164. return LargeLinesPath;
  60165. }(Path);
  60166. var LargeLineDraw =
  60167. /** @class */
  60168. function () {
  60169. function LargeLineDraw() {
  60170. this.group = new Group();
  60171. }
  60172. /**
  60173. * Update symbols draw by new data
  60174. */
  60175. LargeLineDraw.prototype.updateData = function (data) {
  60176. this._clear();
  60177. var lineEl = this._create();
  60178. lineEl.setShape({
  60179. segs: data.getLayout('linesPoints')
  60180. });
  60181. this._setCommon(lineEl, data);
  60182. };
  60183. /**
  60184. * @override
  60185. */
  60186. LargeLineDraw.prototype.incrementalPrepareUpdate = function (data) {
  60187. this.group.removeAll();
  60188. this._clear();
  60189. };
  60190. /**
  60191. * @override
  60192. */
  60193. LargeLineDraw.prototype.incrementalUpdate = function (taskParams, data) {
  60194. var lastAdded = this._newAdded[0];
  60195. var linePoints = data.getLayout('linesPoints');
  60196. var oldSegs = lastAdded && lastAdded.shape.segs; // Merging the exists. Each element has 1e4 points.
  60197. // Consider the performance balance between too much elements and too much points in one shape(may affect hover optimization)
  60198. if (oldSegs && oldSegs.length < 2e4) {
  60199. var oldLen = oldSegs.length;
  60200. var newSegs = new Float32Array(oldLen + linePoints.length); // Concat two array
  60201. newSegs.set(oldSegs);
  60202. newSegs.set(linePoints, oldLen);
  60203. lastAdded.setShape({
  60204. segs: newSegs
  60205. });
  60206. } else {
  60207. // Clear
  60208. this._newAdded = [];
  60209. var lineEl = this._create();
  60210. lineEl.incremental = true;
  60211. lineEl.setShape({
  60212. segs: linePoints
  60213. });
  60214. this._setCommon(lineEl, data);
  60215. lineEl.__startIndex = taskParams.start;
  60216. }
  60217. };
  60218. /**
  60219. * @override
  60220. */
  60221. LargeLineDraw.prototype.remove = function () {
  60222. this._clear();
  60223. };
  60224. LargeLineDraw.prototype.eachRendered = function (cb) {
  60225. this._newAdded[0] && cb(this._newAdded[0]);
  60226. };
  60227. LargeLineDraw.prototype._create = function () {
  60228. var lineEl = new LargeLinesPath({
  60229. cursor: 'default',
  60230. ignoreCoarsePointer: true
  60231. });
  60232. this._newAdded.push(lineEl);
  60233. this.group.add(lineEl);
  60234. return lineEl;
  60235. };
  60236. LargeLineDraw.prototype._setCommon = function (lineEl, data, isIncremental) {
  60237. var hostModel = data.hostModel;
  60238. lineEl.setShape({
  60239. polyline: hostModel.get('polyline'),
  60240. curveness: hostModel.get(['lineStyle', 'curveness'])
  60241. });
  60242. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  60243. lineEl.style.strokeNoScale = true;
  60244. var style = data.getVisual('style');
  60245. if (style && style.stroke) {
  60246. lineEl.setStyle('stroke', style.stroke);
  60247. }
  60248. lineEl.setStyle('fill', null);
  60249. var ecData = getECData(lineEl); // Enable tooltip
  60250. // PENDING May have performance issue when path is extremely large
  60251. ecData.seriesIndex = hostModel.seriesIndex;
  60252. lineEl.on('mousemove', function (e) {
  60253. ecData.dataIndex = null;
  60254. var dataIndex = lineEl.hoverDataIdx;
  60255. if (dataIndex > 0) {
  60256. // Provide dataIndex for tooltip
  60257. ecData.dataIndex = dataIndex + lineEl.__startIndex;
  60258. }
  60259. });
  60260. };
  60261. LargeLineDraw.prototype._clear = function () {
  60262. this._newAdded = [];
  60263. this.group.removeAll();
  60264. };
  60265. return LargeLineDraw;
  60266. }();
  60267. var linesLayout = {
  60268. seriesType: 'lines',
  60269. plan: createRenderPlanner(),
  60270. reset: function (seriesModel) {
  60271. var coordSys = seriesModel.coordinateSystem;
  60272. if (!coordSys) {
  60273. if ("development" !== 'production') {
  60274. error('The lines series must have a coordinate system.');
  60275. }
  60276. return;
  60277. }
  60278. var isPolyline = seriesModel.get('polyline');
  60279. var isLarge = seriesModel.pipelineContext.large;
  60280. return {
  60281. progress: function (params, lineData) {
  60282. var lineCoords = [];
  60283. if (isLarge) {
  60284. var points = void 0;
  60285. var segCount = params.end - params.start;
  60286. if (isPolyline) {
  60287. var totalCoordsCount = 0;
  60288. for (var i = params.start; i < params.end; i++) {
  60289. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  60290. }
  60291. points = new Float32Array(segCount + totalCoordsCount * 2);
  60292. } else {
  60293. points = new Float32Array(segCount * 4);
  60294. }
  60295. var offset = 0;
  60296. var pt = [];
  60297. for (var i = params.start; i < params.end; i++) {
  60298. var len = seriesModel.getLineCoords(i, lineCoords);
  60299. if (isPolyline) {
  60300. points[offset++] = len;
  60301. }
  60302. for (var k = 0; k < len; k++) {
  60303. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  60304. points[offset++] = pt[0];
  60305. points[offset++] = pt[1];
  60306. }
  60307. }
  60308. lineData.setLayout('linesPoints', points);
  60309. } else {
  60310. for (var i = params.start; i < params.end; i++) {
  60311. var itemModel = lineData.getItemModel(i);
  60312. var len = seriesModel.getLineCoords(i, lineCoords);
  60313. var pts = [];
  60314. if (isPolyline) {
  60315. for (var j = 0; j < len; j++) {
  60316. pts.push(coordSys.dataToPoint(lineCoords[j]));
  60317. }
  60318. } else {
  60319. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  60320. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  60321. var curveness = itemModel.get(['lineStyle', 'curveness']);
  60322. if (+curveness) {
  60323. 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];
  60324. }
  60325. }
  60326. lineData.setItemLayout(i, pts);
  60327. }
  60328. }
  60329. }
  60330. };
  60331. }
  60332. };
  60333. var LinesView =
  60334. /** @class */
  60335. function (_super) {
  60336. __extends(LinesView, _super);
  60337. function LinesView() {
  60338. var _this = _super !== null && _super.apply(this, arguments) || this;
  60339. _this.type = LinesView.type;
  60340. return _this;
  60341. }
  60342. LinesView.prototype.render = function (seriesModel, ecModel, api) {
  60343. var data = seriesModel.getData();
  60344. var lineDraw = this._updateLineDraw(data, seriesModel);
  60345. var zlevel = seriesModel.get('zlevel');
  60346. var trailLength = seriesModel.get(['effect', 'trailLength']);
  60347. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  60348. // FIXME Better way ?
  60349. // SVG doesn't support
  60350. var isSvg = zr.painter.getType() === 'svg';
  60351. if (!isSvg) {
  60352. zr.painter.getLayer(zlevel).clear(true);
  60353. } // Config layer with motion blur
  60354. if (this._lastZlevel != null && !isSvg) {
  60355. zr.configLayer(this._lastZlevel, {
  60356. motionBlur: false
  60357. });
  60358. }
  60359. if (this._showEffect(seriesModel) && trailLength > 0) {
  60360. if (!isSvg) {
  60361. zr.configLayer(zlevel, {
  60362. motionBlur: true,
  60363. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  60364. });
  60365. } else if ("development" !== 'production') {
  60366. console.warn('SVG render mode doesn\'t support lines with trail effect');
  60367. }
  60368. }
  60369. lineDraw.updateData(data);
  60370. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  60371. if (clipPath) {
  60372. this.group.setClipPath(clipPath);
  60373. } else {
  60374. this.group.removeClipPath();
  60375. }
  60376. this._lastZlevel = zlevel;
  60377. this._finished = true;
  60378. };
  60379. LinesView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60380. var data = seriesModel.getData();
  60381. var lineDraw = this._updateLineDraw(data, seriesModel);
  60382. lineDraw.incrementalPrepareUpdate(data);
  60383. this._clearLayer(api);
  60384. this._finished = false;
  60385. };
  60386. LinesView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  60387. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  60388. this._finished = taskParams.end === seriesModel.getData().count();
  60389. };
  60390. LinesView.prototype.eachRendered = function (cb) {
  60391. this._lineDraw && this._lineDraw.eachRendered(cb);
  60392. };
  60393. LinesView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  60394. var data = seriesModel.getData();
  60395. var pipelineContext = seriesModel.pipelineContext;
  60396. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  60397. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  60398. return {
  60399. update: true
  60400. };
  60401. } else {
  60402. // TODO Use same logic with ScatterView.
  60403. // Manually update layout
  60404. var res = linesLayout.reset(seriesModel, ecModel, api);
  60405. if (res.progress) {
  60406. res.progress({
  60407. start: 0,
  60408. end: data.count(),
  60409. count: data.count()
  60410. }, data);
  60411. } // Not in large mode
  60412. this._lineDraw.updateLayout();
  60413. this._clearLayer(api);
  60414. }
  60415. };
  60416. LinesView.prototype._updateLineDraw = function (data, seriesModel) {
  60417. var lineDraw = this._lineDraw;
  60418. var hasEffect = this._showEffect(seriesModel);
  60419. var isPolyline = !!seriesModel.get('polyline');
  60420. var pipelineContext = seriesModel.pipelineContext;
  60421. var isLargeDraw = pipelineContext.large;
  60422. if ("development" !== 'production') {
  60423. if (hasEffect && isLargeDraw) {
  60424. console.warn('Large lines not support effect');
  60425. }
  60426. }
  60427. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  60428. if (lineDraw) {
  60429. lineDraw.remove();
  60430. }
  60431. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1);
  60432. this._hasEffet = hasEffect;
  60433. this._isPolyline = isPolyline;
  60434. this._isLargeDraw = isLargeDraw;
  60435. }
  60436. this.group.add(lineDraw.group);
  60437. return lineDraw;
  60438. };
  60439. LinesView.prototype._showEffect = function (seriesModel) {
  60440. return !!seriesModel.get(['effect', 'show']);
  60441. };
  60442. LinesView.prototype._clearLayer = function (api) {
  60443. // Not use motion when dragging or zooming
  60444. var zr = api.getZr();
  60445. var isSvg = zr.painter.getType() === 'svg';
  60446. if (!isSvg && this._lastZlevel != null) {
  60447. zr.painter.getLayer(this._lastZlevel).clear(true);
  60448. }
  60449. };
  60450. LinesView.prototype.remove = function (ecModel, api) {
  60451. this._lineDraw && this._lineDraw.remove();
  60452. this._lineDraw = null; // Clear motion when lineDraw is removed
  60453. this._clearLayer(api);
  60454. };
  60455. LinesView.prototype.dispose = function (ecModel, api) {
  60456. this.remove(ecModel, api);
  60457. };
  60458. LinesView.type = 'lines';
  60459. return LinesView;
  60460. }(ChartView);
  60461. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  60462. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  60463. function compatEc2(seriesOpt) {
  60464. var data = seriesOpt.data;
  60465. if (data && data[0] && data[0][0] && data[0][0].coord) {
  60466. if ("development" !== 'production') {
  60467. console.warn('Lines data configuration has been changed to' + ' { coords:[[1,2],[2,3]] }');
  60468. }
  60469. seriesOpt.data = map(data, function (itemOpt) {
  60470. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  60471. var target = {
  60472. coords: coords
  60473. };
  60474. if (itemOpt[0].name) {
  60475. target.fromName = itemOpt[0].name;
  60476. }
  60477. if (itemOpt[1].name) {
  60478. target.toName = itemOpt[1].name;
  60479. }
  60480. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  60481. });
  60482. }
  60483. }
  60484. var LinesSeriesModel =
  60485. /** @class */
  60486. function (_super) {
  60487. __extends(LinesSeriesModel, _super);
  60488. function LinesSeriesModel() {
  60489. var _this = _super !== null && _super.apply(this, arguments) || this;
  60490. _this.type = LinesSeriesModel.type;
  60491. _this.visualStyleAccessPath = 'lineStyle';
  60492. _this.visualDrawType = 'stroke';
  60493. return _this;
  60494. }
  60495. LinesSeriesModel.prototype.init = function (option) {
  60496. // The input data may be null/undefined.
  60497. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  60498. compatEc2(option);
  60499. var result = this._processFlatCoordsArray(option.data);
  60500. this._flatCoords = result.flatCoords;
  60501. this._flatCoordsOffset = result.flatCoordsOffset;
  60502. if (result.flatCoords) {
  60503. option.data = new Float32Array(result.count);
  60504. }
  60505. _super.prototype.init.apply(this, arguments);
  60506. };
  60507. LinesSeriesModel.prototype.mergeOption = function (option) {
  60508. compatEc2(option);
  60509. if (option.data) {
  60510. // Only update when have option data to merge.
  60511. var result = this._processFlatCoordsArray(option.data);
  60512. this._flatCoords = result.flatCoords;
  60513. this._flatCoordsOffset = result.flatCoordsOffset;
  60514. if (result.flatCoords) {
  60515. option.data = new Float32Array(result.count);
  60516. }
  60517. }
  60518. _super.prototype.mergeOption.apply(this, arguments);
  60519. };
  60520. LinesSeriesModel.prototype.appendData = function (params) {
  60521. var result = this._processFlatCoordsArray(params.data);
  60522. if (result.flatCoords) {
  60523. if (!this._flatCoords) {
  60524. this._flatCoords = result.flatCoords;
  60525. this._flatCoordsOffset = result.flatCoordsOffset;
  60526. } else {
  60527. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  60528. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  60529. }
  60530. params.data = new Float32Array(result.count);
  60531. }
  60532. this.getRawData().appendData(params.data);
  60533. };
  60534. LinesSeriesModel.prototype._getCoordsFromItemModel = function (idx) {
  60535. var itemModel = this.getData().getItemModel(idx);
  60536. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  60537. if ("development" !== 'production') {
  60538. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  60539. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  60540. }
  60541. }
  60542. return coords;
  60543. };
  60544. LinesSeriesModel.prototype.getLineCoordsCount = function (idx) {
  60545. if (this._flatCoordsOffset) {
  60546. return this._flatCoordsOffset[idx * 2 + 1];
  60547. } else {
  60548. return this._getCoordsFromItemModel(idx).length;
  60549. }
  60550. };
  60551. LinesSeriesModel.prototype.getLineCoords = function (idx, out) {
  60552. if (this._flatCoordsOffset) {
  60553. var offset = this._flatCoordsOffset[idx * 2];
  60554. var len = this._flatCoordsOffset[idx * 2 + 1];
  60555. for (var i = 0; i < len; i++) {
  60556. out[i] = out[i] || [];
  60557. out[i][0] = this._flatCoords[offset + i * 2];
  60558. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  60559. }
  60560. return len;
  60561. } else {
  60562. var coords = this._getCoordsFromItemModel(idx);
  60563. for (var i = 0; i < coords.length; i++) {
  60564. out[i] = out[i] || [];
  60565. out[i][0] = coords[i][0];
  60566. out[i][1] = coords[i][1];
  60567. }
  60568. return coords.length;
  60569. }
  60570. };
  60571. LinesSeriesModel.prototype._processFlatCoordsArray = function (data) {
  60572. var startOffset = 0;
  60573. if (this._flatCoords) {
  60574. startOffset = this._flatCoords.length;
  60575. } // Stored as a typed array. In format
  60576. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  60577. if (isNumber(data[0])) {
  60578. var len = data.length; // Store offset and len of each segment
  60579. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  60580. var coordsStorage = new Float64Arr(len);
  60581. var coordsCursor = 0;
  60582. var offsetCursor = 0;
  60583. var dataCount = 0;
  60584. for (var i = 0; i < len;) {
  60585. dataCount++;
  60586. var count = data[i++]; // Offset
  60587. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  60588. coordsOffsetAndLenStorage[offsetCursor++] = count;
  60589. for (var k = 0; k < count; k++) {
  60590. var x = data[i++];
  60591. var y = data[i++];
  60592. coordsStorage[coordsCursor++] = x;
  60593. coordsStorage[coordsCursor++] = y;
  60594. if (i > len) {
  60595. if ("development" !== 'production') {
  60596. throw new Error('Invalid data format.');
  60597. }
  60598. }
  60599. }
  60600. }
  60601. return {
  60602. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  60603. flatCoords: coordsStorage,
  60604. count: dataCount
  60605. };
  60606. }
  60607. return {
  60608. flatCoordsOffset: null,
  60609. flatCoords: null,
  60610. count: data.length
  60611. };
  60612. };
  60613. LinesSeriesModel.prototype.getInitialData = function (option, ecModel) {
  60614. if ("development" !== 'production') {
  60615. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  60616. if (!CoordSys) {
  60617. throw new Error('Unknown coordinate system ' + option.coordinateSystem);
  60618. }
  60619. }
  60620. var lineData = new SeriesData(['value'], this);
  60621. lineData.hasItemOption = false;
  60622. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  60623. // dataItem is simply coords
  60624. if (dataItem instanceof Array) {
  60625. return NaN;
  60626. } else {
  60627. lineData.hasItemOption = true;
  60628. var value = dataItem.value;
  60629. if (value != null) {
  60630. return value instanceof Array ? value[dimIndex] : value;
  60631. }
  60632. }
  60633. });
  60634. return lineData;
  60635. };
  60636. LinesSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  60637. var data = this.getData();
  60638. var itemModel = data.getItemModel(dataIndex);
  60639. var name = itemModel.get('name');
  60640. if (name) {
  60641. return name;
  60642. }
  60643. var fromName = itemModel.get('fromName');
  60644. var toName = itemModel.get('toName');
  60645. var nameArr = [];
  60646. fromName != null && nameArr.push(fromName);
  60647. toName != null && nameArr.push(toName);
  60648. return createTooltipMarkup('nameValue', {
  60649. name: nameArr.join(' > ')
  60650. });
  60651. };
  60652. LinesSeriesModel.prototype.preventIncremental = function () {
  60653. return !!this.get(['effect', 'show']);
  60654. };
  60655. LinesSeriesModel.prototype.getProgressive = function () {
  60656. var progressive = this.option.progressive;
  60657. if (progressive == null) {
  60658. return this.option.large ? 1e4 : this.get('progressive');
  60659. }
  60660. return progressive;
  60661. };
  60662. LinesSeriesModel.prototype.getProgressiveThreshold = function () {
  60663. var progressiveThreshold = this.option.progressiveThreshold;
  60664. if (progressiveThreshold == null) {
  60665. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  60666. }
  60667. return progressiveThreshold;
  60668. };
  60669. LinesSeriesModel.prototype.getZLevelKey = function () {
  60670. var effectModel = this.getModel('effect');
  60671. var trailLength = effectModel.get('trailLength');
  60672. return this.getData().count() > this.getProgressiveThreshold() // Each progressive series has individual key.
  60673. ? this.id : effectModel.get('show') && trailLength > 0 ? trailLength + '' : '';
  60674. };
  60675. LinesSeriesModel.type = 'series.lines';
  60676. LinesSeriesModel.dependencies = ['grid', 'polar', 'geo', 'calendar'];
  60677. LinesSeriesModel.defaultOption = {
  60678. coordinateSystem: 'geo',
  60679. // zlevel: 0,
  60680. z: 2,
  60681. legendHoverLink: true,
  60682. // Cartesian coordinate system
  60683. xAxisIndex: 0,
  60684. yAxisIndex: 0,
  60685. symbol: ['none', 'none'],
  60686. symbolSize: [10, 10],
  60687. // Geo coordinate system
  60688. geoIndex: 0,
  60689. effect: {
  60690. show: false,
  60691. period: 4,
  60692. constantSpeed: 0,
  60693. symbol: 'circle',
  60694. symbolSize: 3,
  60695. loop: true,
  60696. trailLength: 0.2
  60697. },
  60698. large: false,
  60699. // Available when large is true
  60700. largeThreshold: 2000,
  60701. polyline: false,
  60702. clip: true,
  60703. label: {
  60704. show: false,
  60705. position: 'end' // distance: 5,
  60706. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  60707. },
  60708. lineStyle: {
  60709. opacity: 0.5
  60710. }
  60711. };
  60712. return LinesSeriesModel;
  60713. }(SeriesModel);
  60714. /*
  60715. * Licensed to the Apache Software Foundation (ASF) under one
  60716. * or more contributor license agreements. See the NOTICE file
  60717. * distributed with this work for additional information
  60718. * regarding copyright ownership. The ASF licenses this file
  60719. * to you under the Apache License, Version 2.0 (the
  60720. * "License"); you may not use this file except in compliance
  60721. * with the License. You may obtain a copy of the License at
  60722. *
  60723. * http://www.apache.org/licenses/LICENSE-2.0
  60724. *
  60725. * Unless required by applicable law or agreed to in writing,
  60726. * software distributed under the License is distributed on an
  60727. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60728. * KIND, either express or implied. See the License for the
  60729. * specific language governing permissions and limitations
  60730. * under the License.
  60731. */
  60732. /**
  60733. * AUTO-GENERATED FILE. DO NOT MODIFY.
  60734. */
  60735. /*
  60736. * Licensed to the Apache Software Foundation (ASF) under one
  60737. * or more contributor license agreements. See the NOTICE file
  60738. * distributed with this work for additional information
  60739. * regarding copyright ownership. The ASF licenses this file
  60740. * to you under the Apache License, Version 2.0 (the
  60741. * "License"); you may not use this file except in compliance
  60742. * with the License. You may obtain a copy of the License at
  60743. *
  60744. * http://www.apache.org/licenses/LICENSE-2.0
  60745. *
  60746. * Unless required by applicable law or agreed to in writing,
  60747. * software distributed under the License is distributed on an
  60748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60749. * KIND, either express or implied. See the License for the
  60750. * specific language governing permissions and limitations
  60751. * under the License.
  60752. */
  60753. function normalize$3(a) {
  60754. if (!(a instanceof Array)) {
  60755. a = [a, a];
  60756. }
  60757. return a;
  60758. }
  60759. var linesVisual = {
  60760. seriesType: 'lines',
  60761. reset: function (seriesModel) {
  60762. var symbolType = normalize$3(seriesModel.get('symbol'));
  60763. var symbolSize = normalize$3(seriesModel.get('symbolSize'));
  60764. var data = seriesModel.getData();
  60765. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  60766. data.setVisual('toSymbol', symbolType && symbolType[1]);
  60767. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  60768. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  60769. function dataEach(data, idx) {
  60770. var itemModel = data.getItemModel(idx);
  60771. var symbolType = normalize$3(itemModel.getShallow('symbol', true));
  60772. var symbolSize = normalize$3(itemModel.getShallow('symbolSize', true));
  60773. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  60774. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  60775. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  60776. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  60777. }
  60778. return {
  60779. dataEach: data.hasItemOption ? dataEach : null
  60780. };
  60781. }
  60782. };
  60783. function install$m(registers) {
  60784. registers.registerChartView(LinesView);
  60785. registers.registerSeriesModel(LinesSeriesModel);
  60786. registers.registerLayout(linesLayout);
  60787. registers.registerVisual(linesVisual);
  60788. }
  60789. var GRADIENT_LEVELS = 256;
  60790. var HeatmapLayer =
  60791. /** @class */
  60792. function () {
  60793. function HeatmapLayer() {
  60794. this.blurSize = 30;
  60795. this.pointSize = 20;
  60796. this.maxOpacity = 1;
  60797. this.minOpacity = 0;
  60798. this._gradientPixels = {
  60799. inRange: null,
  60800. outOfRange: null
  60801. };
  60802. var canvas = platformApi.createCanvas();
  60803. this.canvas = canvas;
  60804. }
  60805. /**
  60806. * Renders Heatmap and returns the rendered canvas
  60807. * @param data array of data, each has x, y, value
  60808. * @param width canvas width
  60809. * @param height canvas height
  60810. */
  60811. HeatmapLayer.prototype.update = function (data, width, height, normalize, colorFunc, isInRange) {
  60812. var brush = this._getBrush();
  60813. var gradientInRange = this._getGradient(colorFunc, 'inRange');
  60814. var gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange');
  60815. var r = this.pointSize + this.blurSize;
  60816. var canvas = this.canvas;
  60817. var ctx = canvas.getContext('2d');
  60818. var len = data.length;
  60819. canvas.width = width;
  60820. canvas.height = height;
  60821. for (var i = 0; i < len; ++i) {
  60822. var p = data[i];
  60823. var x = p[0];
  60824. var y = p[1];
  60825. var value = p[2]; // calculate alpha using value
  60826. var alpha = normalize(value); // draw with the circle brush with alpha
  60827. ctx.globalAlpha = alpha;
  60828. ctx.drawImage(brush, x - r, y - r);
  60829. }
  60830. if (!canvas.width || !canvas.height) {
  60831. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  60832. // 'CanvasRenderingContext2D': The source height is 0."
  60833. return canvas;
  60834. } // colorize the canvas using alpha value and set with gradient
  60835. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  60836. var pixels = imageData.data;
  60837. var offset = 0;
  60838. var pixelLen = pixels.length;
  60839. var minOpacity = this.minOpacity;
  60840. var maxOpacity = this.maxOpacity;
  60841. var diffOpacity = maxOpacity - minOpacity;
  60842. while (offset < pixelLen) {
  60843. var alpha = pixels[offset + 3] / 256;
  60844. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  60845. if (alpha > 0) {
  60846. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  60847. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  60848. pixels[offset++] = gradient[gradientOffset];
  60849. pixels[offset++] = gradient[gradientOffset + 1];
  60850. pixels[offset++] = gradient[gradientOffset + 2];
  60851. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  60852. } else {
  60853. offset += 4;
  60854. }
  60855. }
  60856. ctx.putImageData(imageData, 0, 0);
  60857. return canvas;
  60858. };
  60859. /**
  60860. * get canvas of a black circle brush used for canvas to draw later
  60861. */
  60862. HeatmapLayer.prototype._getBrush = function () {
  60863. var brushCanvas = this._brushCanvas || (this._brushCanvas = platformApi.createCanvas()); // set brush size
  60864. var r = this.pointSize + this.blurSize;
  60865. var d = r * 2;
  60866. brushCanvas.width = d;
  60867. brushCanvas.height = d;
  60868. var ctx = brushCanvas.getContext('2d');
  60869. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  60870. // draw the distinct circle in an invisible place,
  60871. // and use shadowOffset to draw shadow in the center of the canvas
  60872. ctx.shadowOffsetX = d;
  60873. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  60874. // color in color map
  60875. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  60876. ctx.beginPath();
  60877. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  60878. ctx.closePath();
  60879. ctx.fill();
  60880. return brushCanvas;
  60881. };
  60882. /**
  60883. * get gradient color map
  60884. * @private
  60885. */
  60886. HeatmapLayer.prototype._getGradient = function (colorFunc, state) {
  60887. var gradientPixels = this._gradientPixels;
  60888. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  60889. var color = [0, 0, 0, 0];
  60890. var off = 0;
  60891. for (var i = 0; i < 256; i++) {
  60892. colorFunc[state](i / 255, true, color);
  60893. pixelsSingleState[off++] = color[0];
  60894. pixelsSingleState[off++] = color[1];
  60895. pixelsSingleState[off++] = color[2];
  60896. pixelsSingleState[off++] = color[3];
  60897. }
  60898. return pixelsSingleState;
  60899. };
  60900. return HeatmapLayer;
  60901. }();
  60902. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  60903. var dataSpan = dataExtent[1] - dataExtent[0];
  60904. pieceList = map(pieceList, function (piece) {
  60905. return {
  60906. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  60907. };
  60908. });
  60909. var len = pieceList.length;
  60910. var lastIndex = 0;
  60911. return function (val) {
  60912. var i; // Try to find in the location of the last found
  60913. for (i = lastIndex; i < len; i++) {
  60914. var interval = pieceList[i].interval;
  60915. if (interval[0] <= val && val <= interval[1]) {
  60916. lastIndex = i;
  60917. break;
  60918. }
  60919. }
  60920. if (i === len) {
  60921. // Not found, back interation
  60922. for (i = lastIndex - 1; i >= 0; i--) {
  60923. var interval = pieceList[i].interval;
  60924. if (interval[0] <= val && val <= interval[1]) {
  60925. lastIndex = i;
  60926. break;
  60927. }
  60928. }
  60929. }
  60930. return i >= 0 && i < len && selected[i];
  60931. };
  60932. }
  60933. function getIsInContinuousRange(dataExtent, range) {
  60934. var dataSpan = dataExtent[1] - dataExtent[0];
  60935. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  60936. return function (val) {
  60937. return val >= range[0] && val <= range[1];
  60938. };
  60939. }
  60940. function isGeoCoordSys(coordSys) {
  60941. var dimensions = coordSys.dimensions; // Not use coordSys.type === 'geo' because coordSys maybe extended
  60942. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  60943. }
  60944. var HeatmapView =
  60945. /** @class */
  60946. function (_super) {
  60947. __extends(HeatmapView, _super);
  60948. function HeatmapView() {
  60949. var _this = _super !== null && _super.apply(this, arguments) || this;
  60950. _this.type = HeatmapView.type;
  60951. return _this;
  60952. }
  60953. HeatmapView.prototype.render = function (seriesModel, ecModel, api) {
  60954. var visualMapOfThisSeries;
  60955. ecModel.eachComponent('visualMap', function (visualMap) {
  60956. visualMap.eachTargetSeries(function (targetSeries) {
  60957. if (targetSeries === seriesModel) {
  60958. visualMapOfThisSeries = visualMap;
  60959. }
  60960. });
  60961. });
  60962. if ("development" !== 'production') {
  60963. if (!visualMapOfThisSeries) {
  60964. throw new Error('Heatmap must use with visualMap');
  60965. }
  60966. } // Clear previously rendered progressive elements.
  60967. this._progressiveEls = null;
  60968. this.group.removeAll();
  60969. var coordSys = seriesModel.coordinateSystem;
  60970. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  60971. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  60972. } else if (isGeoCoordSys(coordSys)) {
  60973. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  60974. }
  60975. };
  60976. HeatmapView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  60977. this.group.removeAll();
  60978. };
  60979. HeatmapView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  60980. var coordSys = seriesModel.coordinateSystem;
  60981. if (coordSys) {
  60982. // geo does not support incremental rendering?
  60983. if (isGeoCoordSys(coordSys)) {
  60984. this.render(seriesModel, ecModel, api);
  60985. } else {
  60986. this._progressiveEls = [];
  60987. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  60988. }
  60989. }
  60990. };
  60991. HeatmapView.prototype.eachRendered = function (cb) {
  60992. traverseElements(this._progressiveEls || this.group, cb);
  60993. };
  60994. HeatmapView.prototype._renderOnCartesianAndCalendar = function (seriesModel, api, start, end, incremental) {
  60995. var coordSys = seriesModel.coordinateSystem;
  60996. var isCartesian2d = isCoordinateSystemType(coordSys, 'cartesian2d');
  60997. var width;
  60998. var height;
  60999. var xAxisExtent;
  61000. var yAxisExtent;
  61001. if (isCartesian2d) {
  61002. var xAxis = coordSys.getAxis('x');
  61003. var yAxis = coordSys.getAxis('y');
  61004. if ("development" !== 'production') {
  61005. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  61006. throw new Error('Heatmap on cartesian must have two category axes');
  61007. }
  61008. if (!(xAxis.onBand && yAxis.onBand)) {
  61009. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  61010. }
  61011. } // add 0.5px to avoid the gaps
  61012. width = xAxis.getBandWidth() + .5;
  61013. height = yAxis.getBandWidth() + .5;
  61014. xAxisExtent = xAxis.scale.getExtent();
  61015. yAxisExtent = yAxis.scale.getExtent();
  61016. }
  61017. var group = this.group;
  61018. var data = seriesModel.getData();
  61019. var emphasisStyle = seriesModel.getModel(['emphasis', 'itemStyle']).getItemStyle();
  61020. var blurStyle = seriesModel.getModel(['blur', 'itemStyle']).getItemStyle();
  61021. var selectStyle = seriesModel.getModel(['select', 'itemStyle']).getItemStyle();
  61022. var borderRadius = seriesModel.get(['itemStyle', 'borderRadius']);
  61023. var labelStatesModels = getLabelStatesModels(seriesModel);
  61024. var emphasisModel = seriesModel.getModel('emphasis');
  61025. var focus = emphasisModel.get('focus');
  61026. var blurScope = emphasisModel.get('blurScope');
  61027. var emphasisDisabled = emphasisModel.get('disabled');
  61028. var dataDims = isCartesian2d ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  61029. for (var idx = start; idx < end; idx++) {
  61030. var rect = void 0;
  61031. var style = data.getItemVisual(idx, 'style');
  61032. if (isCartesian2d) {
  61033. var dataDimX = data.get(dataDims[0], idx);
  61034. var dataDimY = data.get(dataDims[1], idx); // Ignore empty data and out of extent data
  61035. if (isNaN(data.get(dataDims[2], idx)) || isNaN(dataDimX) || isNaN(dataDimY) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) {
  61036. continue;
  61037. }
  61038. var point = coordSys.dataToPoint([dataDimX, dataDimY]);
  61039. rect = new Rect({
  61040. shape: {
  61041. x: point[0] - width / 2,
  61042. y: point[1] - height / 2,
  61043. width: width,
  61044. height: height
  61045. },
  61046. style: style
  61047. });
  61048. } else {
  61049. // Ignore empty data
  61050. if (isNaN(data.get(dataDims[1], idx))) {
  61051. continue;
  61052. }
  61053. rect = new Rect({
  61054. z2: 1,
  61055. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  61056. style: style
  61057. });
  61058. } // Optimization for large dataset
  61059. if (data.hasItemOption) {
  61060. var itemModel = data.getItemModel(idx);
  61061. var emphasisModel_1 = itemModel.getModel('emphasis');
  61062. emphasisStyle = emphasisModel_1.getModel('itemStyle').getItemStyle();
  61063. blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  61064. selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle(); // Each item value struct in the data would be firstly
  61065. // {
  61066. // itemStyle: { borderRadius: [30, 30] },
  61067. // value: [2022, 02, 22]
  61068. // }
  61069. borderRadius = itemModel.get(['itemStyle', 'borderRadius']);
  61070. focus = emphasisModel_1.get('focus');
  61071. blurScope = emphasisModel_1.get('blurScope');
  61072. emphasisDisabled = emphasisModel_1.get('disabled');
  61073. labelStatesModels = getLabelStatesModels(itemModel);
  61074. }
  61075. rect.shape.r = borderRadius;
  61076. var rawValue = seriesModel.getRawValue(idx);
  61077. var defaultText = '-';
  61078. if (rawValue && rawValue[2] != null) {
  61079. defaultText = rawValue[2] + '';
  61080. }
  61081. setLabelStyle(rect, labelStatesModels, {
  61082. labelFetcher: seriesModel,
  61083. labelDataIndex: idx,
  61084. defaultOpacity: style.opacity,
  61085. defaultText: defaultText
  61086. });
  61087. rect.ensureState('emphasis').style = emphasisStyle;
  61088. rect.ensureState('blur').style = blurStyle;
  61089. rect.ensureState('select').style = selectStyle;
  61090. toggleHoverEmphasis(rect, focus, blurScope, emphasisDisabled);
  61091. rect.incremental = incremental; // PENDING
  61092. if (incremental) {
  61093. // Rect must use hover layer if it's incremental.
  61094. rect.states.emphasis.hoverLayer = true;
  61095. }
  61096. group.add(rect);
  61097. data.setItemGraphicEl(idx, rect);
  61098. if (this._progressiveEls) {
  61099. this._progressiveEls.push(rect);
  61100. }
  61101. }
  61102. };
  61103. HeatmapView.prototype._renderOnGeo = function (geo, seriesModel, visualMapModel, api) {
  61104. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  61105. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  61106. // throw new Error('Data range must have color visuals');
  61107. // }
  61108. var data = seriesModel.getData();
  61109. var hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer();
  61110. hmLayer.blurSize = seriesModel.get('blurSize');
  61111. hmLayer.pointSize = seriesModel.get('pointSize');
  61112. hmLayer.minOpacity = seriesModel.get('minOpacity');
  61113. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  61114. var rect = geo.getViewRect().clone();
  61115. var roamTransform = geo.getRoamTransform();
  61116. rect.applyTransform(roamTransform); // Clamp on viewport
  61117. var x = Math.max(rect.x, 0);
  61118. var y = Math.max(rect.y, 0);
  61119. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  61120. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  61121. var width = x2 - x;
  61122. var height = y2 - y;
  61123. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  61124. var points = data.mapArray(dims, function (lng, lat, value) {
  61125. var pt = geo.dataToPoint([lng, lat]);
  61126. pt[0] -= x;
  61127. pt[1] -= y;
  61128. pt.push(value);
  61129. return pt;
  61130. });
  61131. var dataExtent = visualMapModel.getExtent();
  61132. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  61133. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  61134. inRange: inRangeVisuals.color.getColorMapper(),
  61135. outOfRange: outOfRangeVisuals.color.getColorMapper()
  61136. }, isInRange);
  61137. var img = new ZRImage({
  61138. style: {
  61139. width: width,
  61140. height: height,
  61141. x: x,
  61142. y: y,
  61143. image: hmLayer.canvas
  61144. },
  61145. silent: true
  61146. });
  61147. this.group.add(img);
  61148. };
  61149. HeatmapView.type = 'heatmap';
  61150. return HeatmapView;
  61151. }(ChartView);
  61152. var HeatmapSeriesModel =
  61153. /** @class */
  61154. function (_super) {
  61155. __extends(HeatmapSeriesModel, _super);
  61156. function HeatmapSeriesModel() {
  61157. var _this = _super !== null && _super.apply(this, arguments) || this;
  61158. _this.type = HeatmapSeriesModel.type;
  61159. return _this;
  61160. }
  61161. HeatmapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61162. return createSeriesData(null, this, {
  61163. generateCoord: 'value'
  61164. });
  61165. };
  61166. HeatmapSeriesModel.prototype.preventIncremental = function () {
  61167. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  61168. if (coordSysCreator && coordSysCreator.dimensions) {
  61169. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  61170. }
  61171. };
  61172. HeatmapSeriesModel.type = 'series.heatmap';
  61173. HeatmapSeriesModel.dependencies = ['grid', 'geo', 'calendar'];
  61174. HeatmapSeriesModel.defaultOption = {
  61175. coordinateSystem: 'cartesian2d',
  61176. // zlevel: 0,
  61177. z: 2,
  61178. // Cartesian coordinate system
  61179. // xAxisIndex: 0,
  61180. // yAxisIndex: 0,
  61181. // Geo coordinate system
  61182. geoIndex: 0,
  61183. blurSize: 30,
  61184. pointSize: 20,
  61185. maxOpacity: 1,
  61186. minOpacity: 0,
  61187. select: {
  61188. itemStyle: {
  61189. borderColor: '#212121'
  61190. }
  61191. }
  61192. };
  61193. return HeatmapSeriesModel;
  61194. }(SeriesModel);
  61195. function install$n(registers) {
  61196. registers.registerChartView(HeatmapView);
  61197. registers.registerSeriesModel(HeatmapSeriesModel);
  61198. }
  61199. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  61200. var LAYOUT_ATTRS = [{
  61201. xy: 'x',
  61202. wh: 'width',
  61203. index: 0,
  61204. posDesc: ['left', 'right']
  61205. }, {
  61206. xy: 'y',
  61207. wh: 'height',
  61208. index: 1,
  61209. posDesc: ['top', 'bottom']
  61210. }];
  61211. var pathForLineWidth = new Circle();
  61212. var PictorialBarView =
  61213. /** @class */
  61214. function (_super) {
  61215. __extends(PictorialBarView, _super);
  61216. function PictorialBarView() {
  61217. var _this = _super !== null && _super.apply(this, arguments) || this;
  61218. _this.type = PictorialBarView.type;
  61219. return _this;
  61220. }
  61221. PictorialBarView.prototype.render = function (seriesModel, ecModel, api) {
  61222. var group = this.group;
  61223. var data = seriesModel.getData();
  61224. var oldData = this._data;
  61225. var cartesian = seriesModel.coordinateSystem;
  61226. var baseAxis = cartesian.getBaseAxis();
  61227. var isHorizontal = baseAxis.isHorizontal();
  61228. var coordSysRect = cartesian.master.getRect();
  61229. var opt = {
  61230. ecSize: {
  61231. width: api.getWidth(),
  61232. height: api.getHeight()
  61233. },
  61234. seriesModel: seriesModel,
  61235. coordSys: cartesian,
  61236. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  61237. isHorizontal: isHorizontal,
  61238. valueDim: LAYOUT_ATTRS[+isHorizontal],
  61239. categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
  61240. };
  61241. data.diff(oldData).add(function (dataIndex) {
  61242. if (!data.hasValue(dataIndex)) {
  61243. return;
  61244. }
  61245. var itemModel = getItemModel(data, dataIndex);
  61246. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  61247. var bar = createBar(data, opt, symbolMeta);
  61248. data.setItemGraphicEl(dataIndex, bar);
  61249. group.add(bar);
  61250. updateCommon$1(bar, opt, symbolMeta);
  61251. }).update(function (newIndex, oldIndex) {
  61252. var bar = oldData.getItemGraphicEl(oldIndex);
  61253. if (!data.hasValue(newIndex)) {
  61254. group.remove(bar);
  61255. return;
  61256. }
  61257. var itemModel = getItemModel(data, newIndex);
  61258. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  61259. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  61260. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  61261. group.remove(bar);
  61262. data.setItemGraphicEl(newIndex, null);
  61263. bar = null;
  61264. }
  61265. if (bar) {
  61266. updateBar(bar, opt, symbolMeta);
  61267. } else {
  61268. bar = createBar(data, opt, symbolMeta, true);
  61269. }
  61270. data.setItemGraphicEl(newIndex, bar);
  61271. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  61272. group.add(bar);
  61273. updateCommon$1(bar, opt, symbolMeta);
  61274. }).remove(function (dataIndex) {
  61275. var bar = oldData.getItemGraphicEl(dataIndex);
  61276. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  61277. }).execute();
  61278. this._data = data;
  61279. return this.group;
  61280. };
  61281. PictorialBarView.prototype.remove = function (ecModel, api) {
  61282. var group = this.group;
  61283. var data = this._data;
  61284. if (ecModel.get('animation')) {
  61285. if (data) {
  61286. data.eachItemGraphicEl(function (bar) {
  61287. removeBar(data, getECData(bar).dataIndex, ecModel, bar);
  61288. });
  61289. }
  61290. } else {
  61291. group.removeAll();
  61292. }
  61293. };
  61294. PictorialBarView.type = 'pictorialBar';
  61295. return PictorialBarView;
  61296. }(ChartView); // Set or calculate default value about symbol, and calculate layout info.
  61297. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  61298. var layout = data.getItemLayout(dataIndex);
  61299. var symbolRepeat = itemModel.get('symbolRepeat');
  61300. var symbolClip = itemModel.get('symbolClip');
  61301. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  61302. var symbolRotate = itemModel.get('symbolRotate');
  61303. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  61304. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  61305. var isAnimationEnabled = itemModel.isAnimationEnabled();
  61306. var symbolMeta = {
  61307. dataIndex: dataIndex,
  61308. layout: layout,
  61309. itemModel: itemModel,
  61310. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  61311. style: data.getItemVisual(dataIndex, 'style'),
  61312. symbolClip: symbolClip,
  61313. symbolRepeat: symbolRepeat,
  61314. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  61315. symbolPatternSize: symbolPatternSize,
  61316. rotation: rotation,
  61317. animationModel: isAnimationEnabled ? itemModel : null,
  61318. hoverScale: isAnimationEnabled && itemModel.get(['emphasis', 'scale']),
  61319. z2: itemModel.getShallow('z', true) || 0
  61320. };
  61321. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  61322. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  61323. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  61324. var symbolSize = symbolMeta.symbolSize;
  61325. var symbolOffset = normalizeSymbolOffset(itemModel.get('symbolOffset'), symbolSize);
  61326. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  61327. return symbolMeta;
  61328. } // bar length can be negative.
  61329. function prepareBarLength(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
  61330. var valueDim = opt.valueDim;
  61331. var symbolBoundingData = itemModel.get('symbolBoundingData');
  61332. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  61333. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  61334. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  61335. var boundingLength;
  61336. if (isArray(symbolBoundingData)) {
  61337. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  61338. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  61339. boundingLength = symbolBoundingExtent[pxSignIdx];
  61340. } else if (symbolBoundingData != null) {
  61341. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  61342. } else if (symbolRepeat) {
  61343. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  61344. } else {
  61345. boundingLength = layout[valueDim.wh];
  61346. }
  61347. outputSymbolMeta.boundingLength = boundingLength;
  61348. if (symbolRepeat) {
  61349. outputSymbolMeta.repeatCutLength = layout[valueDim.wh];
  61350. } // if 'pxSign' means sign of pixel, it can't be zero, or symbolScale will be zero
  61351. // and when borderWidth be settled, the actual linewidth will be NaN
  61352. outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : -1;
  61353. }
  61354. function convertToCoordOnAxis(axis, value) {
  61355. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  61356. } // Support ['100%', '100%']
  61357. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, outputSymbolMeta) {
  61358. var valueDim = opt.valueDim;
  61359. var categoryDim = opt.categoryDim;
  61360. var categorySize = Math.abs(layout[categoryDim.wh]);
  61361. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  61362. var parsedSymbolSize;
  61363. if (isArray(symbolSize)) {
  61364. parsedSymbolSize = symbolSize.slice();
  61365. } else {
  61366. if (symbolSize == null) {
  61367. // will parse to number below
  61368. parsedSymbolSize = ['100%', '100%'];
  61369. } else {
  61370. parsedSymbolSize = [symbolSize, symbolSize];
  61371. }
  61372. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  61373. // to complicated to calculate real percent value if considering scaled lineWidth.
  61374. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  61375. // which can be tolerated in pictorial chart.
  61376. parsedSymbolSize[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize);
  61377. parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  61378. outputSymbolMeta.symbolSize = parsedSymbolSize; // If x or y is less than zero, show reversed shape.
  61379. var symbolScale = outputSymbolMeta.symbolScale = [parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  61380. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  61381. }
  61382. function prepareLineWidth(itemModel, symbolScale, rotation, opt, outputSymbolMeta) {
  61383. // In symbols are drawn with scale, so do not need to care about the case that width
  61384. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  61385. // be calculated.
  61386. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  61387. if (valueLineWidth) {
  61388. pathForLineWidth.attr({
  61389. scaleX: symbolScale[0],
  61390. scaleY: symbolScale[1],
  61391. rotation: rotation
  61392. });
  61393. pathForLineWidth.updateTransform();
  61394. valueLineWidth /= pathForLineWidth.getLineScale();
  61395. valueLineWidth *= symbolScale[opt.valueDim.index];
  61396. }
  61397. outputSymbolMeta.valueLineWidth = valueLineWidth || 0;
  61398. }
  61399. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) {
  61400. var categoryDim = opt.categoryDim;
  61401. var valueDim = opt.valueDim;
  61402. var pxSign = outputSymbolMeta.pxSign;
  61403. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  61404. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  61405. // want symbols to rotate on its center, which should not be translated
  61406. // when rotating.
  61407. if (symbolRepeat) {
  61408. var absBoundingLength = Math.abs(boundingLength);
  61409. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  61410. var hasEndGap = false;
  61411. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  61412. hasEndGap = true;
  61413. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  61414. }
  61415. var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  61416. var uLenWithMargin = Math.max(unitLength + symbolMarginNumeric * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  61417. // to ensure that all of the symbols will not be overflow the given area.
  61418. var endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Both final repeatTimes and final symbolMarginNumeric area calculated based on
  61419. // boundingLength.
  61420. var repeatSpecified = isNumeric(symbolRepeat);
  61421. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  61422. // entirely in the given layout area.
  61423. var mDiff = absBoundingLength - repeatTimes * unitLength;
  61424. symbolMarginNumeric = mDiff / 2 / (hasEndGap ? repeatTimes : Math.max(repeatTimes - 1, 1));
  61425. uLenWithMargin = unitLength + symbolMarginNumeric * 2;
  61426. endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Update repeatTimes when not all symbol will be shown.
  61427. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  61428. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  61429. }
  61430. pathLen = repeatTimes * uLenWithMargin - endFix;
  61431. outputSymbolMeta.repeatTimes = repeatTimes;
  61432. outputSymbolMeta.symbolMargin = symbolMarginNumeric;
  61433. }
  61434. var sizeFix = pxSign * (pathLen / 2);
  61435. var pathPosition = outputSymbolMeta.pathPosition = [];
  61436. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  61437. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  61438. if (symbolOffset) {
  61439. pathPosition[0] += symbolOffset[0];
  61440. pathPosition[1] += symbolOffset[1];
  61441. }
  61442. var bundlePosition = outputSymbolMeta.bundlePosition = [];
  61443. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  61444. bundlePosition[valueDim.index] = layout[valueDim.xy];
  61445. var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout);
  61446. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  61447. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  61448. var clipShape = outputSymbolMeta.clipShape = {}; // Consider that symbol may be overflow layout rect.
  61449. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  61450. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  61451. clipShape[valueDim.xy] = 0;
  61452. clipShape[valueDim.wh] = layout[valueDim.wh];
  61453. }
  61454. function createPath(symbolMeta) {
  61455. var symbolPatternSize = symbolMeta.symbolPatternSize;
  61456. var path = createSymbol( // Consider texture img, make a big size.
  61457. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize);
  61458. path.attr({
  61459. culling: true
  61460. });
  61461. path.type !== 'image' && path.setStyle({
  61462. strokeNoScale: true
  61463. });
  61464. return path;
  61465. }
  61466. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  61467. var bundle = bar.__pictorialBundle;
  61468. var symbolSize = symbolMeta.symbolSize;
  61469. var valueLineWidth = symbolMeta.valueLineWidth;
  61470. var pathPosition = symbolMeta.pathPosition;
  61471. var valueDim = opt.valueDim;
  61472. var repeatTimes = symbolMeta.repeatTimes || 0;
  61473. var index = 0;
  61474. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  61475. eachPath(bar, function (path) {
  61476. path.__pictorialAnimationIndex = index;
  61477. path.__pictorialRepeatTimes = repeatTimes;
  61478. if (index < repeatTimes) {
  61479. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  61480. } else {
  61481. updateAttr(path, null, {
  61482. scaleX: 0,
  61483. scaleY: 0
  61484. }, symbolMeta, isUpdate, function () {
  61485. bundle.remove(path);
  61486. });
  61487. } // updateHoverAnimation(path, symbolMeta);
  61488. index++;
  61489. });
  61490. for (; index < repeatTimes; index++) {
  61491. var path = createPath(symbolMeta);
  61492. path.__pictorialAnimationIndex = index;
  61493. path.__pictorialRepeatTimes = repeatTimes;
  61494. bundle.add(path);
  61495. var target = makeTarget(index);
  61496. updateAttr(path, {
  61497. x: target.x,
  61498. y: target.y,
  61499. scaleX: 0,
  61500. scaleY: 0
  61501. }, {
  61502. scaleX: target.scaleX,
  61503. scaleY: target.scaleY,
  61504. rotation: target.rotation
  61505. }, symbolMeta, isUpdate);
  61506. }
  61507. function makeTarget(index) {
  61508. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  61509. // Otherwise: i = index;
  61510. var pxSign = symbolMeta.pxSign;
  61511. var i = index;
  61512. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  61513. i = repeatTimes - 1 - index;
  61514. }
  61515. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  61516. return {
  61517. x: position[0],
  61518. y: position[1],
  61519. scaleX: symbolMeta.symbolScale[0],
  61520. scaleY: symbolMeta.symbolScale[1],
  61521. rotation: symbolMeta.rotation
  61522. };
  61523. }
  61524. }
  61525. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  61526. var bundle = bar.__pictorialBundle;
  61527. var mainPath = bar.__pictorialMainPath;
  61528. if (!mainPath) {
  61529. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  61530. bundle.add(mainPath);
  61531. updateAttr(mainPath, {
  61532. x: symbolMeta.pathPosition[0],
  61533. y: symbolMeta.pathPosition[1],
  61534. scaleX: 0,
  61535. scaleY: 0,
  61536. rotation: symbolMeta.rotation
  61537. }, {
  61538. scaleX: symbolMeta.symbolScale[0],
  61539. scaleY: symbolMeta.symbolScale[1]
  61540. }, symbolMeta, isUpdate);
  61541. } else {
  61542. updateAttr(mainPath, null, {
  61543. x: symbolMeta.pathPosition[0],
  61544. y: symbolMeta.pathPosition[1],
  61545. scaleX: symbolMeta.symbolScale[0],
  61546. scaleY: symbolMeta.symbolScale[1],
  61547. rotation: symbolMeta.rotation
  61548. }, symbolMeta, isUpdate);
  61549. }
  61550. } // bar rect is used for label.
  61551. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  61552. var rectShape = extend({}, symbolMeta.barRectShape);
  61553. var barRect = bar.__pictorialBarRect;
  61554. if (!barRect) {
  61555. barRect = bar.__pictorialBarRect = new Rect({
  61556. z2: 2,
  61557. shape: rectShape,
  61558. silent: true,
  61559. style: {
  61560. stroke: 'transparent',
  61561. fill: 'transparent',
  61562. lineWidth: 0
  61563. }
  61564. });
  61565. barRect.disableMorphing = true;
  61566. bar.add(barRect);
  61567. } else {
  61568. updateAttr(barRect, null, {
  61569. shape: rectShape
  61570. }, symbolMeta, isUpdate);
  61571. }
  61572. }
  61573. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  61574. // If not clip, symbol will be remove and rebuilt.
  61575. if (symbolMeta.symbolClip) {
  61576. var clipPath = bar.__pictorialClipPath;
  61577. var clipShape = extend({}, symbolMeta.clipShape);
  61578. var valueDim = opt.valueDim;
  61579. var animationModel = symbolMeta.animationModel;
  61580. var dataIndex = symbolMeta.dataIndex;
  61581. if (clipPath) {
  61582. updateProps(clipPath, {
  61583. shape: clipShape
  61584. }, animationModel, dataIndex);
  61585. } else {
  61586. clipShape[valueDim.wh] = 0;
  61587. clipPath = new Rect({
  61588. shape: clipShape
  61589. });
  61590. bar.__pictorialBundle.setClipPath(clipPath);
  61591. bar.__pictorialClipPath = clipPath;
  61592. var target = {};
  61593. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  61594. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  61595. shape: target
  61596. }, animationModel, dataIndex);
  61597. }
  61598. }
  61599. }
  61600. function getItemModel(data, dataIndex) {
  61601. var itemModel = data.getItemModel(dataIndex);
  61602. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  61603. itemModel.isAnimationEnabled = isAnimationEnabled;
  61604. return itemModel;
  61605. }
  61606. function getAnimationDelayParams(path) {
  61607. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  61608. return {
  61609. index: path.__pictorialAnimationIndex,
  61610. count: path.__pictorialRepeatTimes
  61611. };
  61612. }
  61613. function isAnimationEnabled() {
  61614. // `animation` prop can be set on itemModel in pictorial bar chart.
  61615. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  61616. }
  61617. function createBar(data, opt, symbolMeta, isUpdate) {
  61618. // bar is the main element for each data.
  61619. var bar = new Group(); // bundle is used for location and clip.
  61620. var bundle = new Group();
  61621. bar.add(bundle);
  61622. bar.__pictorialBundle = bundle;
  61623. bundle.x = symbolMeta.bundlePosition[0];
  61624. bundle.y = symbolMeta.bundlePosition[1];
  61625. if (symbolMeta.symbolRepeat) {
  61626. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  61627. } else {
  61628. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  61629. }
  61630. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  61631. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  61632. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  61633. bar.__pictorialSymbolMeta = symbolMeta;
  61634. return bar;
  61635. }
  61636. function updateBar(bar, opt, symbolMeta) {
  61637. var animationModel = symbolMeta.animationModel;
  61638. var dataIndex = symbolMeta.dataIndex;
  61639. var bundle = bar.__pictorialBundle;
  61640. updateProps(bundle, {
  61641. x: symbolMeta.bundlePosition[0],
  61642. y: symbolMeta.bundlePosition[1]
  61643. }, animationModel, dataIndex);
  61644. if (symbolMeta.symbolRepeat) {
  61645. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  61646. } else {
  61647. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  61648. }
  61649. createOrUpdateBarRect(bar, symbolMeta, true);
  61650. createOrUpdateClip(bar, opt, symbolMeta, true);
  61651. }
  61652. function removeBar(data, dataIndex, animationModel, bar) {
  61653. // Not show text when animating
  61654. var labelRect = bar.__pictorialBarRect;
  61655. labelRect && labelRect.removeTextContent();
  61656. var paths = [];
  61657. eachPath(bar, function (path) {
  61658. paths.push(path);
  61659. });
  61660. bar.__pictorialMainPath && paths.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  61661. bar.__pictorialClipPath && (animationModel = null);
  61662. each(paths, function (path) {
  61663. removeElement(path, {
  61664. scaleX: 0,
  61665. scaleY: 0
  61666. }, animationModel, dataIndex, function () {
  61667. bar.parent && bar.parent.remove(bar);
  61668. });
  61669. });
  61670. data.setItemGraphicEl(dataIndex, null);
  61671. }
  61672. function getShapeStr(data, symbolMeta) {
  61673. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  61674. }
  61675. function eachPath(bar, cb, context) {
  61676. // Do not use Group#eachChild, because it do not support remove.
  61677. each(bar.__pictorialBundle.children(), function (el) {
  61678. el !== bar.__pictorialBarRect && cb.call(context, el);
  61679. });
  61680. }
  61681. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  61682. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  61683. if (symbolMeta.symbolClip && !isUpdate) {
  61684. animationAttrs && el.attr(animationAttrs);
  61685. } else {
  61686. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  61687. }
  61688. }
  61689. function updateCommon$1(bar, opt, symbolMeta) {
  61690. var dataIndex = symbolMeta.dataIndex;
  61691. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  61692. // Because symbol provide setColor individually to set fill and stroke
  61693. var emphasisModel = itemModel.getModel('emphasis');
  61694. var emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  61695. var blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  61696. var selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  61697. var cursorStyle = itemModel.getShallow('cursor');
  61698. var focus = emphasisModel.get('focus');
  61699. var blurScope = emphasisModel.get('blurScope');
  61700. var hoverScale = emphasisModel.get('scale');
  61701. eachPath(bar, function (path) {
  61702. if (path instanceof ZRImage) {
  61703. var pathStyle = path.style;
  61704. path.useStyle(extend({
  61705. // TODO other properties like dx, dy ?
  61706. image: pathStyle.image,
  61707. x: pathStyle.x,
  61708. y: pathStyle.y,
  61709. width: pathStyle.width,
  61710. height: pathStyle.height
  61711. }, symbolMeta.style));
  61712. } else {
  61713. path.useStyle(symbolMeta.style);
  61714. }
  61715. var emphasisState = path.ensureState('emphasis');
  61716. emphasisState.style = emphasisStyle;
  61717. if (hoverScale) {
  61718. // NOTE: Must after scale is set after updateAttr
  61719. emphasisState.scaleX = path.scaleX * 1.1;
  61720. emphasisState.scaleY = path.scaleY * 1.1;
  61721. }
  61722. path.ensureState('blur').style = blurStyle;
  61723. path.ensureState('select').style = selectStyle;
  61724. cursorStyle && (path.cursor = cursorStyle);
  61725. path.z2 = symbolMeta.z2;
  61726. });
  61727. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  61728. var barRect = bar.__pictorialBarRect;
  61729. setLabelStyle(barRect, getLabelStatesModels(itemModel), {
  61730. labelFetcher: opt.seriesModel,
  61731. labelDataIndex: dataIndex,
  61732. defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex),
  61733. inheritColor: symbolMeta.style.fill,
  61734. defaultOpacity: symbolMeta.style.opacity,
  61735. defaultOutsidePosition: barPositionOutside
  61736. });
  61737. toggleHoverEmphasis(bar, focus, blurScope, emphasisModel.get('disabled'));
  61738. }
  61739. function toIntTimes(times) {
  61740. var roundedTimes = Math.round(times); // Escapse accurate error
  61741. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  61742. }
  61743. var PictorialBarSeriesModel =
  61744. /** @class */
  61745. function (_super) {
  61746. __extends(PictorialBarSeriesModel, _super);
  61747. function PictorialBarSeriesModel() {
  61748. var _this = _super !== null && _super.apply(this, arguments) || this;
  61749. _this.type = PictorialBarSeriesModel.type;
  61750. _this.hasSymbolVisual = true;
  61751. _this.defaultSymbol = 'roundRect';
  61752. return _this;
  61753. }
  61754. PictorialBarSeriesModel.prototype.getInitialData = function (option) {
  61755. // Disable stack.
  61756. option.stack = null;
  61757. return _super.prototype.getInitialData.apply(this, arguments);
  61758. };
  61759. PictorialBarSeriesModel.type = 'series.pictorialBar';
  61760. PictorialBarSeriesModel.dependencies = ['grid'];
  61761. PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  61762. symbol: 'circle',
  61763. symbolSize: null,
  61764. symbolRotate: null,
  61765. symbolPosition: null,
  61766. symbolOffset: null,
  61767. symbolMargin: null,
  61768. symbolRepeat: false,
  61769. symbolRepeatDirection: 'end',
  61770. symbolClip: false,
  61771. symbolBoundingData: null,
  61772. symbolPatternSize: 400,
  61773. barGap: '-100%',
  61774. // z can be set in data item, which is z2 actually.
  61775. // Disable progressive
  61776. progressive: 0,
  61777. emphasis: {
  61778. // By default pictorialBar do not hover scale. Hover scale is not suitable
  61779. // for the case that both has foreground and background.
  61780. scale: false
  61781. },
  61782. select: {
  61783. itemStyle: {
  61784. borderColor: '#212121'
  61785. }
  61786. }
  61787. });
  61788. return PictorialBarSeriesModel;
  61789. }(BaseBarSeriesModel);
  61790. function install$o(registers) {
  61791. registers.registerChartView(PictorialBarView);
  61792. registers.registerSeriesModel(PictorialBarSeriesModel);
  61793. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'pictorialBar')); // Do layout after other overall layout, which can prepare some information.
  61794. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, createProgressiveLayout('pictorialBar'));
  61795. }
  61796. var ThemeRiverView =
  61797. /** @class */
  61798. function (_super) {
  61799. __extends(ThemeRiverView, _super);
  61800. function ThemeRiverView() {
  61801. var _this = _super !== null && _super.apply(this, arguments) || this;
  61802. _this.type = ThemeRiverView.type;
  61803. _this._layers = [];
  61804. return _this;
  61805. }
  61806. ThemeRiverView.prototype.render = function (seriesModel, ecModel, api) {
  61807. var data = seriesModel.getData();
  61808. var self = this;
  61809. var group = this.group;
  61810. var layersSeries = seriesModel.getLayerSeries();
  61811. var layoutInfo = data.getLayout('layoutInfo');
  61812. var rect = layoutInfo.rect;
  61813. var boundaryGap = layoutInfo.boundaryGap;
  61814. group.x = 0;
  61815. group.y = rect.y + boundaryGap[0];
  61816. function keyGetter(item) {
  61817. return item.name;
  61818. }
  61819. var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter);
  61820. var newLayersGroups = [];
  61821. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  61822. function process(status, idx, oldIdx) {
  61823. var oldLayersGroups = self._layers;
  61824. if (status === 'remove') {
  61825. group.remove(oldLayersGroups[idx]);
  61826. return;
  61827. }
  61828. var points0 = [];
  61829. var points1 = [];
  61830. var style;
  61831. var indices = layersSeries[idx].indices;
  61832. var j = 0;
  61833. for (; j < indices.length; j++) {
  61834. var layout = data.getItemLayout(indices[j]);
  61835. var x = layout.x;
  61836. var y0 = layout.y0;
  61837. var y = layout.y;
  61838. points0.push(x, y0);
  61839. points1.push(x, y0 + y);
  61840. style = data.getItemVisual(indices[j], 'style');
  61841. }
  61842. var polygon;
  61843. var textLayout = data.getItemLayout(indices[0]);
  61844. var labelModel = seriesModel.getModel('label');
  61845. var margin = labelModel.get('margin');
  61846. var emphasisModel = seriesModel.getModel('emphasis');
  61847. if (status === 'add') {
  61848. var layerGroup = newLayersGroups[idx] = new Group();
  61849. polygon = new ECPolygon({
  61850. shape: {
  61851. points: points0,
  61852. stackedOnPoints: points1,
  61853. smooth: 0.4,
  61854. stackedOnSmooth: 0.4,
  61855. smoothConstraint: false
  61856. },
  61857. z2: 0
  61858. });
  61859. layerGroup.add(polygon);
  61860. group.add(layerGroup);
  61861. if (seriesModel.isAnimationEnabled()) {
  61862. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  61863. polygon.removeClipPath();
  61864. }));
  61865. }
  61866. } else {
  61867. var layerGroup = oldLayersGroups[oldIdx];
  61868. polygon = layerGroup.childAt(0);
  61869. group.add(layerGroup);
  61870. newLayersGroups[idx] = layerGroup;
  61871. updateProps(polygon, {
  61872. shape: {
  61873. points: points0,
  61874. stackedOnPoints: points1
  61875. }
  61876. }, seriesModel);
  61877. saveOldStyle(polygon);
  61878. }
  61879. setLabelStyle(polygon, getLabelStatesModels(seriesModel), {
  61880. labelDataIndex: indices[j - 1],
  61881. defaultText: data.getName(indices[j - 1]),
  61882. inheritColor: style.fill
  61883. }, {
  61884. normal: {
  61885. verticalAlign: 'middle' // align: 'right'
  61886. }
  61887. });
  61888. polygon.setTextConfig({
  61889. position: null,
  61890. local: true
  61891. });
  61892. var labelEl = polygon.getTextContent(); // TODO More label position options.
  61893. if (labelEl) {
  61894. labelEl.x = textLayout.x - margin;
  61895. labelEl.y = textLayout.y0 + textLayout.y / 2;
  61896. }
  61897. polygon.useStyle(style);
  61898. data.setItemGraphicEl(idx, polygon);
  61899. setStatesStylesFromModel(polygon, seriesModel);
  61900. toggleHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  61901. }
  61902. this._layersSeries = layersSeries;
  61903. this._layers = newLayersGroups;
  61904. };
  61905. ThemeRiverView.type = 'themeRiver';
  61906. return ThemeRiverView;
  61907. }(ChartView);
  61908. function createGridClipShape$2(rect, seriesModel, cb) {
  61909. var rectEl = new Rect({
  61910. shape: {
  61911. x: rect.x - 10,
  61912. y: rect.y - 10,
  61913. width: 0,
  61914. height: rect.height + 20
  61915. }
  61916. });
  61917. initProps(rectEl, {
  61918. shape: {
  61919. x: rect.x - 50,
  61920. width: rect.width + 100,
  61921. height: rect.height + 20
  61922. }
  61923. }, seriesModel, cb);
  61924. return rectEl;
  61925. }
  61926. var DATA_NAME_INDEX = 2;
  61927. var ThemeRiverSeriesModel =
  61928. /** @class */
  61929. function (_super) {
  61930. __extends(ThemeRiverSeriesModel, _super);
  61931. function ThemeRiverSeriesModel() {
  61932. var _this = _super !== null && _super.apply(this, arguments) || this;
  61933. _this.type = ThemeRiverSeriesModel.type;
  61934. return _this;
  61935. }
  61936. /**
  61937. * @override
  61938. */
  61939. ThemeRiverSeriesModel.prototype.init = function (option) {
  61940. // eslint-disable-next-line
  61941. _super.prototype.init.apply(this, arguments); // Put this function here is for the sake of consistency of code style.
  61942. // Enable legend selection for each data item
  61943. // Use a function instead of direct access because data reference may changed
  61944. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  61945. };
  61946. /**
  61947. * If there is no value of a certain point in the time for some event,set it value to 0.
  61948. *
  61949. * @param {Array} data initial data in the option
  61950. * @return {Array}
  61951. */
  61952. ThemeRiverSeriesModel.prototype.fixData = function (data) {
  61953. var rawDataLength = data.length;
  61954. /**
  61955. * Make sure every layer data get the same keys.
  61956. * The value index tells which layer has visited.
  61957. * {
  61958. * 2014/01/01: -1
  61959. * }
  61960. */
  61961. var timeValueKeys = {}; // grouped data by name
  61962. var groupResult = groupData(data, function (item) {
  61963. if (!timeValueKeys.hasOwnProperty(item[0] + '')) {
  61964. timeValueKeys[item[0] + ''] = -1;
  61965. }
  61966. return item[2];
  61967. });
  61968. var layerData = [];
  61969. groupResult.buckets.each(function (items, key) {
  61970. layerData.push({
  61971. name: key,
  61972. dataList: items
  61973. });
  61974. });
  61975. var layerNum = layerData.length;
  61976. for (var k = 0; k < layerNum; ++k) {
  61977. var name_1 = layerData[k].name;
  61978. for (var j = 0; j < layerData[k].dataList.length; ++j) {
  61979. var timeValue = layerData[k].dataList[j][0] + '';
  61980. timeValueKeys[timeValue] = k;
  61981. }
  61982. for (var timeValue in timeValueKeys) {
  61983. if (timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k) {
  61984. timeValueKeys[timeValue] = k;
  61985. data[rawDataLength] = [timeValue, 0, name_1];
  61986. rawDataLength++;
  61987. }
  61988. }
  61989. }
  61990. return data;
  61991. };
  61992. /**
  61993. * @override
  61994. * @param option the initial option that user gave
  61995. * @param ecModel the model object for themeRiver option
  61996. */
  61997. ThemeRiverSeriesModel.prototype.getInitialData = function (option, ecModel) {
  61998. var singleAxisModel = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  61999. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  62000. var filterData = filter(option.data, function (dataItem) {
  62001. return dataItem[2] !== undefined;
  62002. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  62003. var data = this.fixData(filterData || []);
  62004. var nameList = [];
  62005. var nameMap = this.nameMap = createHashMap();
  62006. var count = 0;
  62007. for (var i = 0; i < data.length; ++i) {
  62008. nameList.push(data[i][DATA_NAME_INDEX]);
  62009. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  62010. nameMap.set(data[i][DATA_NAME_INDEX], count);
  62011. count++;
  62012. }
  62013. }
  62014. var dimensions = prepareSeriesDataSchema(data, {
  62015. coordDimensions: ['single'],
  62016. dimensionsDefine: [{
  62017. name: 'time',
  62018. type: getDimensionTypeByAxis(axisType)
  62019. }, {
  62020. name: 'value',
  62021. type: 'float'
  62022. }, {
  62023. name: 'name',
  62024. type: 'ordinal'
  62025. }],
  62026. encodeDefine: {
  62027. single: 0,
  62028. value: 1,
  62029. itemName: 2
  62030. }
  62031. }).dimensions;
  62032. var list = new SeriesData(dimensions, this);
  62033. list.initData(data);
  62034. return list;
  62035. };
  62036. /**
  62037. * The raw data is divided into multiple layers and each layer
  62038. * has same name.
  62039. */
  62040. ThemeRiverSeriesModel.prototype.getLayerSeries = function () {
  62041. var data = this.getData();
  62042. var lenCount = data.count();
  62043. var indexArr = [];
  62044. for (var i = 0; i < lenCount; ++i) {
  62045. indexArr[i] = i;
  62046. }
  62047. var timeDim = data.mapDimension('single'); // data group by name
  62048. var groupResult = groupData(indexArr, function (index) {
  62049. return data.get('name', index);
  62050. });
  62051. var layerSeries = [];
  62052. groupResult.buckets.each(function (items, key) {
  62053. items.sort(function (index1, index2) {
  62054. return data.get(timeDim, index1) - data.get(timeDim, index2);
  62055. });
  62056. layerSeries.push({
  62057. name: key,
  62058. indices: items
  62059. });
  62060. });
  62061. return layerSeries;
  62062. };
  62063. /**
  62064. * Get data indices for show tooltip content
  62065. */
  62066. ThemeRiverSeriesModel.prototype.getAxisTooltipData = function (dim, value, baseAxis) {
  62067. if (!isArray(dim)) {
  62068. dim = dim ? [dim] : [];
  62069. }
  62070. var data = this.getData();
  62071. var layerSeries = this.getLayerSeries();
  62072. var indices = [];
  62073. var layerNum = layerSeries.length;
  62074. var nestestValue;
  62075. for (var i = 0; i < layerNum; ++i) {
  62076. var minDist = Number.MAX_VALUE;
  62077. var nearestIdx = -1;
  62078. var pointNum = layerSeries[i].indices.length;
  62079. for (var j = 0; j < pointNum; ++j) {
  62080. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  62081. var dist = Math.abs(theValue - value);
  62082. if (dist <= minDist) {
  62083. nestestValue = theValue;
  62084. minDist = dist;
  62085. nearestIdx = layerSeries[i].indices[j];
  62086. }
  62087. }
  62088. indices.push(nearestIdx);
  62089. }
  62090. return {
  62091. dataIndices: indices,
  62092. nestestValue: nestestValue
  62093. };
  62094. };
  62095. ThemeRiverSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  62096. var data = this.getData();
  62097. var name = data.getName(dataIndex);
  62098. var value = data.get(data.mapDimension('value'), dataIndex);
  62099. return createTooltipMarkup('nameValue', {
  62100. name: name,
  62101. value: value
  62102. });
  62103. };
  62104. ThemeRiverSeriesModel.type = 'series.themeRiver';
  62105. ThemeRiverSeriesModel.dependencies = ['singleAxis'];
  62106. ThemeRiverSeriesModel.defaultOption = {
  62107. // zlevel: 0,
  62108. z: 2,
  62109. colorBy: 'data',
  62110. coordinateSystem: 'singleAxis',
  62111. // gap in axis's orthogonal orientation
  62112. boundaryGap: ['10%', '10%'],
  62113. // legendHoverLink: true,
  62114. singleAxisIndex: 0,
  62115. animationEasing: 'linear',
  62116. label: {
  62117. margin: 4,
  62118. show: true,
  62119. position: 'left',
  62120. fontSize: 11
  62121. },
  62122. emphasis: {
  62123. label: {
  62124. show: true
  62125. }
  62126. }
  62127. };
  62128. return ThemeRiverSeriesModel;
  62129. }(SeriesModel);
  62130. function themeRiverLayout(ecModel, api) {
  62131. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  62132. var data = seriesModel.getData();
  62133. var single = seriesModel.coordinateSystem;
  62134. var layoutInfo = {}; // use the axis boundingRect for view
  62135. var rect = single.getRect();
  62136. layoutInfo.rect = rect;
  62137. var boundaryGap = seriesModel.get('boundaryGap');
  62138. var axis = single.getAxis();
  62139. layoutInfo.boundaryGap = boundaryGap;
  62140. if (axis.orient === 'horizontal') {
  62141. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  62142. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  62143. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  62144. doThemeRiverLayout(data, seriesModel, height);
  62145. } else {
  62146. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  62147. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  62148. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  62149. doThemeRiverLayout(data, seriesModel, width);
  62150. }
  62151. data.setLayout('layoutInfo', layoutInfo);
  62152. });
  62153. }
  62154. /**
  62155. * The layout information about themeriver
  62156. *
  62157. * @param data data in the series
  62158. * @param seriesModel the model object of themeRiver series
  62159. * @param height value used to compute every series height
  62160. */
  62161. function doThemeRiverLayout(data, seriesModel, height) {
  62162. if (!data.count()) {
  62163. return;
  62164. }
  62165. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  62166. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  62167. var timeDim = data.mapDimension('single');
  62168. var valueDim = data.mapDimension('value');
  62169. var layerPoints = map(layerSeries, function (singleLayer) {
  62170. return map(singleLayer.indices, function (idx) {
  62171. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  62172. pt[1] = data.get(valueDim, idx);
  62173. return pt;
  62174. });
  62175. });
  62176. var base = computeBaseline(layerPoints);
  62177. var baseLine = base.y0;
  62178. var ky = height / base.max; // set layout information for each item.
  62179. var n = layerSeries.length;
  62180. var m = layerSeries[0].indices.length;
  62181. var baseY0;
  62182. for (var j = 0; j < m; ++j) {
  62183. baseY0 = baseLine[j] * ky;
  62184. data.setItemLayout(layerSeries[0].indices[j], {
  62185. layerIndex: 0,
  62186. x: layerPoints[0][j][0],
  62187. y0: baseY0,
  62188. y: layerPoints[0][j][1] * ky
  62189. });
  62190. for (var i = 1; i < n; ++i) {
  62191. baseY0 += layerPoints[i - 1][j][1] * ky;
  62192. data.setItemLayout(layerSeries[i].indices[j], {
  62193. layerIndex: i,
  62194. x: layerPoints[i][j][0],
  62195. y0: baseY0,
  62196. y: layerPoints[i][j][1] * ky
  62197. });
  62198. }
  62199. }
  62200. }
  62201. /**
  62202. * Compute the baseLine of the rawdata
  62203. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  62204. *
  62205. * @param data the points in each layer
  62206. */
  62207. function computeBaseline(data) {
  62208. var layerNum = data.length;
  62209. var pointNum = data[0].length;
  62210. var sums = [];
  62211. var y0 = [];
  62212. var max = 0;
  62213. for (var i = 0; i < pointNum; ++i) {
  62214. var temp = 0;
  62215. for (var j = 0; j < layerNum; ++j) {
  62216. temp += data[j][i][1];
  62217. }
  62218. if (temp > max) {
  62219. max = temp;
  62220. }
  62221. sums.push(temp);
  62222. }
  62223. for (var k = 0; k < pointNum; ++k) {
  62224. y0[k] = (max - sums[k]) / 2;
  62225. }
  62226. max = 0;
  62227. for (var l = 0; l < pointNum; ++l) {
  62228. var sum = sums[l] + y0[l];
  62229. if (sum > max) {
  62230. max = sum;
  62231. }
  62232. }
  62233. return {
  62234. y0: y0,
  62235. max: max
  62236. };
  62237. }
  62238. function install$p(registers) {
  62239. registers.registerChartView(ThemeRiverView);
  62240. registers.registerSeriesModel(ThemeRiverSeriesModel);
  62241. registers.registerLayout(themeRiverLayout);
  62242. registers.registerProcessor(dataFilter('themeRiver'));
  62243. }
  62244. var DEFAULT_SECTOR_Z = 2;
  62245. var DEFAULT_TEXT_Z = 4;
  62246. /**
  62247. * Sunburstce of Sunburst including Sector, Label, LabelLine
  62248. */
  62249. var SunburstPiece =
  62250. /** @class */
  62251. function (_super) {
  62252. __extends(SunburstPiece, _super);
  62253. function SunburstPiece(node, seriesModel, ecModel, api) {
  62254. var _this = _super.call(this) || this;
  62255. _this.z2 = DEFAULT_SECTOR_Z;
  62256. _this.textConfig = {
  62257. inside: true
  62258. };
  62259. getECData(_this).seriesIndex = seriesModel.seriesIndex;
  62260. var text = new ZRText({
  62261. z2: DEFAULT_TEXT_Z,
  62262. silent: node.getModel().get(['label', 'silent'])
  62263. });
  62264. _this.setTextContent(text);
  62265. _this.updateData(true, node, seriesModel, ecModel, api);
  62266. return _this;
  62267. }
  62268. SunburstPiece.prototype.updateData = function (firstCreate, node, // state: 'emphasis' | 'normal' | 'highlight' | 'downplay',
  62269. seriesModel, ecModel, api) {
  62270. this.node = node;
  62271. node.piece = this;
  62272. seriesModel = seriesModel || this._seriesModel;
  62273. ecModel = ecModel || this._ecModel;
  62274. var sector = this;
  62275. getECData(sector).dataIndex = node.dataIndex;
  62276. var itemModel = node.getModel();
  62277. var emphasisModel = itemModel.getModel('emphasis');
  62278. var layout = node.getLayout();
  62279. var sectorShape = extend({}, layout);
  62280. sectorShape.label = null;
  62281. var normalStyle = node.getVisual('style');
  62282. normalStyle.lineJoin = 'bevel';
  62283. var decal = node.getVisual('decal');
  62284. if (decal) {
  62285. normalStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  62286. }
  62287. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape, true);
  62288. extend(sectorShape, cornerRadius);
  62289. each(SPECIAL_STATES, function (stateName) {
  62290. var state = sector.ensureState(stateName);
  62291. var itemStyleModel = itemModel.getModel([stateName, 'itemStyle']);
  62292. state.style = itemStyleModel.getItemStyle(); // border radius
  62293. var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape);
  62294. if (cornerRadius) {
  62295. state.shape = cornerRadius;
  62296. }
  62297. });
  62298. if (firstCreate) {
  62299. sector.setShape(sectorShape);
  62300. sector.shape.r = layout.r0;
  62301. initProps(sector, {
  62302. shape: {
  62303. r: layout.r
  62304. }
  62305. }, seriesModel, node.dataIndex);
  62306. } else {
  62307. // Disable animation for gradient since no interpolation method
  62308. // is supported for gradient
  62309. updateProps(sector, {
  62310. shape: sectorShape
  62311. }, seriesModel);
  62312. saveOldStyle(sector);
  62313. }
  62314. sector.useStyle(normalStyle);
  62315. this._updateLabel(seriesModel);
  62316. var cursorStyle = itemModel.getShallow('cursor');
  62317. cursorStyle && sector.attr('cursor', cursorStyle);
  62318. this._seriesModel = seriesModel || this._seriesModel;
  62319. this._ecModel = ecModel || this._ecModel;
  62320. var focus = emphasisModel.get('focus');
  62321. var focusOrIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : focus;
  62322. toggleHoverEmphasis(this, focusOrIndices, emphasisModel.get('blurScope'), emphasisModel.get('disabled'));
  62323. };
  62324. SunburstPiece.prototype._updateLabel = function (seriesModel) {
  62325. var _this = this;
  62326. var itemModel = this.node.getModel();
  62327. var normalLabelModel = itemModel.getModel('label');
  62328. var layout = this.node.getLayout();
  62329. var angle = layout.endAngle - layout.startAngle;
  62330. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  62331. var dx = Math.cos(midAngle);
  62332. var dy = Math.sin(midAngle);
  62333. var sector = this;
  62334. var label = sector.getTextContent();
  62335. var dataIndex = this.node.dataIndex;
  62336. var labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI;
  62337. var isNormalShown = normalLabelModel.get('show') && !(labelMinAngle != null && Math.abs(angle) < labelMinAngle);
  62338. label.ignore = !isNormalShown; // TODO use setLabelStyle
  62339. each(DISPLAY_STATES, function (stateName) {
  62340. var labelStateModel = stateName === 'normal' ? itemModel.getModel('label') : itemModel.getModel([stateName, 'label']);
  62341. var isNormal = stateName === 'normal';
  62342. var state = isNormal ? label : label.ensureState(stateName);
  62343. var text = seriesModel.getFormattedLabel(dataIndex, stateName);
  62344. if (isNormal) {
  62345. text = text || _this.node.name;
  62346. }
  62347. state.style = createTextStyle(labelStateModel, {}, null, stateName !== 'normal', true);
  62348. if (text) {
  62349. state.style.text = text;
  62350. } // Not displaying text when angle is too small
  62351. var isShown = labelStateModel.get('show');
  62352. if (isShown != null && !isNormal) {
  62353. state.ignore = !isShown;
  62354. }
  62355. var labelPosition = getLabelAttr(labelStateModel, 'position');
  62356. var sectorState = isNormal ? sector : sector.states[stateName];
  62357. var labelColor = sectorState.style.fill;
  62358. sectorState.textConfig = {
  62359. outsideFill: labelStateModel.get('color') === 'inherit' ? labelColor : null,
  62360. inside: labelPosition !== 'outside'
  62361. };
  62362. var r;
  62363. var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0;
  62364. var textAlign = getLabelAttr(labelStateModel, 'align');
  62365. if (labelPosition === 'outside') {
  62366. r = layout.r + labelPadding;
  62367. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  62368. } else {
  62369. if (!textAlign || textAlign === 'center') {
  62370. // Put label in the center if it's a circle
  62371. if (angle === 2 * Math.PI && layout.r0 === 0) {
  62372. r = 0;
  62373. } else {
  62374. r = (layout.r + layout.r0) / 2;
  62375. }
  62376. textAlign = 'center';
  62377. } else if (textAlign === 'left') {
  62378. r = layout.r0 + labelPadding;
  62379. if (midAngle > Math.PI / 2) {
  62380. textAlign = 'right';
  62381. }
  62382. } else if (textAlign === 'right') {
  62383. r = layout.r - labelPadding;
  62384. if (midAngle > Math.PI / 2) {
  62385. textAlign = 'left';
  62386. }
  62387. }
  62388. }
  62389. state.style.align = textAlign;
  62390. state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle';
  62391. state.x = r * dx + layout.cx;
  62392. state.y = r * dy + layout.cy;
  62393. var rotateType = getLabelAttr(labelStateModel, 'rotate');
  62394. var rotate = 0;
  62395. if (rotateType === 'radial') {
  62396. rotate = normalizeRadian(-midAngle);
  62397. if (rotate > Math.PI / 2 && rotate < Math.PI * 1.5) {
  62398. rotate += Math.PI;
  62399. }
  62400. } else if (rotateType === 'tangential') {
  62401. rotate = Math.PI / 2 - midAngle;
  62402. if (rotate > Math.PI / 2) {
  62403. rotate -= Math.PI;
  62404. } else if (rotate < -Math.PI / 2) {
  62405. rotate += Math.PI;
  62406. }
  62407. } else if (isNumber(rotateType)) {
  62408. rotate = rotateType * Math.PI / 180;
  62409. }
  62410. state.rotation = normalizeRadian(rotate);
  62411. });
  62412. function getLabelAttr(model, name) {
  62413. var stateAttr = model.get(name);
  62414. if (stateAttr == null) {
  62415. return normalLabelModel.get(name);
  62416. }
  62417. return stateAttr;
  62418. }
  62419. label.dirtyStyle();
  62420. };
  62421. return SunburstPiece;
  62422. }(Sector);
  62423. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  62424. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  62425. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  62426. function installSunburstAction(registers) {
  62427. registers.registerAction({
  62428. type: ROOT_TO_NODE_ACTION,
  62429. update: 'updateView'
  62430. }, function (payload, ecModel) {
  62431. ecModel.eachComponent({
  62432. mainType: 'series',
  62433. subType: 'sunburst',
  62434. query: payload
  62435. }, handleRootToNode);
  62436. function handleRootToNode(model, index) {
  62437. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION], model);
  62438. if (targetInfo) {
  62439. var originViewRoot = model.getViewRoot();
  62440. if (originViewRoot) {
  62441. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  62442. }
  62443. model.resetViewRoot(targetInfo.node);
  62444. }
  62445. }
  62446. });
  62447. registers.registerAction({
  62448. type: HIGHLIGHT_ACTION,
  62449. update: 'none'
  62450. }, function (payload, ecModel, api) {
  62451. // Clone
  62452. payload = extend({}, payload);
  62453. ecModel.eachComponent({
  62454. mainType: 'series',
  62455. subType: 'sunburst',
  62456. query: payload
  62457. }, handleHighlight);
  62458. function handleHighlight(model) {
  62459. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  62460. if (targetInfo) {
  62461. payload.dataIndex = targetInfo.node.dataIndex;
  62462. }
  62463. }
  62464. if ("development" !== 'production') {
  62465. deprecateReplaceLog('sunburstHighlight', 'highlight');
  62466. } // Fast forward action
  62467. api.dispatchAction(extend(payload, {
  62468. type: 'highlight'
  62469. }));
  62470. });
  62471. registers.registerAction({
  62472. type: UNHIGHLIGHT_ACTION,
  62473. update: 'updateView'
  62474. }, function (payload, ecModel, api) {
  62475. payload = extend({}, payload);
  62476. if ("development" !== 'production') {
  62477. deprecateReplaceLog('sunburstUnhighlight', 'downplay');
  62478. }
  62479. api.dispatchAction(extend(payload, {
  62480. type: 'downplay'
  62481. }));
  62482. });
  62483. }
  62484. var SunburstView =
  62485. /** @class */
  62486. function (_super) {
  62487. __extends(SunburstView, _super);
  62488. function SunburstView() {
  62489. var _this = _super !== null && _super.apply(this, arguments) || this;
  62490. _this.type = SunburstView.type;
  62491. return _this;
  62492. }
  62493. SunburstView.prototype.render = function (seriesModel, ecModel, api, // @ts-ignore
  62494. payload) {
  62495. var self = this;
  62496. this.seriesModel = seriesModel;
  62497. this.api = api;
  62498. this.ecModel = ecModel;
  62499. var data = seriesModel.getData();
  62500. var virtualRoot = data.tree.root;
  62501. var newRoot = seriesModel.getViewRoot();
  62502. var group = this.group;
  62503. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  62504. var newChildren = [];
  62505. newRoot.eachNode(function (node) {
  62506. newChildren.push(node);
  62507. });
  62508. var oldChildren = this._oldChildren || [];
  62509. dualTravel(newChildren, oldChildren);
  62510. renderRollUp(virtualRoot, newRoot);
  62511. this._initEvents();
  62512. this._oldChildren = newChildren;
  62513. function dualTravel(newChildren, oldChildren) {
  62514. if (newChildren.length === 0 && oldChildren.length === 0) {
  62515. return;
  62516. }
  62517. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  62518. function getKey(node) {
  62519. return node.getId();
  62520. }
  62521. function processNode(newIdx, oldIdx) {
  62522. var newNode = newIdx == null ? null : newChildren[newIdx];
  62523. var oldNode = oldIdx == null ? null : oldChildren[oldIdx];
  62524. doRenderNode(newNode, oldNode);
  62525. }
  62526. }
  62527. function doRenderNode(newNode, oldNode) {
  62528. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  62529. // Not render data with value 0
  62530. newNode = null;
  62531. }
  62532. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  62533. if (oldNode && oldNode.piece) {
  62534. if (newNode) {
  62535. // Update
  62536. oldNode.piece.updateData(false, newNode, seriesModel, ecModel, api); // For tooltip
  62537. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  62538. } else {
  62539. // Remove
  62540. removeNode(oldNode);
  62541. }
  62542. } else if (newNode) {
  62543. // Add
  62544. var piece = new SunburstPiece(newNode, seriesModel, ecModel, api);
  62545. group.add(piece); // For tooltip
  62546. data.setItemGraphicEl(newNode.dataIndex, piece);
  62547. }
  62548. }
  62549. }
  62550. function removeNode(node) {
  62551. if (!node) {
  62552. return;
  62553. }
  62554. if (node.piece) {
  62555. group.remove(node.piece);
  62556. node.piece = null;
  62557. }
  62558. }
  62559. function renderRollUp(virtualRoot, viewRoot) {
  62560. if (viewRoot.depth > 0) {
  62561. // Render
  62562. if (self.virtualPiece) {
  62563. // Update
  62564. self.virtualPiece.updateData(false, virtualRoot, seriesModel, ecModel, api);
  62565. } else {
  62566. // Add
  62567. self.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api);
  62568. group.add(self.virtualPiece);
  62569. } // TODO event scope
  62570. viewRoot.piece.off('click');
  62571. self.virtualPiece.on('click', function (e) {
  62572. self._rootToNode(viewRoot.parentNode);
  62573. });
  62574. } else if (self.virtualPiece) {
  62575. // Remove
  62576. group.remove(self.virtualPiece);
  62577. self.virtualPiece = null;
  62578. }
  62579. }
  62580. };
  62581. /**
  62582. * @private
  62583. */
  62584. SunburstView.prototype._initEvents = function () {
  62585. var _this = this;
  62586. this.group.off('click');
  62587. this.group.on('click', function (e) {
  62588. var targetFound = false;
  62589. var viewRoot = _this.seriesModel.getViewRoot();
  62590. viewRoot.eachNode(function (node) {
  62591. if (!targetFound && node.piece && node.piece === e.target) {
  62592. var nodeClick = node.getModel().get('nodeClick');
  62593. if (nodeClick === 'rootToNode') {
  62594. _this._rootToNode(node);
  62595. } else if (nodeClick === 'link') {
  62596. var itemModel = node.getModel();
  62597. var link = itemModel.get('link');
  62598. if (link) {
  62599. var linkTarget = itemModel.get('target', true) || '_blank';
  62600. windowOpen(link, linkTarget);
  62601. }
  62602. }
  62603. targetFound = true;
  62604. }
  62605. });
  62606. });
  62607. };
  62608. /**
  62609. * @private
  62610. */
  62611. SunburstView.prototype._rootToNode = function (node) {
  62612. if (node !== this.seriesModel.getViewRoot()) {
  62613. this.api.dispatchAction({
  62614. type: ROOT_TO_NODE_ACTION,
  62615. from: this.uid,
  62616. seriesId: this.seriesModel.id,
  62617. targetNode: node
  62618. });
  62619. }
  62620. };
  62621. /**
  62622. * @implement
  62623. */
  62624. SunburstView.prototype.containPoint = function (point, seriesModel) {
  62625. var treeRoot = seriesModel.getData();
  62626. var itemLayout = treeRoot.getItemLayout(0);
  62627. if (itemLayout) {
  62628. var dx = point[0] - itemLayout.cx;
  62629. var dy = point[1] - itemLayout.cy;
  62630. var radius = Math.sqrt(dx * dx + dy * dy);
  62631. return radius <= itemLayout.r && radius >= itemLayout.r0;
  62632. }
  62633. };
  62634. SunburstView.type = 'sunburst';
  62635. return SunburstView;
  62636. }(ChartView);
  62637. var SunburstSeriesModel =
  62638. /** @class */
  62639. function (_super) {
  62640. __extends(SunburstSeriesModel, _super);
  62641. function SunburstSeriesModel() {
  62642. var _this = _super !== null && _super.apply(this, arguments) || this;
  62643. _this.type = SunburstSeriesModel.type;
  62644. _this.ignoreStyleOnData = true;
  62645. return _this;
  62646. }
  62647. SunburstSeriesModel.prototype.getInitialData = function (option, ecModel) {
  62648. // Create a virtual root.
  62649. var root = {
  62650. name: option.name,
  62651. children: option.data
  62652. };
  62653. completeTreeValue$1(root);
  62654. var levelModels = this._levelModels = map(option.levels || [], function (levelDefine) {
  62655. return new Model(levelDefine, this, ecModel);
  62656. }, this); // Make sure always a new tree is created when setOption,
  62657. // in TreemapView, we check whether oldTree === newTree
  62658. // to choose mappings approach among old shapes and new shapes.
  62659. var tree = Tree.createTree(root, this, beforeLink);
  62660. function beforeLink(nodeData) {
  62661. nodeData.wrapMethod('getItemModel', function (model, idx) {
  62662. var node = tree.getNodeByDataIndex(idx);
  62663. var levelModel = levelModels[node.depth];
  62664. levelModel && (model.parentModel = levelModel);
  62665. return model;
  62666. });
  62667. }
  62668. return tree.data;
  62669. };
  62670. SunburstSeriesModel.prototype.optionUpdated = function () {
  62671. this.resetViewRoot();
  62672. };
  62673. /*
  62674. * @override
  62675. */
  62676. SunburstSeriesModel.prototype.getDataParams = function (dataIndex) {
  62677. var params = _super.prototype.getDataParams.apply(this, arguments);
  62678. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  62679. params.treePathInfo = wrapTreePathInfo(node, this);
  62680. return params;
  62681. };
  62682. SunburstSeriesModel.prototype.getLevelModel = function (node) {
  62683. return this._levelModels && this._levelModels[node.depth];
  62684. };
  62685. SunburstSeriesModel.prototype.getViewRoot = function () {
  62686. return this._viewRoot;
  62687. };
  62688. SunburstSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  62689. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  62690. var root = this.getRawData().tree.root;
  62691. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  62692. this._viewRoot = root;
  62693. }
  62694. };
  62695. SunburstSeriesModel.prototype.enableAriaDecal = function () {
  62696. enableAriaDecalForTree(this);
  62697. };
  62698. SunburstSeriesModel.type = 'series.sunburst';
  62699. SunburstSeriesModel.defaultOption = {
  62700. // zlevel: 0,
  62701. z: 2,
  62702. // 默认全局居中
  62703. center: ['50%', '50%'],
  62704. radius: [0, '75%'],
  62705. // 默认顺时针
  62706. clockwise: true,
  62707. startAngle: 90,
  62708. // 最小角度改为0
  62709. minAngle: 0,
  62710. // If still show when all data zero.
  62711. stillShowZeroSum: true,
  62712. // 'rootToNode', 'link', or false
  62713. nodeClick: 'rootToNode',
  62714. renderLabelForZeroData: false,
  62715. label: {
  62716. // could be: 'radial', 'tangential', or 'none'
  62717. rotate: 'radial',
  62718. show: true,
  62719. opacity: 1,
  62720. // 'left' is for inner side of inside, and 'right' is for outer
  62721. // side for inside
  62722. align: 'center',
  62723. position: 'inside',
  62724. distance: 5,
  62725. silent: true
  62726. },
  62727. itemStyle: {
  62728. borderWidth: 1,
  62729. borderColor: 'white',
  62730. borderType: 'solid',
  62731. shadowBlur: 0,
  62732. shadowColor: 'rgba(0, 0, 0, 0.2)',
  62733. shadowOffsetX: 0,
  62734. shadowOffsetY: 0,
  62735. opacity: 1
  62736. },
  62737. emphasis: {
  62738. focus: 'descendant'
  62739. },
  62740. blur: {
  62741. itemStyle: {
  62742. opacity: 0.2
  62743. },
  62744. label: {
  62745. opacity: 0.1
  62746. }
  62747. },
  62748. // Animation type can be expansion, scale.
  62749. animationType: 'expansion',
  62750. animationDuration: 1000,
  62751. animationDurationUpdate: 500,
  62752. data: [],
  62753. /**
  62754. * Sort order.
  62755. *
  62756. * Valid values: 'desc', 'asc', null, or callback function.
  62757. * 'desc' and 'asc' for descend and ascendant order;
  62758. * null for not sorting;
  62759. * example of callback function:
  62760. * function(nodeA, nodeB) {
  62761. * return nodeA.getValue() - nodeB.getValue();
  62762. * }
  62763. */
  62764. sort: 'desc'
  62765. };
  62766. return SunburstSeriesModel;
  62767. }(SeriesModel);
  62768. function completeTreeValue$1(dataNode) {
  62769. // Postorder travel tree.
  62770. // If value of none-leaf node is not set,
  62771. // calculate it by suming up the value of all children.
  62772. var sum = 0;
  62773. each(dataNode.children, function (child) {
  62774. completeTreeValue$1(child);
  62775. var childValue = child.value; // TODO First value of array must be a number
  62776. isArray(childValue) && (childValue = childValue[0]);
  62777. sum += childValue;
  62778. });
  62779. var thisValue = dataNode.value;
  62780. if (isArray(thisValue)) {
  62781. thisValue = thisValue[0];
  62782. }
  62783. if (thisValue == null || isNaN(thisValue)) {
  62784. thisValue = sum;
  62785. } // Value should not less than 0.
  62786. if (thisValue < 0) {
  62787. thisValue = 0;
  62788. }
  62789. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  62790. }
  62791. var RADIAN$2 = Math.PI / 180;
  62792. function sunburstLayout(seriesType, ecModel, api) {
  62793. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  62794. var center = seriesModel.get('center');
  62795. var radius = seriesModel.get('radius');
  62796. if (!isArray(radius)) {
  62797. radius = [0, radius];
  62798. }
  62799. if (!isArray(center)) {
  62800. center = [center, center];
  62801. }
  62802. var width = api.getWidth();
  62803. var height = api.getHeight();
  62804. var size = Math.min(width, height);
  62805. var cx = parsePercent$1(center[0], width);
  62806. var cy = parsePercent$1(center[1], height);
  62807. var r0 = parsePercent$1(radius[0], size / 2);
  62808. var r = parsePercent$1(radius[1], size / 2);
  62809. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  62810. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  62811. var virtualRoot = seriesModel.getData().tree.root;
  62812. var treeRoot = seriesModel.getViewRoot();
  62813. var rootDepth = treeRoot.depth;
  62814. var sort = seriesModel.get('sort');
  62815. if (sort != null) {
  62816. initChildren$1(treeRoot, sort);
  62817. }
  62818. var validDataCount = 0;
  62819. each(treeRoot.children, function (child) {
  62820. !isNaN(child.getValue()) && validDataCount++;
  62821. });
  62822. var sum = treeRoot.getValue(); // Sum may be 0
  62823. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  62824. var renderRollupNode = treeRoot.depth > 0;
  62825. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  62826. var rPerLevel = (r - r0) / (levels || 1);
  62827. var clockwise = seriesModel.get('clockwise');
  62828. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  62829. // let restAngle = PI2;
  62830. // let valueSumLargerThanMinAngle = 0;
  62831. var dir = clockwise ? 1 : -1;
  62832. /**
  62833. * Render a tree
  62834. * @return increased angle
  62835. */
  62836. var renderNode = function (node, startAngle) {
  62837. if (!node) {
  62838. return;
  62839. }
  62840. var endAngle = startAngle; // Render self
  62841. if (node !== virtualRoot) {
  62842. // Tree node is virtual, so it doesn't need to be drawn
  62843. var value = node.getValue();
  62844. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  62845. if (angle < minAngle) {
  62846. angle = minAngle; // restAngle -= minAngle;
  62847. } // else {
  62848. // valueSumLargerThanMinAngle += value;
  62849. // }
  62850. endAngle = startAngle + dir * angle;
  62851. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  62852. var rStart = r0 + rPerLevel * depth;
  62853. var rEnd = r0 + rPerLevel * (depth + 1);
  62854. var levelModel = seriesModel.getLevelModel(node);
  62855. if (levelModel) {
  62856. var r0_1 = levelModel.get('r0', true);
  62857. var r_1 = levelModel.get('r', true);
  62858. var radius_1 = levelModel.get('radius', true);
  62859. if (radius_1 != null) {
  62860. r0_1 = radius_1[0];
  62861. r_1 = radius_1[1];
  62862. }
  62863. r0_1 != null && (rStart = parsePercent$1(r0_1, size / 2));
  62864. r_1 != null && (rEnd = parsePercent$1(r_1, size / 2));
  62865. }
  62866. node.setLayout({
  62867. angle: angle,
  62868. startAngle: startAngle,
  62869. endAngle: endAngle,
  62870. clockwise: clockwise,
  62871. cx: cx,
  62872. cy: cy,
  62873. r0: rStart,
  62874. r: rEnd
  62875. });
  62876. } // Render children
  62877. if (node.children && node.children.length) {
  62878. // currentAngle = startAngle;
  62879. var siblingAngle_1 = 0;
  62880. each(node.children, function (node) {
  62881. siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1);
  62882. });
  62883. }
  62884. return endAngle - startAngle;
  62885. }; // Virtual root node for roll up
  62886. if (renderRollupNode) {
  62887. var rStart = r0;
  62888. var rEnd = r0 + rPerLevel;
  62889. var angle = Math.PI * 2;
  62890. virtualRoot.setLayout({
  62891. angle: angle,
  62892. startAngle: startAngle,
  62893. endAngle: startAngle + angle,
  62894. clockwise: clockwise,
  62895. cx: cx,
  62896. cy: cy,
  62897. r0: rStart,
  62898. r: rEnd
  62899. });
  62900. }
  62901. renderNode(treeRoot, startAngle);
  62902. });
  62903. }
  62904. /**
  62905. * Init node children by order and update visual
  62906. */
  62907. function initChildren$1(node, sortOrder) {
  62908. var children = node.children || [];
  62909. node.children = sort$2(children, sortOrder); // Init children recursively
  62910. if (children.length) {
  62911. each(node.children, function (child) {
  62912. initChildren$1(child, sortOrder);
  62913. });
  62914. }
  62915. }
  62916. /**
  62917. * Sort children nodes
  62918. *
  62919. * @param {TreeNode[]} children children of node to be sorted
  62920. * @param {string | function | null} sort sort method
  62921. * See SunburstSeries.js for details.
  62922. */
  62923. function sort$2(children, sortOrder) {
  62924. if (isFunction(sortOrder)) {
  62925. var sortTargets = map(children, function (child, idx) {
  62926. var value = child.getValue();
  62927. return {
  62928. params: {
  62929. depth: child.depth,
  62930. height: child.height,
  62931. dataIndex: child.dataIndex,
  62932. getValue: function () {
  62933. return value;
  62934. }
  62935. },
  62936. index: idx
  62937. };
  62938. });
  62939. sortTargets.sort(function (a, b) {
  62940. return sortOrder(a.params, b.params);
  62941. });
  62942. return map(sortTargets, function (target) {
  62943. return children[target.index];
  62944. });
  62945. } else {
  62946. var isAsc_1 = sortOrder === 'asc';
  62947. return children.sort(function (a, b) {
  62948. var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1);
  62949. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff;
  62950. });
  62951. }
  62952. }
  62953. function sunburstVisual(ecModel) {
  62954. var paletteScope = {}; // Default color strategy
  62955. function pickColor(node, seriesModel, treeHeight) {
  62956. // Choose color from palette based on the first level.
  62957. var current = node;
  62958. while (current && current.depth > 1) {
  62959. current = current.parentNode;
  62960. }
  62961. var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope);
  62962. if (node.depth > 1 && isString(color)) {
  62963. // Lighter on the deeper level.
  62964. color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5);
  62965. }
  62966. return color;
  62967. }
  62968. ecModel.eachSeriesByType('sunburst', function (seriesModel) {
  62969. var data = seriesModel.getData();
  62970. var tree = data.tree;
  62971. tree.eachNode(function (node) {
  62972. var model = node.getModel();
  62973. var style = model.getModel('itemStyle').getItemStyle();
  62974. if (!style.fill) {
  62975. style.fill = pickColor(node, seriesModel, tree.root.height);
  62976. }
  62977. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  62978. extend(existsStyle, style);
  62979. });
  62980. });
  62981. }
  62982. function install$q(registers) {
  62983. registers.registerChartView(SunburstView);
  62984. registers.registerSeriesModel(SunburstSeriesModel);
  62985. registers.registerLayout(curry(sunburstLayout, 'sunburst'));
  62986. registers.registerProcessor(curry(dataFilter, 'sunburst'));
  62987. registers.registerVisual(sunburstVisual);
  62988. installSunburstAction(registers);
  62989. }
  62990. // `visual('color') visual('borderColor')` is supported.
  62991. var STYLE_VISUAL_TYPE = {
  62992. color: 'fill',
  62993. borderColor: 'stroke'
  62994. };
  62995. var NON_STYLE_VISUAL_PROPS = {
  62996. symbol: 1,
  62997. symbolSize: 1,
  62998. symbolKeepAspect: 1,
  62999. legendIcon: 1,
  63000. visualMeta: 1,
  63001. liftZ: 1,
  63002. decal: 1
  63003. };
  63004. var customInnerStore = makeInner();
  63005. var CustomSeriesModel =
  63006. /** @class */
  63007. function (_super) {
  63008. __extends(CustomSeriesModel, _super);
  63009. function CustomSeriesModel() {
  63010. var _this = _super !== null && _super.apply(this, arguments) || this;
  63011. _this.type = CustomSeriesModel.type;
  63012. return _this;
  63013. }
  63014. CustomSeriesModel.prototype.optionUpdated = function () {
  63015. this.currentZLevel = this.get('zlevel', true);
  63016. this.currentZ = this.get('z', true);
  63017. };
  63018. CustomSeriesModel.prototype.getInitialData = function (option, ecModel) {
  63019. return createSeriesData(null, this);
  63020. };
  63021. CustomSeriesModel.prototype.getDataParams = function (dataIndex, dataType, el) {
  63022. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  63023. el && (params.info = customInnerStore(el).info);
  63024. return params;
  63025. };
  63026. CustomSeriesModel.type = 'series.custom';
  63027. CustomSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  63028. CustomSeriesModel.defaultOption = {
  63029. coordinateSystem: 'cartesian2d',
  63030. // zlevel: 0,
  63031. z: 2,
  63032. legendHoverLink: true,
  63033. // Custom series will not clip by default.
  63034. // Some case will use custom series to draw label
  63035. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  63036. clip: false // Cartesian coordinate system
  63037. // xAxisIndex: 0,
  63038. // yAxisIndex: 0,
  63039. // Polar coordinate system
  63040. // polarIndex: 0,
  63041. // Geo coordinate system
  63042. // geoIndex: 0,
  63043. };
  63044. return CustomSeriesModel;
  63045. }(SeriesModel);
  63046. function dataToCoordSize(dataSize, dataItem) {
  63047. // dataItem is necessary in log axis.
  63048. dataItem = dataItem || [0, 0];
  63049. return map(['x', 'y'], function (dim, dimIdx) {
  63050. var axis = this.getAxis(dim);
  63051. var val = dataItem[dimIdx];
  63052. var halfSize = dataSize[dimIdx] / 2;
  63053. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63054. }, this);
  63055. }
  63056. function cartesianPrepareCustom(coordSys) {
  63057. var rect = coordSys.master.getRect();
  63058. return {
  63059. coordSys: {
  63060. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  63061. type: 'cartesian2d',
  63062. x: rect.x,
  63063. y: rect.y,
  63064. width: rect.width,
  63065. height: rect.height
  63066. },
  63067. api: {
  63068. coord: function (data) {
  63069. // do not provide "out" param
  63070. return coordSys.dataToPoint(data);
  63071. },
  63072. size: bind(dataToCoordSize, coordSys)
  63073. }
  63074. };
  63075. }
  63076. function dataToCoordSize$1(dataSize, dataItem) {
  63077. dataItem = dataItem || [0, 0];
  63078. return map([0, 1], function (dimIdx) {
  63079. var val = dataItem[dimIdx];
  63080. var halfSize = dataSize[dimIdx] / 2;
  63081. var p1 = [];
  63082. var p2 = [];
  63083. p1[dimIdx] = val - halfSize;
  63084. p2[dimIdx] = val + halfSize;
  63085. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  63086. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  63087. }, this);
  63088. }
  63089. function geoPrepareCustom(coordSys) {
  63090. var rect = coordSys.getBoundingRect();
  63091. return {
  63092. coordSys: {
  63093. type: 'geo',
  63094. x: rect.x,
  63095. y: rect.y,
  63096. width: rect.width,
  63097. height: rect.height,
  63098. zoom: coordSys.getZoom()
  63099. },
  63100. api: {
  63101. coord: function (data) {
  63102. // do not provide "out" and noRoam param,
  63103. // Compatible with this usage:
  63104. // echarts.util.map(item.points, api.coord)
  63105. return coordSys.dataToPoint(data);
  63106. },
  63107. size: bind(dataToCoordSize$1, coordSys)
  63108. }
  63109. };
  63110. }
  63111. function dataToCoordSize$2(dataSize, dataItem) {
  63112. // dataItem is necessary in log axis.
  63113. var axis = this.getAxis();
  63114. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  63115. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  63116. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63117. }
  63118. function singlePrepareCustom(coordSys) {
  63119. var rect = coordSys.getRect();
  63120. return {
  63121. coordSys: {
  63122. type: 'singleAxis',
  63123. x: rect.x,
  63124. y: rect.y,
  63125. width: rect.width,
  63126. height: rect.height
  63127. },
  63128. api: {
  63129. coord: function (val) {
  63130. // do not provide "out" param
  63131. return coordSys.dataToPoint(val);
  63132. },
  63133. size: bind(dataToCoordSize$2, coordSys)
  63134. }
  63135. };
  63136. }
  63137. function dataToCoordSize$3(dataSize, dataItem) {
  63138. // dataItem is necessary in log axis.
  63139. dataItem = dataItem || [0, 0];
  63140. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  63141. var getterName = 'get' + dim + 'Axis'; // TODO: TYPE Check Angle Axis
  63142. var axis = this[getterName]();
  63143. var val = dataItem[dimIdx];
  63144. var halfSize = dataSize[dimIdx] / 2;
  63145. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  63146. if (dim === 'Angle') {
  63147. result = result * Math.PI / 180;
  63148. }
  63149. return result;
  63150. }, this);
  63151. }
  63152. function polarPrepareCustom(coordSys) {
  63153. var radiusAxis = coordSys.getRadiusAxis();
  63154. var angleAxis = coordSys.getAngleAxis();
  63155. var radius = radiusAxis.getExtent();
  63156. radius[0] > radius[1] && radius.reverse();
  63157. return {
  63158. coordSys: {
  63159. type: 'polar',
  63160. cx: coordSys.cx,
  63161. cy: coordSys.cy,
  63162. r: radius[1],
  63163. r0: radius[0]
  63164. },
  63165. api: {
  63166. coord: function (data) {
  63167. var radius = radiusAxis.dataToRadius(data[0]);
  63168. var angle = angleAxis.dataToAngle(data[1]);
  63169. var coord = coordSys.coordToPoint([radius, angle]);
  63170. coord.push(radius, angle * Math.PI / 180);
  63171. return coord;
  63172. },
  63173. size: bind(dataToCoordSize$3, coordSys)
  63174. }
  63175. };
  63176. }
  63177. /*
  63178. * Licensed to the Apache Software Foundation (ASF) under one
  63179. * or more contributor license agreements. See the NOTICE file
  63180. * distributed with this work for additional information
  63181. * regarding copyright ownership. The ASF licenses this file
  63182. * to you under the Apache License, Version 2.0 (the
  63183. * "License"); you may not use this file except in compliance
  63184. * with the License. You may obtain a copy of the License at
  63185. *
  63186. * http://www.apache.org/licenses/LICENSE-2.0
  63187. *
  63188. * Unless required by applicable law or agreed to in writing,
  63189. * software distributed under the License is distributed on an
  63190. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63191. * KIND, either express or implied. See the License for the
  63192. * specific language governing permissions and limitations
  63193. * under the License.
  63194. */
  63195. /**
  63196. * AUTO-GENERATED FILE. DO NOT MODIFY.
  63197. */
  63198. /*
  63199. * Licensed to the Apache Software Foundation (ASF) under one
  63200. * or more contributor license agreements. See the NOTICE file
  63201. * distributed with this work for additional information
  63202. * regarding copyright ownership. The ASF licenses this file
  63203. * to you under the Apache License, Version 2.0 (the
  63204. * "License"); you may not use this file except in compliance
  63205. * with the License. You may obtain a copy of the License at
  63206. *
  63207. * http://www.apache.org/licenses/LICENSE-2.0
  63208. *
  63209. * Unless required by applicable law or agreed to in writing,
  63210. * software distributed under the License is distributed on an
  63211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63212. * KIND, either express or implied. See the License for the
  63213. * specific language governing permissions and limitations
  63214. * under the License.
  63215. */
  63216. function calendarPrepareCustom(coordSys) {
  63217. var rect = coordSys.getRect();
  63218. var rangeInfo = coordSys.getRangeInfo();
  63219. return {
  63220. coordSys: {
  63221. type: 'calendar',
  63222. x: rect.x,
  63223. y: rect.y,
  63224. width: rect.width,
  63225. height: rect.height,
  63226. cellWidth: coordSys.getCellWidth(),
  63227. cellHeight: coordSys.getCellHeight(),
  63228. rangeInfo: {
  63229. start: rangeInfo.start,
  63230. end: rangeInfo.end,
  63231. weeks: rangeInfo.weeks,
  63232. dayCount: rangeInfo.allDay
  63233. }
  63234. },
  63235. api: {
  63236. coord: function (data, clamp) {
  63237. return coordSys.dataToPoint(data, clamp);
  63238. }
  63239. }
  63240. };
  63241. }
  63242. var deprecatedLogs = {};
  63243. /**
  63244. * Whether need to call `convertEC4CompatibleStyle`.
  63245. */
  63246. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  63247. // Since echarts5, `RectText` is separated from its host element and style.text
  63248. // does not exist any more. The compat work brings some extra burden on performance.
  63249. // So we provide:
  63250. // `legacy: true` force make compat.
  63251. // `legacy: false`, force do not compat.
  63252. // `legacy` not set: auto detect whether legacy.
  63253. // But in this case we do not compat (difficult to detect and rare case):
  63254. // Becuse custom series and graphic component support "merge", users may firstly
  63255. // only set `textStrokeWidth` style or secondly only set `text`.
  63256. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  63257. && (elType === 'text' || hasOwn(style, 'text')));
  63258. }
  63259. /**
  63260. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  63261. * @param hostStyle The properties might be modified.
  63262. * @return If be text el, `textContentStyle` and `textConfig` will not be returned.
  63263. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  63264. * retried from the `hostStyle`.
  63265. */
  63266. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  63267. var srcStyle = hostStyle;
  63268. var textConfig;
  63269. var textContent;
  63270. var textContentStyle;
  63271. if (elType === 'text') {
  63272. textContentStyle = srcStyle;
  63273. } else {
  63274. textContentStyle = {};
  63275. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  63276. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  63277. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  63278. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  63279. hasOwn(srcStyle, 'fontFamily') && (textContentStyle.fontFamily = srcStyle.fontFamily);
  63280. hasOwn(srcStyle, 'fontSize') && (textContentStyle.fontSize = srcStyle.fontSize);
  63281. hasOwn(srcStyle, 'fontStyle') && (textContentStyle.fontStyle = srcStyle.fontStyle);
  63282. hasOwn(srcStyle, 'fontWeight') && (textContentStyle.fontWeight = srcStyle.fontWeight);
  63283. textContent = {
  63284. type: 'text',
  63285. style: textContentStyle,
  63286. // ec4 does not support rectText trigger.
  63287. // And when text position is different in normal and emphasis
  63288. // => hover text trigger emphasis;
  63289. // => text position changed, leave mouse pointer immediately;
  63290. // That might cause incorrect state.
  63291. silent: true
  63292. };
  63293. textConfig = {};
  63294. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  63295. if (isNormal) {
  63296. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  63297. } else {
  63298. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  63299. }
  63300. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  63301. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  63302. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  63303. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  63304. }
  63305. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  63306. each(textContentStyle.rich, function (richItem) {
  63307. convertEC4CompatibleRichItem(richItem, richItem);
  63308. });
  63309. return {
  63310. textConfig: textConfig,
  63311. textContent: textContent
  63312. };
  63313. }
  63314. /**
  63315. * The result will be set to `out`.
  63316. */
  63317. function convertEC4CompatibleRichItem(out, richItem) {
  63318. if (!richItem) {
  63319. return;
  63320. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  63321. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  63322. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  63323. // richText in ec5.
  63324. // (2) `out === richItem` if and only if `out` is text el or rich item.
  63325. // So we can overwrite existing props in `out` since textXXX has higher priority.
  63326. richItem.font = richItem.textFont || richItem.font;
  63327. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  63328. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  63329. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  63330. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  63331. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  63332. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  63333. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  63334. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  63335. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  63336. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  63337. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  63338. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  63339. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  63340. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  63341. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  63342. }
  63343. /**
  63344. * Convert to pure echarts4 format style.
  63345. * `itemStyle` will be modified, added with ec4 style properties from
  63346. * `textStyle` and `textConfig`.
  63347. *
  63348. * [Caveat]: For simplicity, `insideRollback` in ec4 does not compat, where
  63349. * `styleEmphasis: {textFill: 'red'}` will remove the normal auto added stroke.
  63350. */
  63351. function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) {
  63352. var out = itemStl; // See `custom.ts`, a trick to set extra `textPosition` firstly.
  63353. out.textPosition = out.textPosition || txCfg.position || 'inside';
  63354. txCfg.offset != null && (out.textOffset = txCfg.offset);
  63355. txCfg.rotation != null && (out.textRotation = txCfg.rotation);
  63356. txCfg.distance != null && (out.textDistance = txCfg.distance);
  63357. var isInside = out.textPosition.indexOf('inside') >= 0;
  63358. var hostFill = itemStl.fill || '#000';
  63359. convertToEC4RichItem(out, txStl);
  63360. var textFillNotSet = out.textFill == null;
  63361. if (isInside) {
  63362. if (textFillNotSet) {
  63363. out.textFill = txCfg.insideFill || '#fff';
  63364. !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke);
  63365. !out.textStroke && (out.textStroke = hostFill);
  63366. out.textStrokeWidth == null && (out.textStrokeWidth = 2);
  63367. }
  63368. } else {
  63369. if (textFillNotSet) {
  63370. out.textFill = itemStl.fill || txCfg.outsideFill || '#000';
  63371. }
  63372. !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke);
  63373. }
  63374. out.text = txStl.text;
  63375. out.rich = txStl.rich;
  63376. each(txStl.rich, function (richItem) {
  63377. convertToEC4RichItem(richItem, richItem);
  63378. });
  63379. return out;
  63380. }
  63381. function convertToEC4RichItem(out, richItem) {
  63382. if (!richItem) {
  63383. return;
  63384. }
  63385. hasOwn(richItem, 'fill') && (out.textFill = richItem.fill);
  63386. hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill);
  63387. hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth);
  63388. hasOwn(richItem, 'font') && (out.font = richItem.font);
  63389. hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle);
  63390. hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight);
  63391. hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize);
  63392. hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily);
  63393. hasOwn(richItem, 'align') && (out.textAlign = richItem.align);
  63394. hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign);
  63395. hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight);
  63396. hasOwn(richItem, 'width') && (out.textWidth = richItem.width);
  63397. hasOwn(richItem, 'height') && (out.textHeight = richItem.height);
  63398. hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor);
  63399. hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding);
  63400. hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor);
  63401. hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth);
  63402. hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius);
  63403. hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor);
  63404. hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur);
  63405. hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX);
  63406. hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY);
  63407. hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor);
  63408. hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur);
  63409. hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX);
  63410. hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY);
  63411. }
  63412. function warnDeprecated(deprecated, insteadApproach) {
  63413. if ("development" !== 'production') {
  63414. var key = deprecated + '^_^' + insteadApproach;
  63415. if (!deprecatedLogs[key]) {
  63416. console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach);
  63417. deprecatedLogs[key] = true;
  63418. }
  63419. }
  63420. }
  63421. var LEGACY_TRANSFORM_PROPS_MAP = {
  63422. position: ['x', 'y'],
  63423. scale: ['scaleX', 'scaleY'],
  63424. origin: ['originX', 'originY']
  63425. };
  63426. var LEGACY_TRANSFORM_PROPS = keys(LEGACY_TRANSFORM_PROPS_MAP);
  63427. var TRANSFORM_PROPS_MAP = reduce(TRANSFORMABLE_PROPS, function (obj, key) {
  63428. obj[key] = 1;
  63429. return obj;
  63430. }, {});
  63431. var transformPropNamesStr = TRANSFORMABLE_PROPS.join(', '); // '' means root
  63432. var ELEMENT_ANIMATABLE_PROPS = ['', 'style', 'shape', 'extra'];
  63433. var transitionInnerStore = makeInner();
  63434. function getElementAnimationConfig(animationType, el, elOption, parentModel, dataIndex) {
  63435. var animationProp = animationType + "Animation";
  63436. var config = getAnimationConfig(animationType, parentModel, dataIndex) || {};
  63437. var userDuring = transitionInnerStore(el).userDuring; // Only set when duration is > 0 and it's need to be animated.
  63438. if (config.duration > 0) {
  63439. // For simplicity, if during not specified, the previous during will not work any more.
  63440. config.during = userDuring ? bind(duringCall, {
  63441. el: el,
  63442. userDuring: userDuring
  63443. }) : null;
  63444. config.setToFinal = true;
  63445. config.scope = animationType;
  63446. }
  63447. extend(config, elOption[animationProp]);
  63448. return config;
  63449. }
  63450. function applyUpdateTransition(el, elOption, animatableModel, opts) {
  63451. opts = opts || {};
  63452. var dataIndex = opts.dataIndex,
  63453. isInit = opts.isInit,
  63454. clearStyle = opts.clearStyle;
  63455. var hasAnimation = animatableModel.isAnimationEnabled(); // Save the meta info for further morphing. Like apply on the sub morphing elements.
  63456. var store = transitionInnerStore(el);
  63457. var styleOpt = elOption.style;
  63458. store.userDuring = elOption.during;
  63459. var transFromProps = {};
  63460. var propsToSet = {};
  63461. prepareTransformAllPropsFinal(el, elOption, propsToSet);
  63462. prepareShapeOrExtraAllPropsFinal('shape', elOption, propsToSet);
  63463. prepareShapeOrExtraAllPropsFinal('extra', elOption, propsToSet);
  63464. if (!isInit && hasAnimation) {
  63465. prepareTransformTransitionFrom(el, elOption, transFromProps);
  63466. prepareShapeOrExtraTransitionFrom('shape', el, elOption, transFromProps);
  63467. prepareShapeOrExtraTransitionFrom('extra', el, elOption, transFromProps);
  63468. prepareStyleTransitionFrom(el, elOption, styleOpt, transFromProps);
  63469. }
  63470. propsToSet.style = styleOpt;
  63471. applyPropsDirectly(el, propsToSet, clearStyle);
  63472. applyMiscProps(el, elOption);
  63473. if (hasAnimation) {
  63474. if (isInit) {
  63475. var enterFromProps_1 = {};
  63476. each(ELEMENT_ANIMATABLE_PROPS, function (propName) {
  63477. var prop = propName ? elOption[propName] : elOption;
  63478. if (prop && prop.enterFrom) {
  63479. if (propName) {
  63480. enterFromProps_1[propName] = enterFromProps_1[propName] || {};
  63481. }
  63482. extend(propName ? enterFromProps_1[propName] : enterFromProps_1, prop.enterFrom);
  63483. }
  63484. });
  63485. var config = getElementAnimationConfig('enter', el, elOption, animatableModel, dataIndex);
  63486. if (config.duration > 0) {
  63487. el.animateFrom(enterFromProps_1, config);
  63488. }
  63489. } else {
  63490. applyPropsTransition(el, elOption, dataIndex || 0, animatableModel, transFromProps);
  63491. }
  63492. } // Store leave to be used in leave transition.
  63493. updateLeaveTo(el, elOption);
  63494. styleOpt ? el.dirty() : el.markRedraw();
  63495. }
  63496. function updateLeaveTo(el, elOption) {
  63497. // Try merge to previous set leaveTo
  63498. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63499. for (var i = 0; i < ELEMENT_ANIMATABLE_PROPS.length; i++) {
  63500. var propName = ELEMENT_ANIMATABLE_PROPS[i];
  63501. var prop = propName ? elOption[propName] : elOption;
  63502. if (prop && prop.leaveTo) {
  63503. if (!leaveToProps) {
  63504. leaveToProps = transitionInnerStore(el).leaveToProps = {};
  63505. }
  63506. if (propName) {
  63507. leaveToProps[propName] = leaveToProps[propName] || {};
  63508. }
  63509. extend(propName ? leaveToProps[propName] : leaveToProps, prop.leaveTo);
  63510. }
  63511. }
  63512. }
  63513. function applyLeaveTransition(el, elOption, animatableModel, onRemove) {
  63514. if (el) {
  63515. var parent_1 = el.parent;
  63516. var leaveToProps = transitionInnerStore(el).leaveToProps;
  63517. if (leaveToProps) {
  63518. // TODO TODO use leave after leaveAnimation in series is introduced
  63519. // TODO Data index?
  63520. var config = getElementAnimationConfig('update', el, elOption, animatableModel, 0);
  63521. config.done = function () {
  63522. parent_1.remove(el);
  63523. onRemove && onRemove();
  63524. };
  63525. el.animateTo(leaveToProps, config);
  63526. } else {
  63527. parent_1.remove(el);
  63528. onRemove && onRemove();
  63529. }
  63530. }
  63531. }
  63532. function isTransitionAll(transition) {
  63533. return transition === 'all';
  63534. }
  63535. function applyPropsDirectly(el, // Can be null/undefined
  63536. allPropsFinal, clearStyle) {
  63537. var styleOpt = allPropsFinal.style;
  63538. if (!el.isGroup && styleOpt) {
  63539. if (clearStyle) {
  63540. el.useStyle({}); // When style object changed, how to trade the existing animation?
  63541. // It is probably complicated and not needed to cover all the cases.
  63542. // But still need consider the case:
  63543. // (1) When using init animation on `style.opacity`, and before the animation
  63544. // ended users triggers an update by mousewhel. At that time the init
  63545. // animation should better be continued rather than terminated.
  63546. // So after `useStyle` called, we should change the animation target manually
  63547. // to continue the effect of the init animation.
  63548. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  63549. // to update the value to `val2` and no animation declared, should be terminate
  63550. // the previous animation or just modify the target of the animation?
  63551. // Therotically That will happen not only on `style` but also on `shape` and
  63552. // `transfrom` props. But we haven't handle this case at present yet.
  63553. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  63554. var animators = el.animators;
  63555. for (var i = 0; i < animators.length; i++) {
  63556. var animator = animators[i]; // targetName is the "topKey".
  63557. if (animator.targetName === 'style') {
  63558. animator.changeTarget(el.style);
  63559. }
  63560. }
  63561. }
  63562. el.setStyle(styleOpt);
  63563. }
  63564. if (allPropsFinal) {
  63565. // Not set style here.
  63566. allPropsFinal.style = null; // Set el to the final state firstly.
  63567. allPropsFinal && el.attr(allPropsFinal);
  63568. allPropsFinal.style = styleOpt;
  63569. }
  63570. }
  63571. function applyPropsTransition(el, elOption, dataIndex, model, // Can be null/undefined
  63572. transFromProps) {
  63573. if (transFromProps) {
  63574. var config = getElementAnimationConfig('update', el, elOption, model, dataIndex);
  63575. if (config.duration > 0) {
  63576. el.animateFrom(transFromProps, config);
  63577. }
  63578. }
  63579. }
  63580. function applyMiscProps(el, elOption) {
  63581. // Merge by default.
  63582. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  63583. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  63584. if (el instanceof Displayable) {
  63585. hasOwn(elOption, 'invisible') && (el.invisible = elOption.invisible);
  63586. }
  63587. if (el instanceof Path) {
  63588. hasOwn(elOption, 'autoBatch') && (el.autoBatch = elOption.autoBatch);
  63589. }
  63590. } // Use it to avoid it be exposed to user.
  63591. var tmpDuringScope = {};
  63592. var transitionDuringAPI = {
  63593. // Usually other props do not need to be changed in animation during.
  63594. setTransform: function (key, val) {
  63595. if ("development" !== 'production') {
  63596. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  63597. }
  63598. tmpDuringScope.el[key] = val;
  63599. return this;
  63600. },
  63601. getTransform: function (key) {
  63602. if ("development" !== 'production') {
  63603. assert(hasOwn(TRANSFORM_PROPS_MAP, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  63604. }
  63605. return tmpDuringScope.el[key];
  63606. },
  63607. setShape: function (key, val) {
  63608. if ("development" !== 'production') {
  63609. assertNotReserved(key);
  63610. }
  63611. var el = tmpDuringScope.el;
  63612. var shape = el.shape || (el.shape = {});
  63613. shape[key] = val;
  63614. el.dirtyShape && el.dirtyShape();
  63615. return this;
  63616. },
  63617. getShape: function (key) {
  63618. if ("development" !== 'production') {
  63619. assertNotReserved(key);
  63620. }
  63621. var shape = tmpDuringScope.el.shape;
  63622. if (shape) {
  63623. return shape[key];
  63624. }
  63625. },
  63626. setStyle: function (key, val) {
  63627. if ("development" !== 'production') {
  63628. assertNotReserved(key);
  63629. }
  63630. var el = tmpDuringScope.el;
  63631. var style = el.style;
  63632. if (style) {
  63633. if ("development" !== 'production') {
  63634. if (eqNaN(val)) {
  63635. warn('style.' + key + ' must not be assigned with NaN.');
  63636. }
  63637. }
  63638. style[key] = val;
  63639. el.dirtyStyle && el.dirtyStyle();
  63640. }
  63641. return this;
  63642. },
  63643. getStyle: function (key) {
  63644. if ("development" !== 'production') {
  63645. assertNotReserved(key);
  63646. }
  63647. var style = tmpDuringScope.el.style;
  63648. if (style) {
  63649. return style[key];
  63650. }
  63651. },
  63652. setExtra: function (key, val) {
  63653. if ("development" !== 'production') {
  63654. assertNotReserved(key);
  63655. }
  63656. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  63657. extra[key] = val;
  63658. return this;
  63659. },
  63660. getExtra: function (key) {
  63661. if ("development" !== 'production') {
  63662. assertNotReserved(key);
  63663. }
  63664. var extra = tmpDuringScope.el.extra;
  63665. if (extra) {
  63666. return extra[key];
  63667. }
  63668. }
  63669. };
  63670. function assertNotReserved(key) {
  63671. if ("development" !== 'production') {
  63672. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  63673. throw new Error('key must not be "' + key + '"');
  63674. }
  63675. }
  63676. }
  63677. function duringCall() {
  63678. // Do not provide "percent" until some requirements come.
  63679. // Because consider thies case:
  63680. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  63681. // And enter duration is different from update duration.
  63682. // Thus it might be confused about the meaning of "percent" in during callback.
  63683. var scope = this;
  63684. var el = scope.el;
  63685. if (!el) {
  63686. return;
  63687. } // If el is remove from zr by reason like legend, during still need to called,
  63688. // because el will be added back to zr and the prop value should not be incorrect.
  63689. var latestUserDuring = transitionInnerStore(el).userDuring;
  63690. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  63691. // If a during is called multiple times in one frame, maybe some users' calculation logic
  63692. // might be wrong (not sure whether this usage exists).
  63693. // The case of a during might be called twice can be: by default there is a animator for
  63694. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  63695. // another animators for 'style'/'shape'/'extra'.
  63696. if (latestUserDuring !== scopeUserDuring) {
  63697. // release
  63698. scope.el = scope.userDuring = null;
  63699. return;
  63700. }
  63701. tmpDuringScope.el = el; // Give no `this` to user in "during" calling.
  63702. scopeUserDuring(transitionDuringAPI); // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  63703. // consider the issue that the prop might be incorrect when return to "normal" state.
  63704. }
  63705. function prepareShapeOrExtraTransitionFrom(mainAttr, fromEl, elOption, transFromProps) {
  63706. var attrOpt = elOption[mainAttr];
  63707. if (!attrOpt) {
  63708. return;
  63709. }
  63710. var elPropsInAttr = fromEl[mainAttr];
  63711. var transFromPropsInAttr;
  63712. if (elPropsInAttr) {
  63713. var transition = elOption.transition;
  63714. var attrTransition = attrOpt.transition;
  63715. if (attrTransition) {
  63716. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63717. if (isTransitionAll(attrTransition)) {
  63718. extend(transFromPropsInAttr, elPropsInAttr);
  63719. } else {
  63720. var transitionKeys = normalizeToArray(attrTransition);
  63721. for (var i = 0; i < transitionKeys.length; i++) {
  63722. var key = transitionKeys[i];
  63723. var elVal = elPropsInAttr[key];
  63724. transFromPropsInAttr[key] = elVal;
  63725. }
  63726. }
  63727. } else if (isTransitionAll(transition) || indexOf(transition, mainAttr) >= 0) {
  63728. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  63729. var elPropsInAttrKeys = keys(elPropsInAttr);
  63730. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  63731. var key = elPropsInAttrKeys[i];
  63732. var elVal = elPropsInAttr[key];
  63733. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  63734. transFromPropsInAttr[key] = elVal;
  63735. }
  63736. }
  63737. }
  63738. }
  63739. }
  63740. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  63741. var attrOpt = elOption[mainAttr];
  63742. if (!attrOpt) {
  63743. return;
  63744. }
  63745. var allPropsInAttr = allProps[mainAttr] = {};
  63746. var keysInAttr = keys(attrOpt);
  63747. for (var i = 0; i < keysInAttr.length; i++) {
  63748. var key = keysInAttr[i]; // To avoid share one object with different element, and
  63749. // to avoid user modify the object inexpectedly, have to clone.
  63750. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  63751. }
  63752. }
  63753. function prepareTransformTransitionFrom(el, elOption, transFromProps) {
  63754. var transition = elOption.transition;
  63755. var transitionKeys = isTransitionAll(transition) ? TRANSFORMABLE_PROPS : normalizeToArray(transition || []);
  63756. for (var i = 0; i < transitionKeys.length; i++) {
  63757. var key = transitionKeys[i];
  63758. if (key === 'style' || key === 'shape' || key === 'extra') {
  63759. continue;
  63760. }
  63761. var elVal = el[key];
  63762. if ("development" !== 'production') {
  63763. checkTransformPropRefer(key, 'el.transition');
  63764. } // Do not clone, animator will perform that clone.
  63765. transFromProps[key] = elVal;
  63766. }
  63767. }
  63768. function prepareTransformAllPropsFinal(el, elOption, allProps) {
  63769. for (var i = 0; i < LEGACY_TRANSFORM_PROPS.length; i++) {
  63770. var legacyName = LEGACY_TRANSFORM_PROPS[i];
  63771. var xyName = LEGACY_TRANSFORM_PROPS_MAP[legacyName];
  63772. var legacyArr = elOption[legacyName];
  63773. if (legacyArr) {
  63774. allProps[xyName[0]] = legacyArr[0];
  63775. allProps[xyName[1]] = legacyArr[1];
  63776. }
  63777. }
  63778. for (var i = 0; i < TRANSFORMABLE_PROPS.length; i++) {
  63779. var key = TRANSFORMABLE_PROPS[i];
  63780. if (elOption[key] != null) {
  63781. allProps[key] = elOption[key];
  63782. }
  63783. }
  63784. }
  63785. function prepareStyleTransitionFrom(fromEl, elOption, styleOpt, transFromProps) {
  63786. if (!styleOpt) {
  63787. return;
  63788. }
  63789. var fromElStyle = fromEl.style;
  63790. var transFromStyleProps;
  63791. if (fromElStyle) {
  63792. var styleTransition = styleOpt.transition;
  63793. var elTransition = elOption.transition;
  63794. if (styleTransition && !isTransitionAll(styleTransition)) {
  63795. var transitionKeys = normalizeToArray(styleTransition);
  63796. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63797. for (var i = 0; i < transitionKeys.length; i++) {
  63798. var key = transitionKeys[i];
  63799. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  63800. transFromStyleProps[key] = elVal;
  63801. }
  63802. } else if (fromEl.getAnimationStyleProps && (isTransitionAll(elTransition) || isTransitionAll(styleTransition) || indexOf(elTransition, 'style') >= 0)) {
  63803. var animationProps = fromEl.getAnimationStyleProps();
  63804. var animationStyleProps = animationProps ? animationProps.style : null;
  63805. if (animationStyleProps) {
  63806. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  63807. var styleKeys = keys(styleOpt);
  63808. for (var i = 0; i < styleKeys.length; i++) {
  63809. var key = styleKeys[i];
  63810. if (animationStyleProps[key]) {
  63811. var elVal = fromElStyle[key];
  63812. transFromStyleProps[key] = elVal;
  63813. }
  63814. }
  63815. }
  63816. }
  63817. }
  63818. }
  63819. function isNonStyleTransitionEnabled(optVal, elVal) {
  63820. // The same as `checkNonStyleTansitionRefer`.
  63821. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  63822. }
  63823. var checkTransformPropRefer;
  63824. if ("development" !== 'production') {
  63825. checkTransformPropRefer = function (key, usedIn) {
  63826. if (!hasOwn(TRANSFORM_PROPS_MAP, key)) {
  63827. warn('Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS_MAP).join('`, `') + '` are permitted.');
  63828. }
  63829. };
  63830. }
  63831. var getStateToRestore = makeInner();
  63832. var KEYFRAME_EXCLUDE_KEYS = ['percent', 'easing', 'shape', 'style', 'extra'];
  63833. /**
  63834. * Stop previous keyframe animation and restore the attributes.
  63835. * Avoid new keyframe animation starts with wrong internal state when the percent: 0 is not set.
  63836. */
  63837. function stopPreviousKeyframeAnimationAndRestore(el) {
  63838. // Stop previous keyframe animation.
  63839. el.stopAnimation('keyframe'); // Restore
  63840. el.attr(getStateToRestore(el));
  63841. }
  63842. function applyKeyframeAnimation(el, animationOpts, animatableModel) {
  63843. if (!animatableModel.isAnimationEnabled() || !animationOpts) {
  63844. return;
  63845. }
  63846. if (isArray(animationOpts)) {
  63847. each(animationOpts, function (singleAnimationOpts) {
  63848. applyKeyframeAnimation(el, singleAnimationOpts, animatableModel);
  63849. });
  63850. return;
  63851. }
  63852. var keyframes = animationOpts.keyframes;
  63853. var duration = animationOpts.duration;
  63854. if (animatableModel && duration == null) {
  63855. // Default to use duration of config.
  63856. // NOTE: animation config from payload will be ignored because they are mainly for transitions.
  63857. var config = getAnimationConfig('enter', animatableModel, 0);
  63858. duration = config && config.duration;
  63859. }
  63860. if (!keyframes || !duration) {
  63861. return;
  63862. }
  63863. var stateToRestore = getStateToRestore(el);
  63864. each(ELEMENT_ANIMATABLE_PROPS, function (targetPropName) {
  63865. if (targetPropName && !el[targetPropName]) {
  63866. return;
  63867. }
  63868. var animator;
  63869. var endFrameIsSet = false; // Sort keyframes by percent.
  63870. keyframes.sort(function (a, b) {
  63871. return a.percent - b.percent;
  63872. });
  63873. each(keyframes, function (kf) {
  63874. // Stop current animation.
  63875. var animators = el.animators;
  63876. var kfValues = targetPropName ? kf[targetPropName] : kf;
  63877. if ("development" !== 'production') {
  63878. if (kf.percent >= 1) {
  63879. endFrameIsSet = true;
  63880. }
  63881. }
  63882. if (!kfValues) {
  63883. return;
  63884. }
  63885. var propKeys = keys(kfValues);
  63886. if (!targetPropName) {
  63887. // PENDING performance?
  63888. propKeys = filter(propKeys, function (key) {
  63889. return indexOf(KEYFRAME_EXCLUDE_KEYS, key) < 0;
  63890. });
  63891. }
  63892. if (!propKeys.length) {
  63893. return;
  63894. }
  63895. if (!animator) {
  63896. animator = el.animate(targetPropName, animationOpts.loop, true);
  63897. animator.scope = 'keyframe';
  63898. }
  63899. for (var i = 0; i < animators.length; i++) {
  63900. // Stop all other animation that is not keyframe.
  63901. if (animators[i] !== animator && animators[i].targetName === animator.targetName) {
  63902. animators[i].stopTracks(propKeys);
  63903. }
  63904. }
  63905. targetPropName && (stateToRestore[targetPropName] = stateToRestore[targetPropName] || {});
  63906. var savedTarget = targetPropName ? stateToRestore[targetPropName] : stateToRestore;
  63907. each(propKeys, function (key) {
  63908. // Save original value.
  63909. savedTarget[key] = ((targetPropName ? el[targetPropName] : el) || {})[key];
  63910. });
  63911. animator.whenWithKeys(duration * kf.percent, kfValues, propKeys, kf.easing);
  63912. });
  63913. if (!animator) {
  63914. return;
  63915. }
  63916. if ("development" !== 'production') {
  63917. if (!endFrameIsSet) {
  63918. warn('End frame with percent: 1 is missing in the keyframeAnimation.', true);
  63919. }
  63920. }
  63921. animator.delay(animationOpts.delay || 0).duration(duration).start(animationOpts.easing);
  63922. });
  63923. }
  63924. var EMPHASIS = 'emphasis';
  63925. var NORMAL = 'normal';
  63926. var BLUR = 'blur';
  63927. var SELECT = 'select';
  63928. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  63929. var PATH_ITEM_STYLE = {
  63930. normal: ['itemStyle'],
  63931. emphasis: [EMPHASIS, 'itemStyle'],
  63932. blur: [BLUR, 'itemStyle'],
  63933. select: [SELECT, 'itemStyle']
  63934. };
  63935. var PATH_LABEL = {
  63936. normal: ['label'],
  63937. emphasis: [EMPHASIS, 'label'],
  63938. blur: [BLUR, 'label'],
  63939. select: [SELECT, 'label']
  63940. };
  63941. var DEFAULT_TRANSITION = ['x', 'y']; // Use prefix to avoid index to be the same as el.name,
  63942. // which will cause weird update animation.
  63943. var GROUP_DIFF_PREFIX = 'e\0\0';
  63944. var attachedTxInfoTmp = {
  63945. normal: {},
  63946. emphasis: {},
  63947. blur: {},
  63948. select: {}
  63949. };
  63950. /**
  63951. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  63952. * of each coordinate systems are not required by each coordinate systems directly, but
  63953. * required by the module `custom`.
  63954. *
  63955. * prepareInfoForCustomSeries {Function}: optional
  63956. * @return {Object} {coordSys: {...}, api: {
  63957. * coord: function (data, clamp) {}, // return point in global.
  63958. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  63959. * }}
  63960. */
  63961. var prepareCustoms = {
  63962. cartesian2d: cartesianPrepareCustom,
  63963. geo: geoPrepareCustom,
  63964. single: singlePrepareCustom,
  63965. polar: polarPrepareCustom,
  63966. calendar: calendarPrepareCustom
  63967. };
  63968. function isPath$1(el) {
  63969. return el instanceof Path;
  63970. }
  63971. function isDisplayable(el) {
  63972. return el instanceof Displayable;
  63973. }
  63974. function copyElement(sourceEl, targetEl) {
  63975. targetEl.copyTransform(sourceEl);
  63976. if (isDisplayable(targetEl) && isDisplayable(sourceEl)) {
  63977. targetEl.setStyle(sourceEl.style);
  63978. targetEl.z = sourceEl.z;
  63979. targetEl.z2 = sourceEl.z2;
  63980. targetEl.zlevel = sourceEl.zlevel;
  63981. targetEl.invisible = sourceEl.invisible;
  63982. targetEl.ignore = sourceEl.ignore;
  63983. if (isPath$1(targetEl) && isPath$1(sourceEl)) {
  63984. targetEl.setShape(sourceEl.shape);
  63985. }
  63986. }
  63987. }
  63988. var CustomChartView =
  63989. /** @class */
  63990. function (_super) {
  63991. __extends(CustomChartView, _super);
  63992. function CustomChartView() {
  63993. var _this = _super !== null && _super.apply(this, arguments) || this;
  63994. _this.type = CustomChartView.type;
  63995. return _this;
  63996. }
  63997. CustomChartView.prototype.render = function (customSeries, ecModel, api, payload) {
  63998. // Clear previously rendered progressive elements.
  63999. this._progressiveEls = null;
  64000. var oldData = this._data;
  64001. var data = customSeries.getData();
  64002. var group = this.group;
  64003. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  64004. if (!oldData) {
  64005. // Previous render is incremental render or first render.
  64006. // Needs remove the incremental rendered elements.
  64007. group.removeAll();
  64008. }
  64009. data.diff(oldData).add(function (newIdx) {
  64010. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  64011. }).remove(function (oldIdx) {
  64012. var el = oldData.getItemGraphicEl(oldIdx);
  64013. el && applyLeaveTransition(el, customInnerStore(el).option, customSeries);
  64014. }).update(function (newIdx, oldIdx) {
  64015. var oldEl = oldData.getItemGraphicEl(oldIdx);
  64016. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  64017. }).execute(); // Do clipping
  64018. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  64019. if (clipPath) {
  64020. group.setClipPath(clipPath);
  64021. } else {
  64022. group.removeClipPath();
  64023. }
  64024. this._data = data;
  64025. };
  64026. CustomChartView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  64027. this.group.removeAll();
  64028. this._data = null;
  64029. };
  64030. CustomChartView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  64031. var data = customSeries.getData();
  64032. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  64033. var progressiveEls = this._progressiveEls = [];
  64034. function setIncrementalAndHoverLayer(el) {
  64035. if (!el.isGroup) {
  64036. el.incremental = true;
  64037. el.ensureState('emphasis').hoverLayer = true;
  64038. }
  64039. }
  64040. for (var idx = params.start; idx < params.end; idx++) {
  64041. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data);
  64042. if (el) {
  64043. el.traverse(setIncrementalAndHoverLayer);
  64044. progressiveEls.push(el);
  64045. }
  64046. }
  64047. };
  64048. CustomChartView.prototype.eachRendered = function (cb) {
  64049. traverseElements(this._progressiveEls || this.group, cb);
  64050. };
  64051. CustomChartView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  64052. var elementName = query.element;
  64053. if (elementName == null || targetEl.name === elementName) {
  64054. return true;
  64055. } // Enable to give a name on a group made by `renderItem`, and listen
  64056. // events that are triggered by its descendents.
  64057. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  64058. if (targetEl.name === elementName) {
  64059. return true;
  64060. }
  64061. }
  64062. return false;
  64063. };
  64064. CustomChartView.type = 'custom';
  64065. return CustomChartView;
  64066. }(ChartView);
  64067. function createEl(elOption) {
  64068. var graphicType = elOption.type;
  64069. var el; // Those graphic elements are not shapes. They should not be
  64070. // overwritten by users, so do them first.
  64071. if (graphicType === 'path') {
  64072. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  64073. var pathRect = shape.width != null && shape.height != null ? {
  64074. x: shape.x || 0,
  64075. y: shape.y || 0,
  64076. width: shape.width,
  64077. height: shape.height
  64078. } : null;
  64079. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  64080. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  64081. customInnerStore(el).customPathData = pathData;
  64082. } else if (graphicType === 'image') {
  64083. el = new ZRImage({});
  64084. customInnerStore(el).customImagePath = elOption.style.image;
  64085. } else if (graphicType === 'text') {
  64086. el = new ZRText({}); // customInnerStore(el).customText = (elOption.style as TextStyleProps).text;
  64087. } else if (graphicType === 'group') {
  64088. el = new Group();
  64089. } else if (graphicType === 'compoundPath') {
  64090. throw new Error('"compoundPath" is not supported yet.');
  64091. } else {
  64092. var Clz = getShapeClass(graphicType);
  64093. if (!Clz) {
  64094. var errMsg = '';
  64095. if ("development" !== 'production') {
  64096. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  64097. }
  64098. throwError(errMsg);
  64099. }
  64100. el = new Clz();
  64101. }
  64102. customInnerStore(el).customGraphicType = graphicType;
  64103. el.name = elOption.name; // Compat ec4: the default z2 lift is 1. If changing the number,
  64104. // some cases probably be broken: hierarchy layout along z, like circle packing,
  64105. // where emphasis only intending to modify color/border rather than lift z2.
  64106. el.z2EmphasisLift = 1;
  64107. el.z2SelectLift = 1;
  64108. return el;
  64109. }
  64110. function updateElNormal( // Can be null/undefined
  64111. api, el, dataIndex, elOption, attachedTxInfo, seriesModel, isInit) {
  64112. // Stop and restore before update any other attributes.
  64113. stopPreviousKeyframeAnimationAndRestore(el);
  64114. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  64115. if (txCfgOpt) {
  64116. // PENDING: whether use user object directly rather than clone?
  64117. // TODO:5.0 textConfig transition animation?
  64118. el.setTextConfig(txCfgOpt);
  64119. } // Default transition ['x', 'y']
  64120. if (elOption && elOption.transition == null) {
  64121. elOption.transition = DEFAULT_TRANSITION;
  64122. } // Do some normalization on style.
  64123. var styleOpt = elOption && elOption.style;
  64124. if (styleOpt) {
  64125. if (el.type === 'text') {
  64126. var textOptionStyle = styleOpt; // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  64127. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  64128. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  64129. }
  64130. var decalPattern = void 0;
  64131. var decalObj = isPath$1(el) ? styleOpt.decal : null;
  64132. if (api && decalObj) {
  64133. decalObj.dirty = true;
  64134. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  64135. } // Always overwrite in case user specify this prop.
  64136. styleOpt.__decalPattern = decalPattern;
  64137. }
  64138. if (isDisplayable(el)) {
  64139. if (styleOpt) {
  64140. var decalPattern = styleOpt.__decalPattern;
  64141. if (decalPattern) {
  64142. styleOpt.decal = decalPattern;
  64143. }
  64144. }
  64145. }
  64146. applyUpdateTransition(el, elOption, seriesModel, {
  64147. dataIndex: dataIndex,
  64148. isInit: isInit,
  64149. clearStyle: true
  64150. });
  64151. applyKeyframeAnimation(el, elOption.keyframeAnimation, seriesModel);
  64152. }
  64153. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo) {
  64154. var elDisplayable = el.isGroup ? null : el;
  64155. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; // PENDING:5.0 support customize scale change and transition animation?
  64156. if (elDisplayable) {
  64157. // By default support auto lift color when hover whether `emphasis` specified.
  64158. var stateObj = elDisplayable.ensureState(state);
  64159. if (styleOpt === false) {
  64160. var existingEmphasisState = elDisplayable.getState(state);
  64161. if (existingEmphasisState) {
  64162. existingEmphasisState.style = null;
  64163. }
  64164. } else {
  64165. // style is needed to enable default emphasis.
  64166. stateObj.style = styleOpt || null;
  64167. } // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  64168. // remove hover style.
  64169. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  64170. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  64171. if (txCfgOpt) {
  64172. stateObj.textConfig = txCfgOpt;
  64173. }
  64174. setDefaultStateProxy(elDisplayable);
  64175. }
  64176. }
  64177. function updateZ$1(el, elOption, seriesModel) {
  64178. // Group not support textContent and not support z yet.
  64179. if (el.isGroup) {
  64180. return;
  64181. }
  64182. var elDisplayable = el;
  64183. var currentZ = seriesModel.currentZ;
  64184. var currentZLevel = seriesModel.currentZLevel; // Always erase.
  64185. elDisplayable.z = currentZ;
  64186. elDisplayable.zlevel = currentZLevel; // z2 must not be null/undefined, otherwise sort error may occur.
  64187. var optZ2 = elOption.z2;
  64188. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  64189. for (var i = 0; i < STATES.length; i++) {
  64190. updateZForEachState(elDisplayable, elOption, STATES[i]);
  64191. }
  64192. }
  64193. function updateZForEachState(elDisplayable, elOption, state) {
  64194. var isNormal = state === NORMAL;
  64195. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  64196. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  64197. var stateObj;
  64198. if (optZ2 != null) {
  64199. // Do not `ensureState` until required.
  64200. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  64201. stateObj.z2 = optZ2 || 0;
  64202. }
  64203. }
  64204. function makeRenderItem(customSeries, data, ecModel, api) {
  64205. var renderItem = customSeries.get('renderItem');
  64206. var coordSys = customSeries.coordinateSystem;
  64207. var prepareResult = {};
  64208. if (coordSys) {
  64209. if ("development" !== 'production') {
  64210. assert(renderItem, 'series.render is required.');
  64211. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  64212. } // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  64213. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  64214. }
  64215. var userAPI = defaults({
  64216. getWidth: api.getWidth,
  64217. getHeight: api.getHeight,
  64218. getZr: api.getZr,
  64219. getDevicePixelRatio: api.getDevicePixelRatio,
  64220. value: value,
  64221. style: style,
  64222. ordinalRawValue: ordinalRawValue,
  64223. styleEmphasis: styleEmphasis,
  64224. visual: visual,
  64225. barLayout: barLayout,
  64226. currentSeriesIndices: currentSeriesIndices,
  64227. font: font
  64228. }, prepareResult.api || {});
  64229. var userParams = {
  64230. // The life cycle of context: current round of rendering.
  64231. // The global life cycle is probably not necessary, because
  64232. // user can store global status by themselves.
  64233. context: {},
  64234. seriesId: customSeries.id,
  64235. seriesName: customSeries.name,
  64236. seriesIndex: customSeries.seriesIndex,
  64237. coordSys: prepareResult.coordSys,
  64238. dataInsideLength: data.count(),
  64239. encode: wrapEncodeDef(customSeries.getData())
  64240. }; // If someday intending to refactor them to a class, should consider do not
  64241. // break change: currently these attribute member are encapsulated in a closure
  64242. // so that do not need to force user to call these method with a scope.
  64243. // Do not support call `api` asynchronously without dataIndexInside input.
  64244. var currDataIndexInside;
  64245. var currItemModel;
  64246. var currItemStyleModels = {};
  64247. var currLabelModels = {};
  64248. var seriesItemStyleModels = {};
  64249. var seriesLabelModels = {};
  64250. for (var i = 0; i < STATES.length; i++) {
  64251. var stateName = STATES[i];
  64252. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  64253. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  64254. }
  64255. function getItemModel(dataIndexInside) {
  64256. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  64257. }
  64258. function getItemStyleModel(dataIndexInside, state) {
  64259. 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]);
  64260. }
  64261. function getLabelModel(dataIndexInside, state) {
  64262. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  64263. }
  64264. return function (dataIndexInside, payload) {
  64265. currDataIndexInside = dataIndexInside;
  64266. currItemModel = null;
  64267. currItemStyleModels = {};
  64268. currLabelModels = {};
  64269. return renderItem && renderItem(defaults({
  64270. dataIndexInside: dataIndexInside,
  64271. dataIndex: data.getRawIndex(dataIndexInside),
  64272. // Can be used for optimization when zoom or roam.
  64273. actionType: payload ? payload.type : null
  64274. }, userParams), userAPI);
  64275. };
  64276. /**
  64277. * @public
  64278. * @param dim by default 0.
  64279. * @param dataIndexInside by default `currDataIndexInside`.
  64280. */
  64281. function value(dim, dataIndexInside) {
  64282. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64283. return data.getStore().get(data.getDimensionIndex(dim || 0), dataIndexInside);
  64284. }
  64285. /**
  64286. * @public
  64287. * @param dim by default 0.
  64288. * @param dataIndexInside by default `currDataIndexInside`.
  64289. */
  64290. function ordinalRawValue(dim, dataIndexInside) {
  64291. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64292. dim = dim || 0;
  64293. var dimInfo = data.getDimensionInfo(dim);
  64294. if (!dimInfo) {
  64295. var dimIndex = data.getDimensionIndex(dim);
  64296. return dimIndex >= 0 ? data.getStore().get(dimIndex, dataIndexInside) : undefined;
  64297. }
  64298. var val = data.get(dimInfo.name, dataIndexInside);
  64299. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  64300. return ordinalMeta ? ordinalMeta.categories[val] : val;
  64301. }
  64302. /**
  64303. * @deprecated The original intention of `api.style` is enable to set itemStyle
  64304. * like other series. But it is not necessary and not easy to give a strict definition
  64305. * of what it returns. And since echarts5 it needs to be make compat work. So
  64306. * deprecates it since echarts5.
  64307. *
  64308. * By default, `visual` is applied to style (to support visualMap).
  64309. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  64310. * it can be implemented as:
  64311. * `api.style({stroke: api.visual('color'), fill: null})`;
  64312. *
  64313. * [Compat]: since ec5, RectText has been separated from its hosts el.
  64314. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  64315. * any more. But `series.label` config is never published in doc.
  64316. * We still compat it in `api.style()`. But not encourage to use it and will still not
  64317. * to pulish it to doc.
  64318. * @public
  64319. * @param dataIndexInside by default `currDataIndexInside`.
  64320. */
  64321. function style(userProps, dataIndexInside) {
  64322. if ("development" !== 'production') {
  64323. warnDeprecated('api.style', 'Please write literal style directly instead.');
  64324. }
  64325. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64326. var style = data.getItemVisual(dataIndexInside, 'style');
  64327. var visualColor = style && style.fill;
  64328. var opacity = style && style.opacity;
  64329. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  64330. visualColor != null && (itemStyle.fill = visualColor);
  64331. opacity != null && (itemStyle.opacity = opacity);
  64332. var opt = {
  64333. inheritColor: isString(visualColor) ? visualColor : '#000'
  64334. };
  64335. var labelModel = getLabelModel(dataIndexInside, NORMAL); // Now that the feature of "auto adjust text fill/stroke" has been migrated to zrender
  64336. // since ec5, we should set `isAttached` as `false` here and make compat in
  64337. // `convertToEC4StyleForCustomSerise`.
  64338. var textStyle = createTextStyle(labelModel, null, opt, false, true);
  64339. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64340. var textConfig = createTextConfig(labelModel, opt, false);
  64341. preFetchFromExtra(userProps, itemStyle);
  64342. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64343. userProps && applyUserPropsAfter(itemStyle, userProps);
  64344. itemStyle.legacy = true;
  64345. return itemStyle;
  64346. }
  64347. /**
  64348. * @deprecated The reason see `api.style()`
  64349. * @public
  64350. * @param dataIndexInside by default `currDataIndexInside`.
  64351. */
  64352. function styleEmphasis(userProps, dataIndexInside) {
  64353. if ("development" !== 'production') {
  64354. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  64355. }
  64356. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64357. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  64358. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  64359. var textStyle = createTextStyle(labelModel, null, null, true, true);
  64360. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  64361. var textConfig = createTextConfig(labelModel, null, true);
  64362. preFetchFromExtra(userProps, itemStyle);
  64363. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  64364. userProps && applyUserPropsAfter(itemStyle, userProps);
  64365. itemStyle.legacy = true;
  64366. return itemStyle;
  64367. }
  64368. function applyUserPropsAfter(itemStyle, extra) {
  64369. for (var key in extra) {
  64370. if (hasOwn(extra, key)) {
  64371. itemStyle[key] = extra[key];
  64372. }
  64373. }
  64374. }
  64375. function preFetchFromExtra(extra, itemStyle) {
  64376. // A trick to retrieve those props firstly, which are used to
  64377. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  64378. // (It's not reasonable but only for a degree of compat)
  64379. if (extra) {
  64380. extra.textFill && (itemStyle.textFill = extra.textFill);
  64381. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  64382. }
  64383. }
  64384. /**
  64385. * @public
  64386. * @param dataIndexInside by default `currDataIndexInside`.
  64387. */
  64388. function visual(visualType, dataIndexInside) {
  64389. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  64390. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  64391. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  64392. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  64393. } // Only support these visuals. Other visual might be inner tricky
  64394. // for performance (like `style`), do not expose to users.
  64395. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  64396. return data.getItemVisual(dataIndexInside, visualType);
  64397. }
  64398. }
  64399. /**
  64400. * @public
  64401. * @return If not support, return undefined.
  64402. */
  64403. function barLayout(opt) {
  64404. if (coordSys.type === 'cartesian2d') {
  64405. var baseAxis = coordSys.getBaseAxis();
  64406. return getLayoutOnAxis(defaults({
  64407. axis: baseAxis
  64408. }, opt));
  64409. }
  64410. }
  64411. /**
  64412. * @public
  64413. */
  64414. function currentSeriesIndices() {
  64415. return ecModel.getCurrentSeriesIndices();
  64416. }
  64417. /**
  64418. * @public
  64419. * @return font string
  64420. */
  64421. function font(opt) {
  64422. return getFont(opt, ecModel);
  64423. }
  64424. }
  64425. function wrapEncodeDef(data) {
  64426. var encodeDef = {};
  64427. each(data.dimensions, function (dimName) {
  64428. var dimInfo = data.getDimensionInfo(dimName);
  64429. if (!dimInfo.isExtraCoord) {
  64430. var coordDim = dimInfo.coordDim;
  64431. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  64432. dataDims[dimInfo.coordDimIndex] = data.getDimensionIndex(dimName);
  64433. }
  64434. });
  64435. return encodeDef;
  64436. }
  64437. function createOrUpdateItem(api, existsEl, dataIndex, elOption, seriesModel, group, data) {
  64438. // [Rule]
  64439. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  64440. // (It seems that violate the "merge" principle, but most of users probably intuitively
  64441. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  64442. // most cases.)
  64443. // The rule or "merge" see [STRATEGY_MERGE].
  64444. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  64445. if (!elOption) {
  64446. group.remove(existsEl);
  64447. return;
  64448. }
  64449. var el = doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group);
  64450. el && data.setItemGraphicEl(dataIndex, el);
  64451. el && toggleHoverEmphasis(el, elOption.focus, elOption.blurScope, elOption.emphasisDisabled);
  64452. return el;
  64453. }
  64454. function doCreateOrUpdateEl(api, existsEl, dataIndex, elOption, seriesModel, group) {
  64455. if ("development" !== 'production') {
  64456. assert(elOption, 'should not have an null/undefined element setting');
  64457. }
  64458. var toBeReplacedIdx = -1;
  64459. var oldEl = existsEl;
  64460. if (existsEl && doesElNeedRecreate(existsEl, elOption, seriesModel) // || (
  64461. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  64462. // // do not sure whether the el will be mapped to another el with different
  64463. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  64464. // morphHelper && morphHelper.isOneToOneFrom(el)
  64465. // )
  64466. ) {
  64467. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  64468. toBeReplacedIdx = indexOf(group.childrenRef(), existsEl);
  64469. existsEl = null;
  64470. }
  64471. var isInit = !existsEl;
  64472. var el = existsEl;
  64473. if (!el) {
  64474. el = createEl(elOption);
  64475. if (oldEl) {
  64476. copyElement(oldEl, el);
  64477. }
  64478. } else {
  64479. // FIMXE:NEXT unified clearState?
  64480. // If in some case the performance issue arised, consider
  64481. // do not clearState but update cached normal state directly.
  64482. el.clearStates();
  64483. } // Need to set morph: false explictly to disable automatically morphing.
  64484. if (elOption.morph === false) {
  64485. el.disableMorphing = true;
  64486. } else if (el.disableMorphing) {
  64487. el.disableMorphing = false;
  64488. }
  64489. 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;
  64490. attachedTxInfoTmp.isLegacy = false;
  64491. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  64492. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  64493. updateElNormal(api, el, dataIndex, elOption, attachedTxInfoTmp, seriesModel, isInit); // `elOption.info` enables user to mount some info on
  64494. // elements and use them in event handlers.
  64495. // Update them only when user specified, otherwise, remain.
  64496. hasOwn(elOption, 'info') && (customInnerStore(el).info = elOption.info);
  64497. for (var i = 0; i < STATES.length; i++) {
  64498. var stateName = STATES[i];
  64499. if (stateName !== NORMAL) {
  64500. var otherStateOpt = retrieveStateOption(elOption, stateName);
  64501. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  64502. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  64503. }
  64504. }
  64505. updateZ$1(el, elOption, seriesModel);
  64506. if (elOption.type === 'group') {
  64507. mergeChildren(api, el, dataIndex, elOption, seriesModel);
  64508. }
  64509. if (toBeReplacedIdx >= 0) {
  64510. group.replaceAt(el, toBeReplacedIdx);
  64511. } else {
  64512. group.add(el);
  64513. }
  64514. return el;
  64515. } // `el` must not be null/undefined.
  64516. function doesElNeedRecreate(el, elOption, seriesModel) {
  64517. var elInner = customInnerStore(el);
  64518. var elOptionType = elOption.type;
  64519. var elOptionShape = elOption.shape;
  64520. var elOptionStyle = elOption.style;
  64521. return (// Always create new if universal transition is enabled.
  64522. // Because we do transition after render. It needs to know what old element is. Replacement will loose it.
  64523. seriesModel.isUniversalTransitionEnabled() // If `elOptionType` is `null`, follow the merge principle.
  64524. || 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?
  64525. // || (elOptionType === 'text'
  64526. // && hasOwn(elOptionStyle, 'text')
  64527. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  64528. // )
  64529. );
  64530. }
  64531. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  64532. // Based on the "merge" principle, if no clipPath provided,
  64533. // do nothing. The exists clip will be totally removed only if
  64534. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  64535. var clipPathOpt = elOption.clipPath;
  64536. if (clipPathOpt === false) {
  64537. if (el && el.getClipPath()) {
  64538. el.removeClipPath();
  64539. }
  64540. } else if (clipPathOpt) {
  64541. var clipPath = el.getClipPath();
  64542. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt, seriesModel)) {
  64543. clipPath = null;
  64544. }
  64545. if (!clipPath) {
  64546. clipPath = createEl(clipPathOpt);
  64547. if ("development" !== 'production') {
  64548. assert(isPath$1(clipPath), 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  64549. }
  64550. el.setClipPath(clipPath);
  64551. }
  64552. updateElNormal(null, clipPath, dataIndex, clipPathOpt, null, seriesModel, isInit);
  64553. } // If not define `clipPath` in option, do nothing unnecessary.
  64554. }
  64555. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  64556. // Group does not support textContent temporarily until necessary.
  64557. if (el.isGroup) {
  64558. return;
  64559. } // Normal must be called before emphasis, for `isLegacy` detection.
  64560. processTxInfo(elOption, null, attachedTxInfo);
  64561. processTxInfo(elOption, EMPHASIS, attachedTxInfo); // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sense.
  64562. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  64563. // trade them as set to null to el.
  64564. // Especially:
  64565. // `elOption.textContent: false` means remove textContent.
  64566. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  64567. var txConOptNormal = attachedTxInfo.normal.conOpt;
  64568. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  64569. var txConOptBlur = attachedTxInfo.blur.conOpt;
  64570. var txConOptSelect = attachedTxInfo.select.conOpt;
  64571. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  64572. var textContent = el.getTextContent();
  64573. if (txConOptNormal === false) {
  64574. textContent && el.removeTextContent();
  64575. } else {
  64576. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  64577. type: 'text'
  64578. };
  64579. if (!textContent) {
  64580. textContent = createEl(txConOptNormal);
  64581. el.setTextContent(textContent);
  64582. } else {
  64583. // If in some case the performance issue arised, consider
  64584. // do not clearState but update cached normal state directly.
  64585. textContent.clearStates();
  64586. }
  64587. updateElNormal(null, textContent, dataIndex, txConOptNormal, null, seriesModel, isInit);
  64588. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  64589. for (var i = 0; i < STATES.length; i++) {
  64590. var stateName = STATES[i];
  64591. if (stateName !== NORMAL) {
  64592. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  64593. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  64594. }
  64595. }
  64596. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  64597. }
  64598. }
  64599. }
  64600. function processTxInfo(elOption, state, attachedTxInfo) {
  64601. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  64602. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  64603. var elType = elOption.type;
  64604. var txCfg = stateOpt ? stateOpt.textConfig : null;
  64605. var txConOptNormal = elOption.textContent;
  64606. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  64607. if (styleOpt && ( // Because emphasis style has little info to detect legacy,
  64608. // if normal is legacy, emphasis is trade as legacy.
  64609. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  64610. attachedTxInfo.isLegacy = true;
  64611. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); // Explicitly specified `textConfig` and `textContent` has higher priority than
  64612. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  64613. // at the same time, they not both work and hardly to known why.
  64614. if (!txCfg && convertResult.textConfig) {
  64615. txCfg = convertResult.textConfig;
  64616. }
  64617. if (!txConOpt && convertResult.textContent) {
  64618. txConOpt = convertResult.textContent;
  64619. }
  64620. }
  64621. if (!state && txConOpt) {
  64622. var txConOptNormal_1 = txConOpt; // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  64623. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  64624. if ("development" !== 'production') {
  64625. // Do not tolerate incorrcet type for forward compat.
  64626. assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  64627. }
  64628. }
  64629. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  64630. info.cfg = txCfg;
  64631. info.conOpt = txConOpt;
  64632. }
  64633. function retrieveStateOption(elOption, state) {
  64634. return !state ? elOption : elOption ? elOption[state] : null;
  64635. }
  64636. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  64637. var style = stateOption && stateOption.style;
  64638. if (style == null && state === EMPHASIS && stateOptionNormal) {
  64639. style = stateOptionNormal.styleEmphasis;
  64640. }
  64641. return style;
  64642. } // Usage:
  64643. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates
  64644. // that the existing children will not be removed, and enables the feature
  64645. // that update some of the props of some of the children simply by construct
  64646. // the returned children of `renderItem` like:
  64647. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  64648. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  64649. // by child.name. But that might be lower performance.
  64650. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  64651. // replaced totally.
  64652. // (4) If `!elOption.children`, following the "merge" principle, nothing will
  64653. // happen.
  64654. // (5) If `elOption.$mergeChildren` is not `false` neither `'byName'` and the
  64655. // `el` is a group, and if any of the new child is null, it means to remove
  64656. // the element at the same index, if exists. On the other hand, if the new
  64657. // child is and empty object `{}`, it means to keep the element not changed.
  64658. //
  64659. // For implementation simpleness, do not provide a direct way to remove single
  64660. // child (otherwise the total indices of the children array have to be modified).
  64661. // User can remove a single child by setting its `ignore` to `true`.
  64662. function mergeChildren(api, el, dataIndex, elOption, seriesModel) {
  64663. var newChildren = elOption.children;
  64664. var newLen = newChildren ? newChildren.length : 0;
  64665. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  64666. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  64667. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  64668. if (!newLen && !byName && !notMerge) {
  64669. return;
  64670. }
  64671. if (byName) {
  64672. diffGroupChildren({
  64673. api: api,
  64674. oldChildren: el.children() || [],
  64675. newChildren: newChildren || [],
  64676. dataIndex: dataIndex,
  64677. seriesModel: seriesModel,
  64678. group: el
  64679. });
  64680. return;
  64681. }
  64682. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  64683. // might be better performance.
  64684. var index = 0;
  64685. for (; index < newLen; index++) {
  64686. var newChild = newChildren[index];
  64687. var oldChild = el.childAt(index);
  64688. if (newChild) {
  64689. if (newChild.ignore == null) {
  64690. // The old child is set to be ignored if null (see comments
  64691. // below). So we need to set ignore to be false back.
  64692. newChild.ignore = false;
  64693. }
  64694. doCreateOrUpdateEl(api, oldChild, dataIndex, newChild, seriesModel, el);
  64695. } else {
  64696. if ("development" !== 'production') {
  64697. assert(oldChild, 'renderItem should not return a group containing elements' + ' as null/undefined/{} if they do not exist before.');
  64698. } // If the new element option is null, it means to remove the old
  64699. // element. But we cannot really remove the element from the group
  64700. // directly, because the element order may not be stable when this
  64701. // element is added back. So we set the element to be ignored.
  64702. oldChild.ignore = true;
  64703. }
  64704. }
  64705. for (var i = el.childCount() - 1; i >= index; i--) {
  64706. var child = el.childAt(i);
  64707. removeChildFromGroup(el, child, seriesModel);
  64708. }
  64709. }
  64710. function removeChildFromGroup(group, child, seriesModel) {
  64711. // Do not support leave elements that are not mentioned in the latest
  64712. // `renderItem` return. Otherwise users may not have a clear and simple
  64713. // concept that how to control all of the elements.
  64714. child && applyLeaveTransition(child, customInnerStore(group).option, seriesModel);
  64715. }
  64716. function diffGroupChildren(context) {
  64717. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  64718. }
  64719. function getKey(item, idx) {
  64720. var name = item && item.name;
  64721. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  64722. }
  64723. function processAddUpdate(newIndex, oldIndex) {
  64724. var context = this.context;
  64725. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  64726. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  64727. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group);
  64728. }
  64729. function processRemove(oldIndex) {
  64730. var context = this.context;
  64731. var child = context.oldChildren[oldIndex];
  64732. child && applyLeaveTransition(child, customInnerStore(child).option, context.seriesModel);
  64733. }
  64734. /**
  64735. * @return SVG Path data.
  64736. */
  64737. function getPathData(shape) {
  64738. // "d" follows the SVG convention.
  64739. return shape && (shape.pathData || shape.d);
  64740. }
  64741. function hasOwnPathData(shape) {
  64742. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  64743. }
  64744. function install$r(registers) {
  64745. registers.registerChartView(CustomChartView);
  64746. registers.registerSeriesModel(CustomSeriesModel);
  64747. }
  64748. var inner$a = makeInner();
  64749. var clone$3 = clone;
  64750. var bind$1 = bind;
  64751. /**
  64752. * Base axis pointer class in 2D.
  64753. */
  64754. var BaseAxisPointer =
  64755. /** @class */
  64756. function () {
  64757. function BaseAxisPointer() {
  64758. this._dragging = false;
  64759. /**
  64760. * In px, arbitrary value. Do not set too small,
  64761. * no animation is ok for most cases.
  64762. */
  64763. this.animationThreshold = 15;
  64764. }
  64765. /**
  64766. * @implement
  64767. */
  64768. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  64769. var value = axisPointerModel.get('value');
  64770. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  64771. // be replaced when user calling setOption in not merge mode.
  64772. this._axisModel = axisModel;
  64773. this._axisPointerModel = axisPointerModel;
  64774. this._api = api; // Optimize: `render` will be called repeatedly during mouse move.
  64775. // So it is power consuming if performing `render` each time,
  64776. // especially on mobile device.
  64777. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  64778. return;
  64779. }
  64780. this._lastValue = value;
  64781. this._lastStatus = status;
  64782. var group = this._group;
  64783. var handle = this._handle;
  64784. if (!status || status === 'hide') {
  64785. // Do not clear here, for animation better.
  64786. group && group.hide();
  64787. handle && handle.hide();
  64788. return;
  64789. }
  64790. group && group.show();
  64791. handle && handle.show(); // Otherwise status is 'show'
  64792. var elOption = {};
  64793. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  64794. var graphicKey = elOption.graphicKey;
  64795. if (graphicKey !== this._lastGraphicKey) {
  64796. this.clear(api);
  64797. }
  64798. this._lastGraphicKey = graphicKey;
  64799. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  64800. if (!group) {
  64801. group = this._group = new Group();
  64802. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  64803. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  64804. api.getZr().add(group);
  64805. } else {
  64806. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  64807. this.updatePointerEl(group, elOption, doUpdateProps);
  64808. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  64809. }
  64810. updateMandatoryProps(group, axisPointerModel, true);
  64811. this._renderHandle(value);
  64812. };
  64813. /**
  64814. * @implement
  64815. */
  64816. BaseAxisPointer.prototype.remove = function (api) {
  64817. this.clear(api);
  64818. };
  64819. /**
  64820. * @implement
  64821. */
  64822. BaseAxisPointer.prototype.dispose = function (api) {
  64823. this.clear(api);
  64824. };
  64825. /**
  64826. * @protected
  64827. */
  64828. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  64829. var animation = axisPointerModel.get('animation');
  64830. var axis = axisModel.axis;
  64831. var isCategoryAxis = axis.type === 'category';
  64832. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  64833. if (!useSnap && !isCategoryAxis) {
  64834. return false;
  64835. }
  64836. if (animation === 'auto' || animation == null) {
  64837. var animationThreshold = this.animationThreshold;
  64838. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  64839. return true;
  64840. } // It is important to auto animation when snap used. Consider if there is
  64841. // a dataZoom, animation will be disabled when too many points exist, while
  64842. // it will be enabled for better visual effect when little points exist.
  64843. if (useSnap) {
  64844. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  64845. var axisExtent = axis.getExtent(); // Approximate band width
  64846. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  64847. }
  64848. return false;
  64849. }
  64850. return animation === true;
  64851. };
  64852. /**
  64853. * add {pointer, label, graphicKey} to elOption
  64854. * @protected
  64855. */
  64856. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Should be implemenented by sub-class.
  64857. };
  64858. /**
  64859. * @protected
  64860. */
  64861. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  64862. var pointerOption = elOption.pointer;
  64863. if (pointerOption) {
  64864. var pointerEl = inner$a(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  64865. group.add(pointerEl);
  64866. }
  64867. };
  64868. /**
  64869. * @protected
  64870. */
  64871. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  64872. if (elOption.label) {
  64873. var labelEl = inner$a(group).labelEl = new ZRText(clone$3(elOption.label));
  64874. group.add(labelEl);
  64875. updateLabelShowHide(labelEl, axisPointerModel);
  64876. }
  64877. };
  64878. /**
  64879. * @protected
  64880. */
  64881. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  64882. var pointerEl = inner$a(group).pointerEl;
  64883. if (pointerEl && elOption.pointer) {
  64884. pointerEl.setStyle(elOption.pointer.style);
  64885. updateProps(pointerEl, {
  64886. shape: elOption.pointer.shape
  64887. });
  64888. }
  64889. };
  64890. /**
  64891. * @protected
  64892. */
  64893. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  64894. var labelEl = inner$a(group).labelEl;
  64895. if (labelEl) {
  64896. labelEl.setStyle(elOption.label.style);
  64897. updateProps(labelEl, {
  64898. // Consider text length change in vertical axis, animation should
  64899. // be used on shape, otherwise the effect will be weird.
  64900. // TODOTODO
  64901. // shape: elOption.label.shape,
  64902. x: elOption.label.x,
  64903. y: elOption.label.y
  64904. });
  64905. updateLabelShowHide(labelEl, axisPointerModel);
  64906. }
  64907. };
  64908. /**
  64909. * @private
  64910. */
  64911. BaseAxisPointer.prototype._renderHandle = function (value) {
  64912. if (this._dragging || !this.updateHandleTransform) {
  64913. return;
  64914. }
  64915. var axisPointerModel = this._axisPointerModel;
  64916. var zr = this._api.getZr();
  64917. var handle = this._handle;
  64918. var handleModel = axisPointerModel.getModel('handle');
  64919. var status = axisPointerModel.get('status');
  64920. if (!handleModel.get('show') || !status || status === 'hide') {
  64921. handle && zr.remove(handle);
  64922. this._handle = null;
  64923. return;
  64924. }
  64925. var isInit;
  64926. if (!this._handle) {
  64927. isInit = true;
  64928. handle = this._handle = createIcon(handleModel.get('icon'), {
  64929. cursor: 'move',
  64930. draggable: true,
  64931. onmousemove: function (e) {
  64932. // For mobile device, prevent screen slider on the button.
  64933. stop(e.event);
  64934. },
  64935. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  64936. drift: bind$1(this._onHandleDragMove, this),
  64937. ondragend: bind$1(this._onHandleDragEnd, this)
  64938. });
  64939. zr.add(handle);
  64940. }
  64941. updateMandatoryProps(handle, axisPointerModel, false); // update style
  64942. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  64943. var handleSize = handleModel.get('size');
  64944. if (!isArray(handleSize)) {
  64945. handleSize = [handleSize, handleSize];
  64946. }
  64947. handle.scaleX = handleSize[0] / 2;
  64948. handle.scaleY = handleSize[1] / 2;
  64949. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  64950. this._moveHandleToValue(value, isInit);
  64951. };
  64952. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  64953. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  64954. };
  64955. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  64956. var handle = this._handle;
  64957. if (!handle) {
  64958. return;
  64959. }
  64960. this._dragging = true; // Persistent for throttle.
  64961. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  64962. this._payloadInfo = trans;
  64963. handle.stopAnimation();
  64964. handle.attr(getHandleTransProps(trans));
  64965. inner$a(handle).lastProp = null;
  64966. this._doDispatchAxisPointer();
  64967. };
  64968. /**
  64969. * Throttled method.
  64970. */
  64971. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  64972. var handle = this._handle;
  64973. if (!handle) {
  64974. return;
  64975. }
  64976. var payloadInfo = this._payloadInfo;
  64977. var axisModel = this._axisModel;
  64978. this._api.dispatchAction({
  64979. type: 'updateAxisPointer',
  64980. x: payloadInfo.cursorPoint[0],
  64981. y: payloadInfo.cursorPoint[1],
  64982. tooltipOption: payloadInfo.tooltipOption,
  64983. axesInfo: [{
  64984. axisDim: axisModel.axis.dim,
  64985. axisIndex: axisModel.componentIndex
  64986. }]
  64987. });
  64988. };
  64989. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  64990. this._dragging = false;
  64991. var handle = this._handle;
  64992. if (!handle) {
  64993. return;
  64994. }
  64995. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  64996. // axisPointer. So move handle to align the exact value position when
  64997. // drag ended.
  64998. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  64999. // button, and will be hidden after finger left handle button.
  65000. this._api.dispatchAction({
  65001. type: 'hideTip'
  65002. });
  65003. };
  65004. /**
  65005. * @private
  65006. */
  65007. BaseAxisPointer.prototype.clear = function (api) {
  65008. this._lastValue = null;
  65009. this._lastStatus = null;
  65010. var zr = api.getZr();
  65011. var group = this._group;
  65012. var handle = this._handle;
  65013. if (zr && group) {
  65014. this._lastGraphicKey = null;
  65015. group && zr.remove(group);
  65016. handle && zr.remove(handle);
  65017. this._group = null;
  65018. this._handle = null;
  65019. this._payloadInfo = null;
  65020. }
  65021. clear(this, '_doDispatchAxisPointer');
  65022. };
  65023. /**
  65024. * @protected
  65025. */
  65026. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  65027. };
  65028. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  65029. xDimIndex = xDimIndex || 0;
  65030. return {
  65031. x: xy[xDimIndex],
  65032. y: xy[1 - xDimIndex],
  65033. width: wh[xDimIndex],
  65034. height: wh[1 - xDimIndex]
  65035. };
  65036. };
  65037. return BaseAxisPointer;
  65038. }();
  65039. function updateProps$1(animationModel, moveAnimation, el, props) {
  65040. // Animation optimize.
  65041. if (!propsEqual(inner$a(el).lastProp, props)) {
  65042. inner$a(el).lastProp = props;
  65043. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  65044. }
  65045. }
  65046. function propsEqual(lastProps, newProps) {
  65047. if (isObject(lastProps) && isObject(newProps)) {
  65048. var equals_1 = true;
  65049. each(newProps, function (item, key) {
  65050. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  65051. });
  65052. return !!equals_1;
  65053. } else {
  65054. return lastProps === newProps;
  65055. }
  65056. }
  65057. function updateLabelShowHide(labelEl, axisPointerModel) {
  65058. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  65059. }
  65060. function getHandleTransProps(trans) {
  65061. return {
  65062. x: trans.x || 0,
  65063. y: trans.y || 0,
  65064. rotation: trans.rotation || 0
  65065. };
  65066. }
  65067. function updateMandatoryProps(group, axisPointerModel, silent) {
  65068. var z = axisPointerModel.get('z');
  65069. var zlevel = axisPointerModel.get('zlevel');
  65070. group && group.traverse(function (el) {
  65071. if (el.type !== 'group') {
  65072. z != null && (el.z = z);
  65073. zlevel != null && (el.zlevel = zlevel);
  65074. el.silent = silent;
  65075. }
  65076. });
  65077. }
  65078. function buildElStyle(axisPointerModel) {
  65079. var axisPointerType = axisPointerModel.get('type');
  65080. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  65081. var style;
  65082. if (axisPointerType === 'line') {
  65083. style = styleModel.getLineStyle();
  65084. style.fill = null;
  65085. } else if (axisPointerType === 'shadow') {
  65086. style = styleModel.getAreaStyle();
  65087. style.stroke = null;
  65088. }
  65089. return style;
  65090. }
  65091. /**
  65092. * @param {Function} labelPos {align, verticalAlign, position}
  65093. */
  65094. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  65095. var value = axisPointerModel.get('value');
  65096. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  65097. precision: axisPointerModel.get(['label', 'precision']),
  65098. formatter: axisPointerModel.get(['label', 'formatter'])
  65099. });
  65100. var labelModel = axisPointerModel.getModel('label');
  65101. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  65102. var font = labelModel.getFont();
  65103. var textRect = getBoundingRect(text, font);
  65104. var position = labelPos.position;
  65105. var width = textRect.width + paddings[1] + paddings[3];
  65106. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  65107. var align = labelPos.align;
  65108. align === 'right' && (position[0] -= width);
  65109. align === 'center' && (position[0] -= width / 2);
  65110. var verticalAlign = labelPos.verticalAlign;
  65111. verticalAlign === 'bottom' && (position[1] -= height);
  65112. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  65113. confineInContainer(position, width, height, api);
  65114. var bgColor = labelModel.get('backgroundColor');
  65115. if (!bgColor || bgColor === 'auto') {
  65116. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  65117. }
  65118. elOption.label = {
  65119. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  65120. x: position[0],
  65121. y: position[1],
  65122. style: createTextStyle(labelModel, {
  65123. text: text,
  65124. font: font,
  65125. fill: labelModel.getTextColor(),
  65126. padding: paddings,
  65127. backgroundColor: bgColor
  65128. }),
  65129. // Label should be over axisPointer.
  65130. z2: 10
  65131. };
  65132. } // Do not overflow ec container
  65133. function confineInContainer(position, width, height, api) {
  65134. var viewWidth = api.getWidth();
  65135. var viewHeight = api.getHeight();
  65136. position[0] = Math.min(position[0] + width, viewWidth) - width;
  65137. position[1] = Math.min(position[1] + height, viewHeight) - height;
  65138. position[0] = Math.max(position[0], 0);
  65139. position[1] = Math.max(position[1], 0);
  65140. }
  65141. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  65142. value = axis.scale.parse(value);
  65143. var text = axis.scale.getLabel({
  65144. value: value
  65145. }, {
  65146. // If `precision` is set, width can be fixed (like '12.00500'), which
  65147. // helps to debounce when when moving label.
  65148. precision: opt.precision
  65149. });
  65150. var formatter = opt.formatter;
  65151. if (formatter) {
  65152. var params_1 = {
  65153. value: getAxisRawValue(axis, {
  65154. value: value
  65155. }),
  65156. axisDimension: axis.dim,
  65157. axisIndex: axis.index,
  65158. seriesData: []
  65159. };
  65160. each(seriesDataIndices, function (idxItem) {
  65161. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  65162. var dataIndex = idxItem.dataIndexInside;
  65163. var dataParams = series && series.getDataParams(dataIndex);
  65164. dataParams && params_1.seriesData.push(dataParams);
  65165. });
  65166. if (isString(formatter)) {
  65167. text = formatter.replace('{value}', text);
  65168. } else if (isFunction(formatter)) {
  65169. text = formatter(params_1);
  65170. }
  65171. }
  65172. return text;
  65173. }
  65174. function getTransformedPosition(axis, value, layoutInfo) {
  65175. var transform = create$1();
  65176. rotate(transform, transform, layoutInfo.rotation);
  65177. translate(transform, transform, layoutInfo.position);
  65178. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  65179. }
  65180. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  65181. // @ts-ignore
  65182. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  65183. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  65184. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  65185. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  65186. align: textLayout.textAlign,
  65187. verticalAlign: textLayout.textVerticalAlign
  65188. });
  65189. }
  65190. function makeLineShape(p1, p2, xDimIndex) {
  65191. xDimIndex = xDimIndex || 0;
  65192. return {
  65193. x1: p1[xDimIndex],
  65194. y1: p1[1 - xDimIndex],
  65195. x2: p2[xDimIndex],
  65196. y2: p2[1 - xDimIndex]
  65197. };
  65198. }
  65199. function makeRectShape(xy, wh, xDimIndex) {
  65200. xDimIndex = xDimIndex || 0;
  65201. return {
  65202. x: xy[xDimIndex],
  65203. y: xy[1 - xDimIndex],
  65204. width: wh[xDimIndex],
  65205. height: wh[1 - xDimIndex]
  65206. };
  65207. }
  65208. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  65209. return {
  65210. cx: cx,
  65211. cy: cy,
  65212. r0: r0,
  65213. r: r,
  65214. startAngle: startAngle,
  65215. endAngle: endAngle,
  65216. clockwise: true
  65217. };
  65218. }
  65219. var CartesianAxisPointer =
  65220. /** @class */
  65221. function (_super) {
  65222. __extends(CartesianAxisPointer, _super);
  65223. function CartesianAxisPointer() {
  65224. return _super !== null && _super.apply(this, arguments) || this;
  65225. }
  65226. /**
  65227. * @override
  65228. */
  65229. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65230. var axis = axisModel.axis;
  65231. var grid = axis.grid;
  65232. var axisPointerType = axisPointerModel.get('type');
  65233. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65234. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  65235. if (axisPointerType && axisPointerType !== 'none') {
  65236. var elStyle = buildElStyle(axisPointerModel);
  65237. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  65238. pointerOption.style = elStyle;
  65239. elOption.graphicKey = pointerOption.type;
  65240. elOption.pointer = pointerOption;
  65241. }
  65242. var layoutInfo = layout$1(grid.model, axisModel);
  65243. buildCartesianSingleLabelElOption( // @ts-ignore
  65244. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  65245. };
  65246. /**
  65247. * @override
  65248. */
  65249. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  65250. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  65251. labelInside: false
  65252. }); // @ts-ignore
  65253. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  65254. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  65255. return {
  65256. x: pos[0],
  65257. y: pos[1],
  65258. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  65259. };
  65260. };
  65261. /**
  65262. * @override
  65263. */
  65264. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  65265. var axis = axisModel.axis;
  65266. var grid = axis.grid;
  65267. var axisExtent = axis.getGlobalExtent(true);
  65268. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  65269. var dimIndex = axis.dim === 'x' ? 0 : 1;
  65270. var currPosition = [transform.x, transform.y];
  65271. currPosition[dimIndex] += delta[dimIndex];
  65272. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  65273. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  65274. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  65275. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  65276. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  65277. var tooltipOptions = [{
  65278. verticalAlign: 'middle'
  65279. }, {
  65280. align: 'center'
  65281. }];
  65282. return {
  65283. x: currPosition[0],
  65284. y: currPosition[1],
  65285. rotation: transform.rotation,
  65286. cursorPoint: cursorPoint,
  65287. tooltipOption: tooltipOptions[dimIndex]
  65288. };
  65289. };
  65290. return CartesianAxisPointer;
  65291. }(BaseAxisPointer);
  65292. function getCartesian(grid, axis) {
  65293. var opt = {};
  65294. opt[axis.dim + 'AxisIndex'] = axis.index;
  65295. return grid.getCartesian(opt);
  65296. }
  65297. var pointerShapeBuilder = {
  65298. line: function (axis, pixelValue, otherExtent) {
  65299. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  65300. return {
  65301. type: 'Line',
  65302. subPixelOptimize: true,
  65303. shape: targetShape
  65304. };
  65305. },
  65306. shadow: function (axis, pixelValue, otherExtent) {
  65307. var bandWidth = Math.max(1, axis.getBandWidth());
  65308. var span = otherExtent[1] - otherExtent[0];
  65309. return {
  65310. type: 'Rect',
  65311. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  65312. };
  65313. }
  65314. };
  65315. function getAxisDimIndex(axis) {
  65316. return axis.dim === 'x' ? 0 : 1;
  65317. }
  65318. var AxisPointerModel =
  65319. /** @class */
  65320. function (_super) {
  65321. __extends(AxisPointerModel, _super);
  65322. function AxisPointerModel() {
  65323. var _this = _super !== null && _super.apply(this, arguments) || this;
  65324. _this.type = AxisPointerModel.type;
  65325. return _this;
  65326. }
  65327. AxisPointerModel.type = 'axisPointer';
  65328. AxisPointerModel.defaultOption = {
  65329. // 'auto' means that show when triggered by tooltip or handle.
  65330. show: 'auto',
  65331. // zlevel: 0,
  65332. z: 50,
  65333. type: 'line',
  65334. // axispointer triggered by tootip determine snap automatically,
  65335. // see `modelHelper`.
  65336. snap: false,
  65337. triggerTooltip: true,
  65338. triggerEmphasis: true,
  65339. value: null,
  65340. status: null,
  65341. link: [],
  65342. // Do not set 'auto' here, otherwise global animation: false
  65343. // will not effect at this axispointer.
  65344. animation: null,
  65345. animationDurationUpdate: 200,
  65346. lineStyle: {
  65347. color: '#B9BEC9',
  65348. width: 1,
  65349. type: 'dashed'
  65350. },
  65351. shadowStyle: {
  65352. color: 'rgba(210,219,238,0.2)'
  65353. },
  65354. label: {
  65355. show: true,
  65356. formatter: null,
  65357. precision: 'auto',
  65358. margin: 3,
  65359. color: '#fff',
  65360. padding: [5, 7, 5, 7],
  65361. backgroundColor: 'auto',
  65362. borderColor: null,
  65363. borderWidth: 0,
  65364. borderRadius: 3
  65365. },
  65366. handle: {
  65367. show: false,
  65368. // eslint-disable-next-line
  65369. 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',
  65370. size: 45,
  65371. // handle margin is from symbol center to axis, which is stable when circular move.
  65372. margin: 50,
  65373. // color: '#1b8bbd'
  65374. // color: '#2f4554'
  65375. color: '#333',
  65376. shadowBlur: 3,
  65377. shadowColor: '#aaa',
  65378. shadowOffsetX: 0,
  65379. shadowOffsetY: 2,
  65380. // For mobile performance
  65381. throttle: 40
  65382. }
  65383. };
  65384. return AxisPointerModel;
  65385. }(ComponentModel);
  65386. var inner$b = makeInner();
  65387. var each$7 = each;
  65388. /**
  65389. * @param {string} key
  65390. * @param {module:echarts/ExtensionAPI} api
  65391. * @param {Function} handler
  65392. * param: {string} currTrigger
  65393. * param: {Array.<number>} point
  65394. */
  65395. function register(key, api, handler) {
  65396. if (env.node) {
  65397. return;
  65398. }
  65399. var zr = api.getZr();
  65400. inner$b(zr).records || (inner$b(zr).records = {});
  65401. initGlobalListeners(zr, api);
  65402. var record = inner$b(zr).records[key] || (inner$b(zr).records[key] = {});
  65403. record.handler = handler;
  65404. }
  65405. function initGlobalListeners(zr, api) {
  65406. if (inner$b(zr).initialized) {
  65407. return;
  65408. }
  65409. inner$b(zr).initialized = true;
  65410. useHandler('click', curry(doEnter, 'click'));
  65411. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  65412. useHandler('globalout', onLeave);
  65413. function useHandler(eventType, cb) {
  65414. zr.on(eventType, function (e) {
  65415. var dis = makeDispatchAction(api);
  65416. each$7(inner$b(zr).records, function (record) {
  65417. record && cb(record, e, dis.dispatchAction);
  65418. });
  65419. dispatchTooltipFinally(dis.pendings, api);
  65420. });
  65421. }
  65422. }
  65423. function dispatchTooltipFinally(pendings, api) {
  65424. var showLen = pendings.showTip.length;
  65425. var hideLen = pendings.hideTip.length;
  65426. var actuallyPayload;
  65427. if (showLen) {
  65428. actuallyPayload = pendings.showTip[showLen - 1];
  65429. } else if (hideLen) {
  65430. actuallyPayload = pendings.hideTip[hideLen - 1];
  65431. }
  65432. if (actuallyPayload) {
  65433. actuallyPayload.dispatchAction = null;
  65434. api.dispatchAction(actuallyPayload);
  65435. }
  65436. }
  65437. function onLeave(record, e, dispatchAction) {
  65438. record.handler('leave', null, dispatchAction);
  65439. }
  65440. function doEnter(currTrigger, record, e, dispatchAction) {
  65441. record.handler(currTrigger, e, dispatchAction);
  65442. }
  65443. function makeDispatchAction(api) {
  65444. var pendings = {
  65445. showTip: [],
  65446. hideTip: []
  65447. }; // FIXME
  65448. // better approach?
  65449. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  65450. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  65451. // So we have to add "final stage" to merge those dispatched actions.
  65452. var dispatchAction = function (payload) {
  65453. var pendingList = pendings[payload.type];
  65454. if (pendingList) {
  65455. pendingList.push(payload);
  65456. } else {
  65457. payload.dispatchAction = dispatchAction;
  65458. api.dispatchAction(payload);
  65459. }
  65460. };
  65461. return {
  65462. dispatchAction: dispatchAction,
  65463. pendings: pendings
  65464. };
  65465. }
  65466. function unregister(key, api) {
  65467. if (env.node) {
  65468. return;
  65469. }
  65470. var zr = api.getZr();
  65471. var record = (inner$b(zr).records || {})[key];
  65472. if (record) {
  65473. inner$b(zr).records[key] = null;
  65474. }
  65475. }
  65476. var AxisPointerView =
  65477. /** @class */
  65478. function (_super) {
  65479. __extends(AxisPointerView, _super);
  65480. function AxisPointerView() {
  65481. var _this = _super !== null && _super.apply(this, arguments) || this;
  65482. _this.type = AxisPointerView.type;
  65483. return _this;
  65484. }
  65485. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  65486. var globalTooltipModel = ecModel.getComponent('tooltip');
  65487. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  65488. // AxisPointerView to be independent to Tooltip.
  65489. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  65490. // If 'none', it is not controlled by mouse totally.
  65491. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  65492. dispatchAction({
  65493. type: 'updateAxisPointer',
  65494. currTrigger: currTrigger,
  65495. x: e && e.offsetX,
  65496. y: e && e.offsetY
  65497. });
  65498. }
  65499. });
  65500. };
  65501. AxisPointerView.prototype.remove = function (ecModel, api) {
  65502. unregister('axisPointer', api);
  65503. };
  65504. AxisPointerView.prototype.dispose = function (ecModel, api) {
  65505. unregister('axisPointer', api);
  65506. };
  65507. AxisPointerView.type = 'axisPointer';
  65508. return AxisPointerView;
  65509. }(ComponentView);
  65510. /**
  65511. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  65512. * @param ecModel
  65513. * @return {point: [x, y], el: ...} point Will not be null.
  65514. */
  65515. function findPointFromSeries(finder, ecModel) {
  65516. var point = [];
  65517. var seriesIndex = finder.seriesIndex;
  65518. var seriesModel;
  65519. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  65520. return {
  65521. point: []
  65522. };
  65523. }
  65524. var data = seriesModel.getData();
  65525. var dataIndex = queryDataIndex(data, finder);
  65526. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  65527. return {
  65528. point: []
  65529. };
  65530. }
  65531. var el = data.getItemGraphicEl(dataIndex);
  65532. var coordSys = seriesModel.coordinateSystem;
  65533. if (seriesModel.getTooltipPosition) {
  65534. point = seriesModel.getTooltipPosition(dataIndex) || [];
  65535. } else if (coordSys && coordSys.dataToPoint) {
  65536. if (finder.isStacked) {
  65537. var baseAxis = coordSys.getBaseAxis();
  65538. var valueAxis = coordSys.getOtherAxis(baseAxis);
  65539. var valueAxisDim = valueAxis.dim;
  65540. var baseAxisDim = baseAxis.dim;
  65541. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  65542. var baseDim = data.mapDimension(baseAxisDim);
  65543. var stackedData = [];
  65544. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  65545. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  65546. point = coordSys.dataToPoint(stackedData) || [];
  65547. } else {
  65548. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  65549. return data.mapDimension(dim);
  65550. }), dataIndex)) || [];
  65551. }
  65552. } else if (el) {
  65553. // Use graphic bounding rect
  65554. var rect = el.getBoundingRect().clone();
  65555. rect.applyTransform(el.transform);
  65556. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  65557. }
  65558. return {
  65559. point: point,
  65560. el: el
  65561. };
  65562. }
  65563. var inner$c = makeInner();
  65564. /**
  65565. * Basic logic: check all axis, if they do not demand show/highlight,
  65566. * then hide/downplay them.
  65567. *
  65568. * @return content of event obj for echarts.connect.
  65569. */
  65570. function axisTrigger(payload, ecModel, api) {
  65571. var currTrigger = payload.currTrigger;
  65572. var point = [payload.x, payload.y];
  65573. var finder = payload;
  65574. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  65575. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  65576. // See #6121. But we are not able to reproduce it yet.
  65577. if (!coordSysAxesInfo) {
  65578. return;
  65579. }
  65580. if (illegalPoint(point)) {
  65581. // Used in the default behavior of `connection`: use the sample seriesIndex
  65582. // and dataIndex. And also used in the tooltipView trigger.
  65583. point = findPointFromSeries({
  65584. seriesIndex: finder.seriesIndex,
  65585. // Do not use dataIndexInside from other ec instance.
  65586. // FIXME: auto detect it?
  65587. dataIndex: finder.dataIndex
  65588. }, ecModel).point;
  65589. }
  65590. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  65591. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  65592. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  65593. // and dataIndex.
  65594. var inputAxesInfo = finder.axesInfo;
  65595. var axesInfo = coordSysAxesInfo.axesInfo;
  65596. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  65597. var outputPayload = {};
  65598. var showValueMap = {};
  65599. var dataByCoordSys = {
  65600. list: [],
  65601. map: {}
  65602. };
  65603. var updaters = {
  65604. showPointer: curry(showPointer, showValueMap),
  65605. showTooltip: curry(showTooltip, dataByCoordSys)
  65606. }; // Process for triggered axes.
  65607. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  65608. // If a point given, it must be contained by the coordinate system.
  65609. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  65610. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  65611. var axis = axisInfo.axis;
  65612. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  65613. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  65614. var val = inputAxisInfo && inputAxisInfo.value;
  65615. if (val == null && !isIllegalPoint) {
  65616. val = axis.pointToData(point);
  65617. }
  65618. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  65619. }
  65620. });
  65621. }); // Process for linked axes.
  65622. var linkTriggers = {};
  65623. each(axesInfo, function (tarAxisInfo, tarKey) {
  65624. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  65625. if (linkGroup && !showValueMap[tarKey]) {
  65626. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  65627. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  65628. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  65629. var val = srcValItem.value;
  65630. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  65631. linkTriggers[tarAxisInfo.key] = val;
  65632. }
  65633. });
  65634. }
  65635. });
  65636. each(linkTriggers, function (val, tarKey) {
  65637. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  65638. });
  65639. updateModelActually(showValueMap, axesInfo, outputPayload);
  65640. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  65641. dispatchHighDownActually(axesInfo, dispatchAction, api);
  65642. return outputPayload;
  65643. }
  65644. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  65645. var axis = axisInfo.axis;
  65646. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  65647. return;
  65648. }
  65649. if (!axisInfo.involveSeries) {
  65650. updaters.showPointer(axisInfo, newValue);
  65651. return;
  65652. } // Heavy calculation. So put it after axis.containData checking.
  65653. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  65654. var payloadBatch = payloadInfo.payloadBatch;
  65655. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  65656. // By default use the first involved series data as a sample to connect.
  65657. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  65658. extend(outputFinder, payloadBatch[0]);
  65659. } // If no linkSource input, this process is for collecting link
  65660. // target, where snap should not be accepted.
  65661. if (!noSnap && axisInfo.snap) {
  65662. if (axis.containData(snapToValue) && snapToValue != null) {
  65663. newValue = snapToValue;
  65664. }
  65665. }
  65666. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  65667. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  65668. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  65669. }
  65670. function buildPayloadsBySeries(value, axisInfo) {
  65671. var axis = axisInfo.axis;
  65672. var dim = axis.dim;
  65673. var snapToValue = value;
  65674. var payloadBatch = [];
  65675. var minDist = Number.MAX_VALUE;
  65676. var minDiff = -1;
  65677. each(axisInfo.seriesModels, function (series, idx) {
  65678. var dataDim = series.getData().mapDimensionsAll(dim);
  65679. var seriesNestestValue;
  65680. var dataIndices;
  65681. if (series.getAxisTooltipData) {
  65682. var result = series.getAxisTooltipData(dataDim, value, axis);
  65683. dataIndices = result.dataIndices;
  65684. seriesNestestValue = result.nestestValue;
  65685. } else {
  65686. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  65687. // when data length is not same.
  65688. // false,
  65689. axis.type === 'category' ? 0.5 : null);
  65690. if (!dataIndices.length) {
  65691. return;
  65692. }
  65693. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  65694. }
  65695. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  65696. return;
  65697. }
  65698. var diff = value - seriesNestestValue;
  65699. var dist = Math.abs(diff); // Consider category case
  65700. if (dist <= minDist) {
  65701. if (dist < minDist || diff >= 0 && minDiff < 0) {
  65702. minDist = dist;
  65703. minDiff = diff;
  65704. snapToValue = seriesNestestValue;
  65705. payloadBatch.length = 0;
  65706. }
  65707. each(dataIndices, function (dataIndex) {
  65708. payloadBatch.push({
  65709. seriesIndex: series.seriesIndex,
  65710. dataIndexInside: dataIndex,
  65711. dataIndex: series.getData().getRawIndex(dataIndex)
  65712. });
  65713. });
  65714. }
  65715. });
  65716. return {
  65717. payloadBatch: payloadBatch,
  65718. snapToValue: snapToValue
  65719. };
  65720. }
  65721. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  65722. showValueMap[axisInfo.key] = {
  65723. value: value,
  65724. payloadBatch: payloadBatch
  65725. };
  65726. }
  65727. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  65728. var payloadBatch = payloadInfo.payloadBatch;
  65729. var axis = axisInfo.axis;
  65730. var axisModel = axis.model;
  65731. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  65732. // whose length will be used to judge whether dispatch action.
  65733. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  65734. return;
  65735. }
  65736. var coordSysModel = axisInfo.coordSys.model;
  65737. var coordSysKey = makeKey(coordSysModel);
  65738. var coordSysItem = dataByCoordSys.map[coordSysKey];
  65739. if (!coordSysItem) {
  65740. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  65741. coordSysId: coordSysModel.id,
  65742. coordSysIndex: coordSysModel.componentIndex,
  65743. coordSysType: coordSysModel.type,
  65744. coordSysMainType: coordSysModel.mainType,
  65745. dataByAxis: []
  65746. };
  65747. dataByCoordSys.list.push(coordSysItem);
  65748. }
  65749. coordSysItem.dataByAxis.push({
  65750. axisDim: axis.dim,
  65751. axisIndex: axisModel.componentIndex,
  65752. axisType: axisModel.type,
  65753. axisId: axisModel.id,
  65754. value: value,
  65755. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  65756. // depends that all models have been updated. So it should not be performed
  65757. // here. Considering axisPointerModel used here is volatile, which is hard
  65758. // to be retrieve in TooltipView, we prepare parameters here.
  65759. valueLabelOpt: {
  65760. precision: axisPointerModel.get(['label', 'precision']),
  65761. formatter: axisPointerModel.get(['label', 'formatter'])
  65762. },
  65763. seriesDataIndices: payloadBatch.slice()
  65764. });
  65765. }
  65766. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  65767. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  65768. each(axesInfo, function (axisInfo, key) {
  65769. var option = axisInfo.axisPointerModel.option;
  65770. var valItem = showValueMap[key];
  65771. if (valItem) {
  65772. !axisInfo.useHandle && (option.status = 'show');
  65773. option.value = valItem.value; // For label formatter param and highlight.
  65774. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  65775. } // When always show (e.g., handle used), remain
  65776. // original value and status.
  65777. else {
  65778. // If hide, value still need to be set, consider
  65779. // click legend to toggle axis blank.
  65780. !axisInfo.useHandle && (option.status = 'hide');
  65781. } // If status is 'hide', should be no info in payload.
  65782. option.status === 'show' && outputAxesInfo.push({
  65783. axisDim: axisInfo.axis.dim,
  65784. axisIndex: axisInfo.axis.model.componentIndex,
  65785. value: option.value
  65786. });
  65787. });
  65788. }
  65789. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  65790. // Basic logic: If no showTip required, hideTip will be dispatched.
  65791. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  65792. dispatchAction({
  65793. type: 'hideTip'
  65794. });
  65795. return;
  65796. } // In most case only one axis (or event one series is used). It is
  65797. // convenient to fetch payload.seriesIndex and payload.dataIndex
  65798. // directly. So put the first seriesIndex and dataIndex of the first
  65799. // axis on the payload.
  65800. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  65801. dispatchAction({
  65802. type: 'showTip',
  65803. escapeConnect: true,
  65804. x: point[0],
  65805. y: point[1],
  65806. tooltipOption: payload.tooltipOption,
  65807. position: payload.position,
  65808. dataIndexInside: sampleItem.dataIndexInside,
  65809. dataIndex: sampleItem.dataIndex,
  65810. seriesIndex: sampleItem.seriesIndex,
  65811. dataByCoordSys: dataByCoordSys.list
  65812. });
  65813. }
  65814. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  65815. // FIXME
  65816. // highlight status modification should be a stage of main process?
  65817. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  65818. var zr = api.getZr();
  65819. var highDownKey = 'axisPointerLastHighlights';
  65820. var lastHighlights = inner$c(zr)[highDownKey] || {};
  65821. var newHighlights = inner$c(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  65822. // Build hash map and remove duplicate incidentally.
  65823. each(axesInfo, function (axisInfo, key) {
  65824. var option = axisInfo.axisPointerModel.option;
  65825. option.status === 'show' && axisInfo.triggerEmphasis && each(option.seriesDataIndices, function (batchItem) {
  65826. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  65827. newHighlights[key] = batchItem;
  65828. });
  65829. }); // Diff.
  65830. var toHighlight = [];
  65831. var toDownplay = [];
  65832. each(lastHighlights, function (batchItem, key) {
  65833. !newHighlights[key] && toDownplay.push(batchItem);
  65834. });
  65835. each(newHighlights, function (batchItem, key) {
  65836. !lastHighlights[key] && toHighlight.push(batchItem);
  65837. });
  65838. toDownplay.length && api.dispatchAction({
  65839. type: 'downplay',
  65840. escapeConnect: true,
  65841. // Not blur others when highlight in axisPointer.
  65842. notBlur: true,
  65843. batch: toDownplay
  65844. });
  65845. toHighlight.length && api.dispatchAction({
  65846. type: 'highlight',
  65847. escapeConnect: true,
  65848. // Not blur others when highlight in axisPointer.
  65849. notBlur: true,
  65850. batch: toHighlight
  65851. });
  65852. }
  65853. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  65854. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  65855. var inputAxisInfo = inputAxesInfo[i];
  65856. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  65857. return inputAxisInfo;
  65858. }
  65859. }
  65860. }
  65861. function makeMapperParam(axisInfo) {
  65862. var axisModel = axisInfo.axis.model;
  65863. var item = {};
  65864. var dim = item.axisDim = axisInfo.axis.dim;
  65865. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  65866. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  65867. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  65868. return item;
  65869. }
  65870. function illegalPoint(point) {
  65871. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  65872. }
  65873. function install$s(registers) {
  65874. // CartesianAxisPointer is not supposed to be required here. But consider
  65875. // echarts.simple.js and online build tooltip, which only require gridSimple,
  65876. // CartesianAxisPointer should be able to required somewhere.
  65877. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  65878. registers.registerComponentModel(AxisPointerModel);
  65879. registers.registerComponentView(AxisPointerView);
  65880. registers.registerPreprocessor(function (option) {
  65881. // Always has a global axisPointerModel for default setting.
  65882. if (option) {
  65883. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  65884. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  65885. // is not set, remain null/undefined, otherwise it will
  65886. // override existent link setting.
  65887. if (link && !isArray(link)) {
  65888. option.axisPointer.link = [link];
  65889. }
  65890. }
  65891. }); // This process should proformed after coordinate systems created
  65892. // and series data processed. So put it on statistic processing stage.
  65893. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  65894. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  65895. // allAxesInfo should be updated when setOption performed.
  65896. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  65897. }); // Broadcast to all views.
  65898. registers.registerAction({
  65899. type: 'updateAxisPointer',
  65900. event: 'updateAxisPointer',
  65901. update: ':updateAxisPointer'
  65902. }, axisTrigger);
  65903. }
  65904. function install$t(registers) {
  65905. use(install$5);
  65906. use(install$s);
  65907. }
  65908. var PolarAxisPointer =
  65909. /** @class */
  65910. function (_super) {
  65911. __extends(PolarAxisPointer, _super);
  65912. function PolarAxisPointer() {
  65913. return _super !== null && _super.apply(this, arguments) || this;
  65914. }
  65915. /**
  65916. * @override
  65917. */
  65918. PolarAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  65919. var axis = axisModel.axis;
  65920. if (axis.dim === 'angle') {
  65921. this.animationThreshold = Math.PI / 18;
  65922. }
  65923. var polar = axis.polar;
  65924. var otherAxis = polar.getOtherAxis(axis);
  65925. var otherExtent = otherAxis.getExtent();
  65926. var coordValue = axis.dataToCoord(value);
  65927. var axisPointerType = axisPointerModel.get('type');
  65928. if (axisPointerType && axisPointerType !== 'none') {
  65929. var elStyle = buildElStyle(axisPointerModel);
  65930. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent);
  65931. pointerOption.style = elStyle;
  65932. elOption.graphicKey = pointerOption.type;
  65933. elOption.pointer = pointerOption;
  65934. }
  65935. var labelMargin = axisPointerModel.get(['label', 'margin']);
  65936. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  65937. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  65938. };
  65939. return PolarAxisPointer;
  65940. }(BaseAxisPointer);
  65941. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  65942. var axis = axisModel.axis;
  65943. var coord = axis.dataToCoord(value);
  65944. var axisAngle = polar.getAngleAxis().getExtent()[0];
  65945. axisAngle = axisAngle / 180 * Math.PI;
  65946. var radiusExtent = polar.getRadiusAxis().getExtent();
  65947. var position;
  65948. var align;
  65949. var verticalAlign;
  65950. if (axis.dim === 'radius') {
  65951. var transform = create$1();
  65952. rotate(transform, transform, axisAngle);
  65953. translate(transform, transform, [polar.cx, polar.cy]);
  65954. position = applyTransform$1([coord, -labelMargin], transform);
  65955. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0; // @ts-ignore
  65956. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  65957. align = labelLayout.textAlign;
  65958. verticalAlign = labelLayout.textVerticalAlign;
  65959. } else {
  65960. // angle axis
  65961. var r = radiusExtent[1];
  65962. position = polar.coordToPoint([r + labelMargin, coord]);
  65963. var cx = polar.cx;
  65964. var cy = polar.cy;
  65965. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  65966. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  65967. }
  65968. return {
  65969. position: position,
  65970. align: align,
  65971. verticalAlign: verticalAlign
  65972. };
  65973. }
  65974. var pointerShapeBuilder$1 = {
  65975. line: function (axis, polar, coordValue, otherExtent) {
  65976. return axis.dim === 'angle' ? {
  65977. type: 'Line',
  65978. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  65979. } : {
  65980. type: 'Circle',
  65981. shape: {
  65982. cx: polar.cx,
  65983. cy: polar.cy,
  65984. r: coordValue
  65985. }
  65986. };
  65987. },
  65988. shadow: function (axis, polar, coordValue, otherExtent) {
  65989. var bandWidth = Math.max(1, axis.getBandWidth());
  65990. var radian = Math.PI / 180;
  65991. return axis.dim === 'angle' ? {
  65992. type: 'Sector',
  65993. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  65994. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  65995. } : {
  65996. type: 'Sector',
  65997. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  65998. };
  65999. }
  66000. };
  66001. var PolarModel =
  66002. /** @class */
  66003. function (_super) {
  66004. __extends(PolarModel, _super);
  66005. function PolarModel() {
  66006. var _this = _super !== null && _super.apply(this, arguments) || this;
  66007. _this.type = PolarModel.type;
  66008. return _this;
  66009. }
  66010. PolarModel.prototype.findAxisModel = function (axisType) {
  66011. var foundAxisModel;
  66012. var ecModel = this.ecModel;
  66013. ecModel.eachComponent(axisType, function (axisModel) {
  66014. if (axisModel.getCoordSysModel() === this) {
  66015. foundAxisModel = axisModel;
  66016. }
  66017. }, this);
  66018. return foundAxisModel;
  66019. };
  66020. PolarModel.type = 'polar';
  66021. PolarModel.dependencies = ['radiusAxis', 'angleAxis'];
  66022. PolarModel.defaultOption = {
  66023. // zlevel: 0,
  66024. z: 0,
  66025. center: ['50%', '50%'],
  66026. radius: '80%'
  66027. };
  66028. return PolarModel;
  66029. }(ComponentModel);
  66030. var PolarAxisModel =
  66031. /** @class */
  66032. function (_super) {
  66033. __extends(PolarAxisModel, _super);
  66034. function PolarAxisModel() {
  66035. return _super !== null && _super.apply(this, arguments) || this;
  66036. }
  66037. PolarAxisModel.prototype.getCoordSysModel = function () {
  66038. return this.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  66039. };
  66040. PolarAxisModel.type = 'polarAxis';
  66041. return PolarAxisModel;
  66042. }(ComponentModel);
  66043. mixin(PolarAxisModel, AxisModelCommonMixin);
  66044. var AngleAxisModel =
  66045. /** @class */
  66046. function (_super) {
  66047. __extends(AngleAxisModel, _super);
  66048. function AngleAxisModel() {
  66049. var _this = _super !== null && _super.apply(this, arguments) || this;
  66050. _this.type = AngleAxisModel.type;
  66051. return _this;
  66052. }
  66053. AngleAxisModel.type = 'angleAxis';
  66054. return AngleAxisModel;
  66055. }(PolarAxisModel);
  66056. var RadiusAxisModel =
  66057. /** @class */
  66058. function (_super) {
  66059. __extends(RadiusAxisModel, _super);
  66060. function RadiusAxisModel() {
  66061. var _this = _super !== null && _super.apply(this, arguments) || this;
  66062. _this.type = RadiusAxisModel.type;
  66063. return _this;
  66064. }
  66065. RadiusAxisModel.type = 'radiusAxis';
  66066. return RadiusAxisModel;
  66067. }(PolarAxisModel);
  66068. var RadiusAxis =
  66069. /** @class */
  66070. function (_super) {
  66071. __extends(RadiusAxis, _super);
  66072. function RadiusAxis(scale, radiusExtent) {
  66073. return _super.call(this, 'radius', scale, radiusExtent) || this;
  66074. }
  66075. RadiusAxis.prototype.pointToData = function (point, clamp) {
  66076. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  66077. };
  66078. return RadiusAxis;
  66079. }(Axis);
  66080. RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord;
  66081. RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData;
  66082. var inner$d = makeInner();
  66083. var AngleAxis =
  66084. /** @class */
  66085. function (_super) {
  66086. __extends(AngleAxis, _super);
  66087. function AngleAxis(scale, angleExtent) {
  66088. return _super.call(this, 'angle', scale, angleExtent || [0, 360]) || this;
  66089. }
  66090. AngleAxis.prototype.pointToData = function (point, clamp) {
  66091. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  66092. };
  66093. /**
  66094. * Only be called in category axis.
  66095. * Angle axis uses text height to decide interval
  66096. *
  66097. * @override
  66098. * @return {number} Auto interval for cateogry axis tick and label
  66099. */
  66100. AngleAxis.prototype.calculateCategoryInterval = function () {
  66101. var axis = this;
  66102. var labelModel = axis.getLabelModel();
  66103. var ordinalScale = axis.scale;
  66104. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  66105. // avoid generating a long array by `getTicks`
  66106. // in large category data case.
  66107. var tickCount = ordinalScale.count();
  66108. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  66109. return 0;
  66110. }
  66111. var tickValue = ordinalExtent[0];
  66112. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  66113. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  66114. // and each distance from axis line yet.
  66115. var rect = getBoundingRect(tickValue == null ? '' : tickValue + '', labelModel.getFont(), 'center', 'top');
  66116. var maxH = Math.max(rect.height, 7);
  66117. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  66118. isNaN(dh) && (dh = Infinity);
  66119. var interval = Math.max(0, Math.floor(dh));
  66120. var cache = inner$d(axis.model);
  66121. var lastAutoInterval = cache.lastAutoInterval;
  66122. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  66123. // otherwise the calculated interval might jitter when the zoom
  66124. // window size is close to the interval-changing size.
  66125. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  66126. // point is not the same when zooming in or zooming out.
  66127. && lastAutoInterval > interval) {
  66128. interval = lastAutoInterval;
  66129. } // Only update cache if cache not used, otherwise the
  66130. // changing of interval is too insensitive.
  66131. else {
  66132. cache.lastTickCount = tickCount;
  66133. cache.lastAutoInterval = interval;
  66134. }
  66135. return interval;
  66136. };
  66137. return AngleAxis;
  66138. }(Axis);
  66139. AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord;
  66140. AngleAxis.prototype.angleToData = Axis.prototype.coordToData;
  66141. var polarDimensions = ['radius', 'angle'];
  66142. var Polar =
  66143. /** @class */
  66144. function () {
  66145. function Polar(name) {
  66146. this.dimensions = polarDimensions;
  66147. this.type = 'polar';
  66148. /**
  66149. * x of polar center
  66150. */
  66151. this.cx = 0;
  66152. /**
  66153. * y of polar center
  66154. */
  66155. this.cy = 0;
  66156. this._radiusAxis = new RadiusAxis();
  66157. this._angleAxis = new AngleAxis();
  66158. this.axisPointerEnabled = true;
  66159. this.name = name || '';
  66160. this._radiusAxis.polar = this._angleAxis.polar = this;
  66161. }
  66162. /**
  66163. * If contain coord
  66164. */
  66165. Polar.prototype.containPoint = function (point) {
  66166. var coord = this.pointToCoord(point);
  66167. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  66168. };
  66169. /**
  66170. * If contain data
  66171. */
  66172. Polar.prototype.containData = function (data) {
  66173. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  66174. };
  66175. Polar.prototype.getAxis = function (dim) {
  66176. var key = '_' + dim + 'Axis';
  66177. return this[key];
  66178. };
  66179. Polar.prototype.getAxes = function () {
  66180. return [this._radiusAxis, this._angleAxis];
  66181. };
  66182. /**
  66183. * Get axes by type of scale
  66184. */
  66185. Polar.prototype.getAxesByScale = function (scaleType) {
  66186. var axes = [];
  66187. var angleAxis = this._angleAxis;
  66188. var radiusAxis = this._radiusAxis;
  66189. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  66190. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  66191. return axes;
  66192. };
  66193. Polar.prototype.getAngleAxis = function () {
  66194. return this._angleAxis;
  66195. };
  66196. Polar.prototype.getRadiusAxis = function () {
  66197. return this._radiusAxis;
  66198. };
  66199. Polar.prototype.getOtherAxis = function (axis) {
  66200. var angleAxis = this._angleAxis;
  66201. return axis === angleAxis ? this._radiusAxis : angleAxis;
  66202. };
  66203. /**
  66204. * Base axis will be used on stacking.
  66205. *
  66206. */
  66207. Polar.prototype.getBaseAxis = function () {
  66208. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  66209. };
  66210. Polar.prototype.getTooltipAxes = function (dim) {
  66211. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  66212. return {
  66213. baseAxes: [baseAxis],
  66214. otherAxes: [this.getOtherAxis(baseAxis)]
  66215. };
  66216. };
  66217. /**
  66218. * Convert a single data item to (x, y) point.
  66219. * Parameter data is an array which the first element is radius and the second is angle
  66220. */
  66221. Polar.prototype.dataToPoint = function (data, clamp) {
  66222. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  66223. };
  66224. /**
  66225. * Convert a (x, y) point to data
  66226. */
  66227. Polar.prototype.pointToData = function (point, clamp) {
  66228. var coord = this.pointToCoord(point);
  66229. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  66230. };
  66231. /**
  66232. * Convert a (x, y) point to (radius, angle) coord
  66233. */
  66234. Polar.prototype.pointToCoord = function (point) {
  66235. var dx = point[0] - this.cx;
  66236. var dy = point[1] - this.cy;
  66237. var angleAxis = this.getAngleAxis();
  66238. var extent = angleAxis.getExtent();
  66239. var minAngle = Math.min(extent[0], extent[1]);
  66240. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  66241. // FIXME
  66242. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  66243. var radius = Math.sqrt(dx * dx + dy * dy);
  66244. dx /= radius;
  66245. dy /= radius;
  66246. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  66247. var dir = radian < minAngle ? 1 : -1;
  66248. while (radian < minAngle || radian > maxAngle) {
  66249. radian += dir * 360;
  66250. }
  66251. return [radius, radian];
  66252. };
  66253. /**
  66254. * Convert a (radius, angle) coord to (x, y) point
  66255. */
  66256. Polar.prototype.coordToPoint = function (coord) {
  66257. var radius = coord[0];
  66258. var radian = coord[1] / 180 * Math.PI;
  66259. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  66260. var y = -Math.sin(radian) * radius + this.cy;
  66261. return [x, y];
  66262. };
  66263. /**
  66264. * Get ring area of cartesian.
  66265. * Area will have a contain function to determine if a point is in the coordinate system.
  66266. */
  66267. Polar.prototype.getArea = function () {
  66268. var angleAxis = this.getAngleAxis();
  66269. var radiusAxis = this.getRadiusAxis();
  66270. var radiusExtent = radiusAxis.getExtent().slice();
  66271. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  66272. var angleExtent = angleAxis.getExtent();
  66273. var RADIAN = Math.PI / 180;
  66274. return {
  66275. cx: this.cx,
  66276. cy: this.cy,
  66277. r0: radiusExtent[0],
  66278. r: radiusExtent[1],
  66279. startAngle: -angleExtent[0] * RADIAN,
  66280. endAngle: -angleExtent[1] * RADIAN,
  66281. clockwise: angleAxis.inverse,
  66282. contain: function (x, y) {
  66283. // It's a ring shape.
  66284. // Start angle and end angle don't matter
  66285. var dx = x - this.cx;
  66286. var dy = y - this.cy; // minus a tiny value 1e-4 to avoid being clipped unexpectedly
  66287. var d2 = dx * dx + dy * dy - 1e-4;
  66288. var r = this.r;
  66289. var r0 = this.r0;
  66290. return d2 <= r * r && d2 >= r0 * r0;
  66291. }
  66292. };
  66293. };
  66294. Polar.prototype.convertToPixel = function (ecModel, finder, value) {
  66295. var coordSys = getCoordSys$2(finder);
  66296. return coordSys === this ? this.dataToPoint(value) : null;
  66297. };
  66298. Polar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  66299. var coordSys = getCoordSys$2(finder);
  66300. return coordSys === this ? this.pointToData(pixel) : null;
  66301. };
  66302. return Polar;
  66303. }();
  66304. function getCoordSys$2(finder) {
  66305. var seriesModel = finder.seriesModel;
  66306. var polarModel = finder.polarModel;
  66307. return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  66308. }
  66309. /**
  66310. * Resize method bound to the polar
  66311. */
  66312. function resizePolar(polar, polarModel, api) {
  66313. var center = polarModel.get('center');
  66314. var width = api.getWidth();
  66315. var height = api.getHeight();
  66316. polar.cx = parsePercent$1(center[0], width);
  66317. polar.cy = parsePercent$1(center[1], height);
  66318. var radiusAxis = polar.getRadiusAxis();
  66319. var size = Math.min(width, height) / 2;
  66320. var radius = polarModel.get('radius');
  66321. if (radius == null) {
  66322. radius = [0, '100%'];
  66323. } else if (!isArray(radius)) {
  66324. // r0 = 0
  66325. radius = [0, radius];
  66326. }
  66327. var parsedRadius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  66328. radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]);
  66329. }
  66330. /**
  66331. * Update polar
  66332. */
  66333. function updatePolarScale(ecModel, api) {
  66334. var polar = this;
  66335. var angleAxis = polar.getAngleAxis();
  66336. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  66337. angleAxis.scale.setExtent(Infinity, -Infinity);
  66338. radiusAxis.scale.setExtent(Infinity, -Infinity);
  66339. ecModel.eachSeries(function (seriesModel) {
  66340. if (seriesModel.coordinateSystem === polar) {
  66341. var data_1 = seriesModel.getData();
  66342. each(getDataDimensionsOnAxis(data_1, 'radius'), function (dim) {
  66343. radiusAxis.scale.unionExtentFromData(data_1, dim);
  66344. });
  66345. each(getDataDimensionsOnAxis(data_1, 'angle'), function (dim) {
  66346. angleAxis.scale.unionExtentFromData(data_1, dim);
  66347. });
  66348. }
  66349. });
  66350. niceScaleExtent(angleAxis.scale, angleAxis.model);
  66351. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  66352. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  66353. var extent = angleAxis.getExtent();
  66354. var diff = 360 / angleAxis.scale.count();
  66355. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  66356. angleAxis.setExtent(extent[0], extent[1]);
  66357. }
  66358. }
  66359. function isAngleAxisModel(axisModel) {
  66360. return axisModel.mainType === 'angleAxis';
  66361. }
  66362. /**
  66363. * Set common axis properties
  66364. */
  66365. function setAxis(axis, axisModel) {
  66366. axis.type = axisModel.get('type');
  66367. axis.scale = createScaleByModel(axisModel);
  66368. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  66369. axis.inverse = axisModel.get('inverse');
  66370. if (isAngleAxisModel(axisModel)) {
  66371. axis.inverse = axis.inverse !== axisModel.get('clockwise');
  66372. var startAngle = axisModel.get('startAngle');
  66373. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  66374. } // Inject axis instance
  66375. axisModel.axis = axis;
  66376. axis.model = axisModel;
  66377. }
  66378. var polarCreator = {
  66379. dimensions: polarDimensions,
  66380. create: function (ecModel, api) {
  66381. var polarList = [];
  66382. ecModel.eachComponent('polar', function (polarModel, idx) {
  66383. var polar = new Polar(idx + ''); // Inject resize and update method
  66384. polar.update = updatePolarScale;
  66385. var radiusAxis = polar.getRadiusAxis();
  66386. var angleAxis = polar.getAngleAxis();
  66387. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  66388. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  66389. setAxis(radiusAxis, radiusAxisModel);
  66390. setAxis(angleAxis, angleAxisModel);
  66391. resizePolar(polar, polarModel, api);
  66392. polarList.push(polar);
  66393. polarModel.coordinateSystem = polar;
  66394. polar.model = polarModel;
  66395. }); // Inject coordinateSystem to series
  66396. ecModel.eachSeries(function (seriesModel) {
  66397. if (seriesModel.get('coordinateSystem') === 'polar') {
  66398. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  66399. if ("development" !== 'production') {
  66400. if (!polarModel) {
  66401. throw new Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found');
  66402. }
  66403. }
  66404. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  66405. }
  66406. });
  66407. return polarList;
  66408. }
  66409. };
  66410. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  66411. function getAxisLineShape(polar, rExtent, angle) {
  66412. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  66413. var start = polar.coordToPoint([rExtent[0], angle]);
  66414. var end = polar.coordToPoint([rExtent[1], angle]);
  66415. return {
  66416. x1: start[0],
  66417. y1: start[1],
  66418. x2: end[0],
  66419. y2: end[1]
  66420. };
  66421. }
  66422. function getRadiusIdx(polar) {
  66423. var radiusAxis = polar.getRadiusAxis();
  66424. return radiusAxis.inverse ? 0 : 1;
  66425. } // Remove the last tick which will overlap the first tick
  66426. function fixAngleOverlap(list) {
  66427. var firstItem = list[0];
  66428. var lastItem = list[list.length - 1];
  66429. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  66430. list.pop();
  66431. }
  66432. }
  66433. var AngleAxisView =
  66434. /** @class */
  66435. function (_super) {
  66436. __extends(AngleAxisView, _super);
  66437. function AngleAxisView() {
  66438. var _this = _super !== null && _super.apply(this, arguments) || this;
  66439. _this.type = AngleAxisView.type;
  66440. _this.axisPointerClass = 'PolarAxisPointer';
  66441. return _this;
  66442. }
  66443. AngleAxisView.prototype.render = function (angleAxisModel, ecModel) {
  66444. this.group.removeAll();
  66445. if (!angleAxisModel.get('show')) {
  66446. return;
  66447. }
  66448. var angleAxis = angleAxisModel.axis;
  66449. var polar = angleAxis.polar;
  66450. var radiusExtent = polar.getRadiusAxis().getExtent();
  66451. var ticksAngles = angleAxis.getTicksCoords();
  66452. var minorTickAngles = angleAxis.getMinorTicksCoords();
  66453. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  66454. labelItem = clone(labelItem);
  66455. var scale = angleAxis.scale;
  66456. var tickValue = scale.type === 'ordinal' ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  66457. labelItem.coord = angleAxis.dataToCoord(tickValue);
  66458. return labelItem;
  66459. });
  66460. fixAngleOverlap(labels);
  66461. fixAngleOverlap(ticksAngles);
  66462. each(elementList$1, function (name) {
  66463. if (angleAxisModel.get([name, 'show']) && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  66464. angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  66465. }
  66466. }, this);
  66467. };
  66468. AngleAxisView.type = 'angleAxis';
  66469. return AngleAxisView;
  66470. }(AxisView);
  66471. var angelAxisElementsBuilders = {
  66472. axisLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66473. var lineStyleModel = angleAxisModel.getModel(['axisLine', 'lineStyle']); // extent id of the axis radius (r0 and r)
  66474. var rId = getRadiusIdx(polar);
  66475. var r0Id = rId ? 0 : 1;
  66476. var shape;
  66477. if (radiusExtent[r0Id] === 0) {
  66478. shape = new Circle({
  66479. shape: {
  66480. cx: polar.cx,
  66481. cy: polar.cy,
  66482. r: radiusExtent[rId]
  66483. },
  66484. style: lineStyleModel.getLineStyle(),
  66485. z2: 1,
  66486. silent: true
  66487. });
  66488. } else {
  66489. shape = new Ring({
  66490. shape: {
  66491. cx: polar.cx,
  66492. cy: polar.cy,
  66493. r: radiusExtent[rId],
  66494. r0: radiusExtent[r0Id]
  66495. },
  66496. style: lineStyleModel.getLineStyle(),
  66497. z2: 1,
  66498. silent: true
  66499. });
  66500. }
  66501. shape.style.fill = null;
  66502. group.add(shape);
  66503. },
  66504. axisTick: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66505. var tickModel = angleAxisModel.getModel('axisTick');
  66506. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  66507. var radius = radiusExtent[getRadiusIdx(polar)];
  66508. var lines = map(ticksAngles, function (tickAngleItem) {
  66509. return new Line({
  66510. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  66511. });
  66512. });
  66513. group.add(mergePath$1(lines, {
  66514. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  66515. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66516. })
  66517. }));
  66518. },
  66519. minorTick: function (group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  66520. if (!minorTickAngles.length) {
  66521. return;
  66522. }
  66523. var tickModel = angleAxisModel.getModel('axisTick');
  66524. var minorTickModel = angleAxisModel.getModel('minorTick');
  66525. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  66526. var radius = radiusExtent[getRadiusIdx(polar)];
  66527. var lines = [];
  66528. for (var i = 0; i < minorTickAngles.length; i++) {
  66529. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66530. lines.push(new Line({
  66531. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  66532. }));
  66533. }
  66534. }
  66535. group.add(mergePath$1(lines, {
  66536. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  66537. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  66538. }))
  66539. }));
  66540. },
  66541. axisLabel: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  66542. var rawCategoryData = angleAxisModel.getCategories(true);
  66543. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  66544. var labelMargin = commonLabelModel.get('margin');
  66545. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  66546. each(labels, function (labelItem, idx) {
  66547. var labelModel = commonLabelModel;
  66548. var tickValue = labelItem.tickValue;
  66549. var r = radiusExtent[getRadiusIdx(polar)];
  66550. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  66551. var cx = polar.cx;
  66552. var cy = polar.cy;
  66553. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  66554. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  66555. if (rawCategoryData && rawCategoryData[tickValue]) {
  66556. var rawCategoryItem = rawCategoryData[tickValue];
  66557. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  66558. labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel);
  66559. }
  66560. }
  66561. var textEl = new ZRText({
  66562. silent: AxisBuilder.isLabelSilent(angleAxisModel),
  66563. style: createTextStyle(labelModel, {
  66564. x: p[0],
  66565. y: p[1],
  66566. fill: labelModel.getTextColor() || angleAxisModel.get(['axisLine', 'lineStyle', 'color']),
  66567. text: labelItem.formattedLabel,
  66568. align: labelTextAlign,
  66569. verticalAlign: labelTextVerticalAlign
  66570. })
  66571. });
  66572. group.add(textEl); // Pack data for mouse event
  66573. if (triggerEvent) {
  66574. var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  66575. eventData.targetType = 'axisLabel';
  66576. eventData.value = labelItem.rawLabel;
  66577. getECData(textEl).eventData = eventData;
  66578. }
  66579. }, this);
  66580. },
  66581. splitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66582. var splitLineModel = angleAxisModel.getModel('splitLine');
  66583. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66584. var lineColors = lineStyleModel.get('color');
  66585. var lineCount = 0;
  66586. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66587. var splitLines = [];
  66588. for (var i = 0; i < ticksAngles.length; i++) {
  66589. var colorIndex = lineCount++ % lineColors.length;
  66590. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66591. splitLines[colorIndex].push(new Line({
  66592. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  66593. }));
  66594. } // Simple optimization
  66595. // Batching the lines if color are the same
  66596. for (var i = 0; i < splitLines.length; i++) {
  66597. group.add(mergePath$1(splitLines[i], {
  66598. style: defaults({
  66599. stroke: lineColors[i % lineColors.length]
  66600. }, lineStyleModel.getLineStyle()),
  66601. silent: true,
  66602. z: angleAxisModel.get('z')
  66603. }));
  66604. }
  66605. },
  66606. minorSplitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66607. if (!minorTickAngles.length) {
  66608. return;
  66609. }
  66610. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  66611. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66612. var lines = [];
  66613. for (var i = 0; i < minorTickAngles.length; i++) {
  66614. for (var k = 0; k < minorTickAngles[i].length; k++) {
  66615. lines.push(new Line({
  66616. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  66617. }));
  66618. }
  66619. }
  66620. group.add(mergePath$1(lines, {
  66621. style: lineStyleModel.getLineStyle(),
  66622. silent: true,
  66623. z: angleAxisModel.get('z')
  66624. }));
  66625. },
  66626. splitArea: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  66627. if (!ticksAngles.length) {
  66628. return;
  66629. }
  66630. var splitAreaModel = angleAxisModel.getModel('splitArea');
  66631. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66632. var areaColors = areaStyleModel.get('color');
  66633. var lineCount = 0;
  66634. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66635. var splitAreas = [];
  66636. var RADIAN = Math.PI / 180;
  66637. var prevAngle = -ticksAngles[0].coord * RADIAN;
  66638. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  66639. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  66640. var clockwise = angleAxisModel.get('clockwise');
  66641. for (var i = 1, len = ticksAngles.length; i <= len; i++) {
  66642. var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord;
  66643. var colorIndex = lineCount++ % areaColors.length;
  66644. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66645. splitAreas[colorIndex].push(new Sector({
  66646. shape: {
  66647. cx: polar.cx,
  66648. cy: polar.cy,
  66649. r0: r0,
  66650. r: r1,
  66651. startAngle: prevAngle,
  66652. endAngle: -coord * RADIAN,
  66653. clockwise: clockwise
  66654. },
  66655. silent: true
  66656. }));
  66657. prevAngle = -coord * RADIAN;
  66658. } // Simple optimization
  66659. // Batching the lines if color are the same
  66660. for (var i = 0; i < splitAreas.length; i++) {
  66661. group.add(mergePath$1(splitAreas[i], {
  66662. style: defaults({
  66663. fill: areaColors[i % areaColors.length]
  66664. }, areaStyleModel.getAreaStyle()),
  66665. silent: true
  66666. }));
  66667. }
  66668. }
  66669. };
  66670. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  66671. var selfBuilderAttrs$1 = ['splitLine', 'splitArea', 'minorSplitLine'];
  66672. var RadiusAxisView =
  66673. /** @class */
  66674. function (_super) {
  66675. __extends(RadiusAxisView, _super);
  66676. function RadiusAxisView() {
  66677. var _this = _super !== null && _super.apply(this, arguments) || this;
  66678. _this.type = RadiusAxisView.type;
  66679. _this.axisPointerClass = 'PolarAxisPointer';
  66680. return _this;
  66681. }
  66682. RadiusAxisView.prototype.render = function (radiusAxisModel, ecModel) {
  66683. this.group.removeAll();
  66684. if (!radiusAxisModel.get('show')) {
  66685. return;
  66686. }
  66687. var oldAxisGroup = this._axisGroup;
  66688. var newAxisGroup = this._axisGroup = new Group();
  66689. this.group.add(newAxisGroup);
  66690. var radiusAxis = radiusAxisModel.axis;
  66691. var polar = radiusAxis.polar;
  66692. var angleAxis = polar.getAngleAxis();
  66693. var ticksCoords = radiusAxis.getTicksCoords();
  66694. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  66695. var axisAngle = angleAxis.getExtent()[0];
  66696. var radiusExtent = radiusAxis.getExtent();
  66697. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  66698. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  66699. each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  66700. newAxisGroup.add(axisBuilder.getGroup());
  66701. groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel);
  66702. each(selfBuilderAttrs$1, function (name) {
  66703. if (radiusAxisModel.get([name, 'show']) && !radiusAxis.scale.isBlank()) {
  66704. axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  66705. }
  66706. }, this);
  66707. };
  66708. RadiusAxisView.type = 'radiusAxis';
  66709. return RadiusAxisView;
  66710. }(AxisView);
  66711. var axisElementBuilders$1 = {
  66712. splitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66713. var splitLineModel = radiusAxisModel.getModel('splitLine');
  66714. var lineStyleModel = splitLineModel.getModel('lineStyle');
  66715. var lineColors = lineStyleModel.get('color');
  66716. var lineCount = 0;
  66717. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  66718. var splitLines = [];
  66719. for (var i = 0; i < ticksCoords.length; i++) {
  66720. var colorIndex = lineCount++ % lineColors.length;
  66721. splitLines[colorIndex] = splitLines[colorIndex] || [];
  66722. splitLines[colorIndex].push(new Circle({
  66723. shape: {
  66724. cx: polar.cx,
  66725. cy: polar.cy,
  66726. // ensure circle radius >= 0
  66727. r: Math.max(ticksCoords[i].coord, 0)
  66728. }
  66729. }));
  66730. } // Simple optimization
  66731. // Batching the lines if color are the same
  66732. for (var i = 0; i < splitLines.length; i++) {
  66733. group.add(mergePath$1(splitLines[i], {
  66734. style: defaults({
  66735. stroke: lineColors[i % lineColors.length],
  66736. fill: null
  66737. }, lineStyleModel.getLineStyle()),
  66738. silent: true
  66739. }));
  66740. }
  66741. },
  66742. minorSplitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  66743. if (!minorTicksCoords.length) {
  66744. return;
  66745. }
  66746. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  66747. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  66748. var lines = [];
  66749. for (var i = 0; i < minorTicksCoords.length; i++) {
  66750. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  66751. lines.push(new Circle({
  66752. shape: {
  66753. cx: polar.cx,
  66754. cy: polar.cy,
  66755. r: minorTicksCoords[i][k].coord
  66756. }
  66757. }));
  66758. }
  66759. }
  66760. group.add(mergePath$1(lines, {
  66761. style: defaults({
  66762. fill: null
  66763. }, lineStyleModel.getLineStyle()),
  66764. silent: true
  66765. }));
  66766. },
  66767. splitArea: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  66768. if (!ticksCoords.length) {
  66769. return;
  66770. }
  66771. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  66772. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  66773. var areaColors = areaStyleModel.get('color');
  66774. var lineCount = 0;
  66775. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  66776. var splitAreas = [];
  66777. var prevRadius = ticksCoords[0].coord;
  66778. for (var i = 1; i < ticksCoords.length; i++) {
  66779. var colorIndex = lineCount++ % areaColors.length;
  66780. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  66781. splitAreas[colorIndex].push(new Sector({
  66782. shape: {
  66783. cx: polar.cx,
  66784. cy: polar.cy,
  66785. r0: prevRadius,
  66786. r: ticksCoords[i].coord,
  66787. startAngle: 0,
  66788. endAngle: Math.PI * 2
  66789. },
  66790. silent: true
  66791. }));
  66792. prevRadius = ticksCoords[i].coord;
  66793. } // Simple optimization
  66794. // Batching the lines if color are the same
  66795. for (var i = 0; i < splitAreas.length; i++) {
  66796. group.add(mergePath$1(splitAreas[i], {
  66797. style: defaults({
  66798. fill: areaColors[i % areaColors.length]
  66799. }, areaStyleModel.getAreaStyle()),
  66800. silent: true
  66801. }));
  66802. }
  66803. }
  66804. };
  66805. /**
  66806. * @inner
  66807. */
  66808. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  66809. return {
  66810. position: [polar.cx, polar.cy],
  66811. rotation: axisAngle / 180 * Math.PI,
  66812. labelDirection: -1,
  66813. tickDirection: -1,
  66814. nameDirection: 1,
  66815. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  66816. // Over splitLine and splitArea
  66817. z2: 1
  66818. };
  66819. }
  66820. function getSeriesStackId$1(seriesModel) {
  66821. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  66822. }
  66823. function getAxisKey$1(polar, axis) {
  66824. return axis.dim + polar.model.componentIndex;
  66825. }
  66826. function barLayoutPolar(seriesType, ecModel, api) {
  66827. var lastStackCoords = {};
  66828. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  66829. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  66830. }));
  66831. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  66832. // Check series coordinate, do layout for polar only
  66833. if (seriesModel.coordinateSystem.type !== 'polar') {
  66834. return;
  66835. }
  66836. var data = seriesModel.getData();
  66837. var polar = seriesModel.coordinateSystem;
  66838. var baseAxis = polar.getBaseAxis();
  66839. var axisKey = getAxisKey$1(polar, baseAxis);
  66840. var stackId = getSeriesStackId$1(seriesModel);
  66841. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  66842. var columnOffset = columnLayoutInfo.offset;
  66843. var columnWidth = columnLayoutInfo.width;
  66844. var valueAxis = polar.getOtherAxis(baseAxis);
  66845. var cx = seriesModel.coordinateSystem.cx;
  66846. var cy = seriesModel.coordinateSystem.cy;
  66847. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  66848. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  66849. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  66850. var valueDim = data.mapDimension(valueAxis.dim);
  66851. var baseDim = data.mapDimension(baseAxis.dim);
  66852. var stacked = isDimensionStacked(data, valueDim
  66853. /* , baseDim */
  66854. );
  66855. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  66856. var valueAxisStart = valueAxis.dataToCoord(0);
  66857. for (var idx = 0, len = data.count(); idx < len; idx++) {
  66858. var value = data.get(valueDim, idx);
  66859. var baseValue = data.get(baseDim, idx);
  66860. var sign = value >= 0 ? 'p' : 'n';
  66861. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  66862. // stackResultDimension directly.
  66863. // Only ordinal axis can be stacked.
  66864. if (stacked) {
  66865. if (!lastStackCoords[stackId][baseValue]) {
  66866. lastStackCoords[stackId][baseValue] = {
  66867. p: valueAxisStart,
  66868. n: valueAxisStart // Negative stack
  66869. };
  66870. } // Should also consider #4243
  66871. baseCoord = lastStackCoords[stackId][baseValue][sign];
  66872. }
  66873. var r0 = void 0;
  66874. var r = void 0;
  66875. var startAngle = void 0;
  66876. var endAngle = void 0; // radial sector
  66877. if (valueAxis.dim === 'radius') {
  66878. var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart;
  66879. var angle = baseAxis.dataToCoord(baseValue);
  66880. if (Math.abs(radiusSpan) < barMinHeight) {
  66881. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  66882. }
  66883. r0 = baseCoord;
  66884. r = baseCoord + radiusSpan;
  66885. startAngle = angle - columnOffset;
  66886. endAngle = startAngle - columnWidth;
  66887. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  66888. } // tangential sector
  66889. else {
  66890. var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart;
  66891. var radius = baseAxis.dataToCoord(baseValue);
  66892. if (Math.abs(angleSpan) < barMinAngle) {
  66893. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  66894. }
  66895. r0 = radius + columnOffset;
  66896. r = r0 + columnWidth;
  66897. startAngle = baseCoord;
  66898. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  66899. // add a round to differentiate it from origin
  66900. // let extent = angleAxis.getExtent();
  66901. // let stackCoord = angle;
  66902. // if (stackCoord === extent[0] && value > 0) {
  66903. // stackCoord = extent[1];
  66904. // }
  66905. // else if (stackCoord === extent[1] && value < 0) {
  66906. // stackCoord = extent[0];
  66907. // }
  66908. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  66909. }
  66910. data.setItemLayout(idx, {
  66911. cx: cx,
  66912. cy: cy,
  66913. r0: r0,
  66914. r: r,
  66915. // Consider that positive angle is anti-clockwise,
  66916. // while positive radian of sector is clockwise
  66917. startAngle: -startAngle * Math.PI / 180,
  66918. endAngle: -endAngle * Math.PI / 180,
  66919. /**
  66920. * Keep the same logic with bar in catesion: use end value to
  66921. * control direction. Notice that if clockwise is true (by
  66922. * default), the sector will always draw clockwisely, no matter
  66923. * whether endAngle is greater or less than startAngle.
  66924. */
  66925. clockwise: startAngle >= endAngle
  66926. });
  66927. }
  66928. });
  66929. }
  66930. /**
  66931. * Calculate bar width and offset for radial bar charts
  66932. */
  66933. function calRadialBar(barSeries) {
  66934. // Columns info on each category axis. Key is polar name
  66935. var columnsMap = {};
  66936. each(barSeries, function (seriesModel, idx) {
  66937. var data = seriesModel.getData();
  66938. var polar = seriesModel.coordinateSystem;
  66939. var baseAxis = polar.getBaseAxis();
  66940. var axisKey = getAxisKey$1(polar, baseAxis);
  66941. var axisExtent = baseAxis.getExtent();
  66942. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  66943. var columnsOnAxis = columnsMap[axisKey] || {
  66944. bandWidth: bandWidth,
  66945. remainedWidth: bandWidth,
  66946. autoWidthCount: 0,
  66947. categoryGap: '20%',
  66948. gap: '30%',
  66949. stacks: {}
  66950. };
  66951. var stacks = columnsOnAxis.stacks;
  66952. columnsMap[axisKey] = columnsOnAxis;
  66953. var stackId = getSeriesStackId$1(seriesModel);
  66954. if (!stacks[stackId]) {
  66955. columnsOnAxis.autoWidthCount++;
  66956. }
  66957. stacks[stackId] = stacks[stackId] || {
  66958. width: 0,
  66959. maxWidth: 0
  66960. };
  66961. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  66962. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  66963. var barGap = seriesModel.get('barGap');
  66964. var barCategoryGap = seriesModel.get('barCategoryGap');
  66965. if (barWidth && !stacks[stackId].width) {
  66966. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  66967. stacks[stackId].width = barWidth;
  66968. columnsOnAxis.remainedWidth -= barWidth;
  66969. }
  66970. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  66971. barGap != null && (columnsOnAxis.gap = barGap);
  66972. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  66973. });
  66974. var result = {};
  66975. each(columnsMap, function (columnsOnAxis, coordSysName) {
  66976. result[coordSysName] = {};
  66977. var stacks = columnsOnAxis.stacks;
  66978. var bandWidth = columnsOnAxis.bandWidth;
  66979. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  66980. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  66981. var remainedWidth = columnsOnAxis.remainedWidth;
  66982. var autoWidthCount = columnsOnAxis.autoWidthCount;
  66983. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66984. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  66985. each(stacks, function (column, stack) {
  66986. var maxWidth = column.maxWidth;
  66987. if (maxWidth && maxWidth < autoWidth) {
  66988. maxWidth = Math.min(maxWidth, remainedWidth);
  66989. if (column.width) {
  66990. maxWidth = Math.min(maxWidth, column.width);
  66991. }
  66992. remainedWidth -= maxWidth;
  66993. column.width = maxWidth;
  66994. autoWidthCount--;
  66995. }
  66996. }); // Recalculate width again
  66997. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  66998. autoWidth = Math.max(autoWidth, 0);
  66999. var widthSum = 0;
  67000. var lastColumn;
  67001. each(stacks, function (column, idx) {
  67002. if (!column.width) {
  67003. column.width = autoWidth;
  67004. }
  67005. lastColumn = column;
  67006. widthSum += column.width * (1 + barGapPercent);
  67007. });
  67008. if (lastColumn) {
  67009. widthSum -= lastColumn.width * barGapPercent;
  67010. }
  67011. var offset = -widthSum / 2;
  67012. each(stacks, function (column, stackId) {
  67013. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  67014. offset: offset,
  67015. width: column.width
  67016. };
  67017. offset += column.width * (1 + barGapPercent);
  67018. });
  67019. });
  67020. return result;
  67021. }
  67022. var angleAxisExtraOption = {
  67023. startAngle: 90,
  67024. clockwise: true,
  67025. splitNumber: 12,
  67026. axisLabel: {
  67027. rotate: 0
  67028. }
  67029. };
  67030. var radiusAxisExtraOption = {
  67031. splitNumber: 5
  67032. };
  67033. var PolarView =
  67034. /** @class */
  67035. function (_super) {
  67036. __extends(PolarView, _super);
  67037. function PolarView() {
  67038. var _this = _super !== null && _super.apply(this, arguments) || this;
  67039. _this.type = PolarView.type;
  67040. return _this;
  67041. }
  67042. PolarView.type = 'polar';
  67043. return PolarView;
  67044. }(ComponentView);
  67045. function install$u(registers) {
  67046. use(install$s);
  67047. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  67048. registers.registerCoordinateSystem('polar', polarCreator);
  67049. registers.registerComponentModel(PolarModel);
  67050. registers.registerComponentView(PolarView); // Model and view for angleAxis and radiusAxis
  67051. axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption);
  67052. axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption);
  67053. registers.registerComponentView(AngleAxisView);
  67054. registers.registerComponentView(RadiusAxisView);
  67055. registers.registerLayout(curry(barLayoutPolar, 'bar'));
  67056. }
  67057. function layout$2(axisModel, opt) {
  67058. opt = opt || {};
  67059. var single = axisModel.coordinateSystem;
  67060. var axis = axisModel.axis;
  67061. var layout = {};
  67062. var axisPosition = axis.position;
  67063. var orient = axis.orient;
  67064. var rect = single.getRect();
  67065. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  67066. var positionMap = {
  67067. horizontal: {
  67068. top: rectBound[2],
  67069. bottom: rectBound[3]
  67070. },
  67071. vertical: {
  67072. left: rectBound[0],
  67073. right: rectBound[1]
  67074. }
  67075. };
  67076. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  67077. var r = {
  67078. horizontal: 0,
  67079. vertical: 1
  67080. };
  67081. layout.rotation = Math.PI / 2 * r[orient];
  67082. var directionMap = {
  67083. top: -1,
  67084. bottom: 1,
  67085. right: 1,
  67086. left: -1
  67087. };
  67088. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  67089. if (axisModel.get(['axisTick', 'inside'])) {
  67090. layout.tickDirection = -layout.tickDirection;
  67091. }
  67092. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  67093. layout.labelDirection = -layout.labelDirection;
  67094. }
  67095. var labelRotation = opt.rotate;
  67096. labelRotation == null && (labelRotation = axisModel.get(['axisLabel', 'rotate']));
  67097. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  67098. layout.z2 = 1;
  67099. return layout;
  67100. }
  67101. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  67102. var selfBuilderAttrs$2 = ['splitArea', 'splitLine'];
  67103. var SingleAxisView =
  67104. /** @class */
  67105. function (_super) {
  67106. __extends(SingleAxisView, _super);
  67107. function SingleAxisView() {
  67108. var _this = _super !== null && _super.apply(this, arguments) || this;
  67109. _this.type = SingleAxisView.type;
  67110. _this.axisPointerClass = 'SingleAxisPointer';
  67111. return _this;
  67112. }
  67113. SingleAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  67114. var group = this.group;
  67115. group.removeAll();
  67116. var oldAxisGroup = this._axisGroup;
  67117. this._axisGroup = new Group();
  67118. var layout = layout$2(axisModel);
  67119. var axisBuilder = new AxisBuilder(axisModel, layout);
  67120. each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  67121. group.add(this._axisGroup);
  67122. group.add(axisBuilder.getGroup());
  67123. each(selfBuilderAttrs$2, function (name) {
  67124. if (axisModel.get([name, 'show'])) {
  67125. axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel);
  67126. }
  67127. }, this);
  67128. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  67129. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  67130. };
  67131. SingleAxisView.prototype.remove = function () {
  67132. rectCoordAxisHandleRemove(this);
  67133. };
  67134. SingleAxisView.type = 'singleAxis';
  67135. return SingleAxisView;
  67136. }(AxisView);
  67137. var axisElementBuilders$2 = {
  67138. splitLine: function (axisView, group, axisGroup, axisModel) {
  67139. var axis = axisModel.axis;
  67140. if (axis.scale.isBlank()) {
  67141. return;
  67142. }
  67143. var splitLineModel = axisModel.getModel('splitLine');
  67144. var lineStyleModel = splitLineModel.getModel('lineStyle');
  67145. var lineColors = lineStyleModel.get('color');
  67146. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  67147. var lineWidth = lineStyleModel.get('width');
  67148. var gridRect = axisModel.coordinateSystem.getRect();
  67149. var isHorizontal = axis.isHorizontal();
  67150. var splitLines = [];
  67151. var lineCount = 0;
  67152. var ticksCoords = axis.getTicksCoords({
  67153. tickModel: splitLineModel
  67154. });
  67155. var p1 = [];
  67156. var p2 = [];
  67157. for (var i = 0; i < ticksCoords.length; ++i) {
  67158. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  67159. if (isHorizontal) {
  67160. p1[0] = tickCoord;
  67161. p1[1] = gridRect.y;
  67162. p2[0] = tickCoord;
  67163. p2[1] = gridRect.y + gridRect.height;
  67164. } else {
  67165. p1[0] = gridRect.x;
  67166. p1[1] = tickCoord;
  67167. p2[0] = gridRect.x + gridRect.width;
  67168. p2[1] = tickCoord;
  67169. }
  67170. var line = new Line({
  67171. shape: {
  67172. x1: p1[0],
  67173. y1: p1[1],
  67174. x2: p2[0],
  67175. y2: p2[1]
  67176. },
  67177. silent: true
  67178. });
  67179. subPixelOptimizeLine$1(line.shape, lineWidth);
  67180. var colorIndex = lineCount++ % lineColors.length;
  67181. splitLines[colorIndex] = splitLines[colorIndex] || [];
  67182. splitLines[colorIndex].push(line);
  67183. }
  67184. var lineStyle = lineStyleModel.getLineStyle(['color']);
  67185. for (var i = 0; i < splitLines.length; ++i) {
  67186. group.add(mergePath$1(splitLines[i], {
  67187. style: defaults({
  67188. stroke: lineColors[i % lineColors.length]
  67189. }, lineStyle),
  67190. silent: true
  67191. }));
  67192. }
  67193. },
  67194. splitArea: function (axisView, group, axisGroup, axisModel) {
  67195. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel);
  67196. }
  67197. };
  67198. var SingleAxisModel =
  67199. /** @class */
  67200. function (_super) {
  67201. __extends(SingleAxisModel, _super);
  67202. function SingleAxisModel() {
  67203. var _this = _super !== null && _super.apply(this, arguments) || this;
  67204. _this.type = SingleAxisModel.type;
  67205. return _this;
  67206. }
  67207. SingleAxisModel.prototype.getCoordSysModel = function () {
  67208. return this;
  67209. };
  67210. SingleAxisModel.type = 'singleAxis';
  67211. SingleAxisModel.layoutMode = 'box';
  67212. SingleAxisModel.defaultOption = {
  67213. left: '5%',
  67214. top: '5%',
  67215. right: '5%',
  67216. bottom: '5%',
  67217. type: 'value',
  67218. position: 'bottom',
  67219. orient: 'horizontal',
  67220. axisLine: {
  67221. show: true,
  67222. lineStyle: {
  67223. width: 1,
  67224. type: 'solid'
  67225. }
  67226. },
  67227. // Single coordinate system and single axis is the,
  67228. // which is used as the parent tooltip model.
  67229. // same model, so we set default tooltip show as true.
  67230. tooltip: {
  67231. show: true
  67232. },
  67233. axisTick: {
  67234. show: true,
  67235. length: 6,
  67236. lineStyle: {
  67237. width: 1
  67238. }
  67239. },
  67240. axisLabel: {
  67241. show: true,
  67242. interval: 'auto'
  67243. },
  67244. splitLine: {
  67245. show: true,
  67246. lineStyle: {
  67247. type: 'dashed',
  67248. opacity: 0.2
  67249. }
  67250. }
  67251. };
  67252. return SingleAxisModel;
  67253. }(ComponentModel);
  67254. mixin(SingleAxisModel, AxisModelCommonMixin.prototype);
  67255. var SingleAxis =
  67256. /** @class */
  67257. function (_super) {
  67258. __extends(SingleAxis, _super);
  67259. function SingleAxis(dim, scale, coordExtent, axisType, position) {
  67260. var _this = _super.call(this, dim, scale, coordExtent) || this;
  67261. _this.type = axisType || 'value';
  67262. _this.position = position || 'bottom';
  67263. return _this;
  67264. }
  67265. /**
  67266. * Judge the orient of the axis.
  67267. */
  67268. SingleAxis.prototype.isHorizontal = function () {
  67269. var position = this.position;
  67270. return position === 'top' || position === 'bottom';
  67271. };
  67272. SingleAxis.prototype.pointToData = function (point, clamp) {
  67273. return this.coordinateSystem.pointToData(point)[0];
  67274. };
  67275. return SingleAxis;
  67276. }(Axis);
  67277. var singleDimensions = ['single'];
  67278. /**
  67279. * Create a single coordinates system.
  67280. */
  67281. var Single =
  67282. /** @class */
  67283. function () {
  67284. function Single(axisModel, ecModel, api) {
  67285. this.type = 'single';
  67286. this.dimension = 'single';
  67287. /**
  67288. * Add it just for draw tooltip.
  67289. */
  67290. this.dimensions = singleDimensions;
  67291. this.axisPointerEnabled = true;
  67292. this.model = axisModel;
  67293. this._init(axisModel, ecModel, api);
  67294. }
  67295. /**
  67296. * Initialize single coordinate system.
  67297. */
  67298. Single.prototype._init = function (axisModel, ecModel, api) {
  67299. var dim = this.dimension;
  67300. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  67301. var isCategory = axis.type === 'category';
  67302. axis.onBand = isCategory && axisModel.get('boundaryGap');
  67303. axis.inverse = axisModel.get('inverse');
  67304. axis.orient = axisModel.get('orient');
  67305. axisModel.axis = axis;
  67306. axis.model = axisModel;
  67307. axis.coordinateSystem = this;
  67308. this._axis = axis;
  67309. };
  67310. /**
  67311. * Update axis scale after data processed
  67312. */
  67313. Single.prototype.update = function (ecModel, api) {
  67314. ecModel.eachSeries(function (seriesModel) {
  67315. if (seriesModel.coordinateSystem === this) {
  67316. var data_1 = seriesModel.getData();
  67317. each(data_1.mapDimensionsAll(this.dimension), function (dim) {
  67318. this._axis.scale.unionExtentFromData(data_1, dim);
  67319. }, this);
  67320. niceScaleExtent(this._axis.scale, this._axis.model);
  67321. }
  67322. }, this);
  67323. };
  67324. /**
  67325. * Resize the single coordinate system.
  67326. */
  67327. Single.prototype.resize = function (axisModel, api) {
  67328. this._rect = getLayoutRect({
  67329. left: axisModel.get('left'),
  67330. top: axisModel.get('top'),
  67331. right: axisModel.get('right'),
  67332. bottom: axisModel.get('bottom'),
  67333. width: axisModel.get('width'),
  67334. height: axisModel.get('height')
  67335. }, {
  67336. width: api.getWidth(),
  67337. height: api.getHeight()
  67338. });
  67339. this._adjustAxis();
  67340. };
  67341. Single.prototype.getRect = function () {
  67342. return this._rect;
  67343. };
  67344. Single.prototype._adjustAxis = function () {
  67345. var rect = this._rect;
  67346. var axis = this._axis;
  67347. var isHorizontal = axis.isHorizontal();
  67348. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  67349. var idx = axis.inverse ? 1 : 0;
  67350. axis.setExtent(extent[idx], extent[1 - idx]);
  67351. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  67352. };
  67353. Single.prototype._updateAxisTransform = function (axis, coordBase) {
  67354. var axisExtent = axis.getExtent();
  67355. var extentSum = axisExtent[0] + axisExtent[1];
  67356. var isHorizontal = axis.isHorizontal();
  67357. axis.toGlobalCoord = isHorizontal ? function (coord) {
  67358. return coord + coordBase;
  67359. } : function (coord) {
  67360. return extentSum - coord + coordBase;
  67361. };
  67362. axis.toLocalCoord = isHorizontal ? function (coord) {
  67363. return coord - coordBase;
  67364. } : function (coord) {
  67365. return extentSum - coord + coordBase;
  67366. };
  67367. };
  67368. /**
  67369. * Get axis.
  67370. */
  67371. Single.prototype.getAxis = function () {
  67372. return this._axis;
  67373. };
  67374. /**
  67375. * Get axis, add it just for draw tooltip.
  67376. */
  67377. Single.prototype.getBaseAxis = function () {
  67378. return this._axis;
  67379. };
  67380. Single.prototype.getAxes = function () {
  67381. return [this._axis];
  67382. };
  67383. Single.prototype.getTooltipAxes = function () {
  67384. return {
  67385. baseAxes: [this.getAxis()],
  67386. // Empty otherAxes
  67387. otherAxes: []
  67388. };
  67389. };
  67390. /**
  67391. * If contain point.
  67392. */
  67393. Single.prototype.containPoint = function (point) {
  67394. var rect = this.getRect();
  67395. var axis = this.getAxis();
  67396. var orient = axis.orient;
  67397. if (orient === 'horizontal') {
  67398. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  67399. } else {
  67400. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  67401. }
  67402. };
  67403. Single.prototype.pointToData = function (point) {
  67404. var axis = this.getAxis();
  67405. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  67406. };
  67407. /**
  67408. * Convert the series data to concrete point.
  67409. * Can be [val] | val
  67410. */
  67411. Single.prototype.dataToPoint = function (val) {
  67412. var axis = this.getAxis();
  67413. var rect = this.getRect();
  67414. var pt = [];
  67415. var idx = axis.orient === 'horizontal' ? 0 : 1;
  67416. if (val instanceof Array) {
  67417. val = val[0];
  67418. }
  67419. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  67420. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  67421. return pt;
  67422. };
  67423. Single.prototype.convertToPixel = function (ecModel, finder, value) {
  67424. var coordSys = getCoordSys$3(finder);
  67425. return coordSys === this ? this.dataToPoint(value) : null;
  67426. };
  67427. Single.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  67428. var coordSys = getCoordSys$3(finder);
  67429. return coordSys === this ? this.pointToData(pixel) : null;
  67430. };
  67431. return Single;
  67432. }();
  67433. function getCoordSys$3(finder) {
  67434. var seriesModel = finder.seriesModel;
  67435. var singleModel = finder.singleAxisModel;
  67436. return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  67437. }
  67438. /**
  67439. * Create single coordinate system and inject it into seriesModel.
  67440. */
  67441. function create$2(ecModel, api) {
  67442. var singles = [];
  67443. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  67444. var single = new Single(axisModel, ecModel, api);
  67445. single.name = 'single_' + idx;
  67446. single.resize(axisModel, api);
  67447. axisModel.coordinateSystem = single;
  67448. singles.push(single);
  67449. });
  67450. ecModel.eachSeries(function (seriesModel) {
  67451. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  67452. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  67453. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  67454. }
  67455. });
  67456. return singles;
  67457. }
  67458. var singleCreator = {
  67459. create: create$2,
  67460. dimensions: singleDimensions
  67461. };
  67462. var XY = ['x', 'y'];
  67463. var WH = ['width', 'height'];
  67464. var SingleAxisPointer =
  67465. /** @class */
  67466. function (_super) {
  67467. __extends(SingleAxisPointer, _super);
  67468. function SingleAxisPointer() {
  67469. return _super !== null && _super.apply(this, arguments) || this;
  67470. }
  67471. /**
  67472. * @override
  67473. */
  67474. SingleAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  67475. var axis = axisModel.axis;
  67476. var coordSys = axis.coordinateSystem;
  67477. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  67478. var pixelValue = coordSys.dataToPoint(value)[0];
  67479. var axisPointerType = axisPointerModel.get('type');
  67480. if (axisPointerType && axisPointerType !== 'none') {
  67481. var elStyle = buildElStyle(axisPointerModel);
  67482. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent);
  67483. pointerOption.style = elStyle;
  67484. elOption.graphicKey = pointerOption.type;
  67485. elOption.pointer = pointerOption;
  67486. }
  67487. var layoutInfo = layout$2(axisModel);
  67488. buildCartesianSingleLabelElOption( // @ts-ignore
  67489. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  67490. };
  67491. /**
  67492. * @override
  67493. */
  67494. SingleAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  67495. var layoutInfo = layout$2(axisModel, {
  67496. labelInside: false
  67497. }); // @ts-ignore
  67498. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  67499. var position = getTransformedPosition(axisModel.axis, value, layoutInfo);
  67500. return {
  67501. x: position[0],
  67502. y: position[1],
  67503. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  67504. };
  67505. };
  67506. /**
  67507. * @override
  67508. */
  67509. SingleAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  67510. var axis = axisModel.axis;
  67511. var coordSys = axis.coordinateSystem;
  67512. var dimIndex = getPointDimIndex(axis);
  67513. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  67514. var currPosition = [transform.x, transform.y];
  67515. currPosition[dimIndex] += delta[dimIndex];
  67516. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  67517. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  67518. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  67519. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  67520. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  67521. cursorPoint[dimIndex] = currPosition[dimIndex];
  67522. return {
  67523. x: currPosition[0],
  67524. y: currPosition[1],
  67525. rotation: transform.rotation,
  67526. cursorPoint: cursorPoint,
  67527. tooltipOption: {
  67528. verticalAlign: 'middle'
  67529. }
  67530. };
  67531. };
  67532. return SingleAxisPointer;
  67533. }(BaseAxisPointer);
  67534. var pointerShapeBuilder$2 = {
  67535. line: function (axis, pixelValue, otherExtent) {
  67536. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  67537. return {
  67538. type: 'Line',
  67539. subPixelOptimize: true,
  67540. shape: targetShape
  67541. };
  67542. },
  67543. shadow: function (axis, pixelValue, otherExtent) {
  67544. var bandWidth = axis.getBandWidth();
  67545. var span = otherExtent[1] - otherExtent[0];
  67546. return {
  67547. type: 'Rect',
  67548. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  67549. };
  67550. }
  67551. };
  67552. function getPointDimIndex(axis) {
  67553. return axis.isHorizontal() ? 0 : 1;
  67554. }
  67555. function getGlobalExtent(coordSys, dimIndex) {
  67556. var rect = coordSys.getRect();
  67557. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  67558. }
  67559. var SingleView =
  67560. /** @class */
  67561. function (_super) {
  67562. __extends(SingleView, _super);
  67563. function SingleView() {
  67564. var _this = _super !== null && _super.apply(this, arguments) || this;
  67565. _this.type = SingleView.type;
  67566. return _this;
  67567. }
  67568. SingleView.type = 'single';
  67569. return SingleView;
  67570. }(ComponentView);
  67571. function install$v(registers) {
  67572. use(install$s);
  67573. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  67574. registers.registerComponentView(SingleView); // Axis
  67575. registers.registerComponentView(SingleAxisView);
  67576. registers.registerComponentModel(SingleAxisModel);
  67577. axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption);
  67578. registers.registerCoordinateSystem('single', singleCreator);
  67579. }
  67580. var CalendarModel =
  67581. /** @class */
  67582. function (_super) {
  67583. __extends(CalendarModel, _super);
  67584. function CalendarModel() {
  67585. var _this = _super !== null && _super.apply(this, arguments) || this;
  67586. _this.type = CalendarModel.type;
  67587. return _this;
  67588. }
  67589. /**
  67590. * @override
  67591. */
  67592. CalendarModel.prototype.init = function (option, parentModel, ecModel) {
  67593. var inputPositionParams = getLayoutParams(option);
  67594. _super.prototype.init.apply(this, arguments);
  67595. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  67596. };
  67597. /**
  67598. * @override
  67599. */
  67600. CalendarModel.prototype.mergeOption = function (option) {
  67601. _super.prototype.mergeOption.apply(this, arguments);
  67602. mergeAndNormalizeLayoutParams(this.option, option);
  67603. };
  67604. CalendarModel.prototype.getCellSize = function () {
  67605. // Has been normalized
  67606. return this.option.cellSize;
  67607. };
  67608. CalendarModel.type = 'calendar';
  67609. CalendarModel.defaultOption = {
  67610. // zlevel: 0,
  67611. z: 2,
  67612. left: 80,
  67613. top: 60,
  67614. cellSize: 20,
  67615. // horizontal vertical
  67616. orient: 'horizontal',
  67617. // month separate line style
  67618. splitLine: {
  67619. show: true,
  67620. lineStyle: {
  67621. color: '#000',
  67622. width: 1,
  67623. type: 'solid'
  67624. }
  67625. },
  67626. // rect style temporarily unused emphasis
  67627. itemStyle: {
  67628. color: '#fff',
  67629. borderWidth: 1,
  67630. borderColor: '#ccc'
  67631. },
  67632. // week text style
  67633. dayLabel: {
  67634. show: true,
  67635. firstDay: 0,
  67636. // start end
  67637. position: 'start',
  67638. margin: '50%',
  67639. color: '#000'
  67640. },
  67641. // month text style
  67642. monthLabel: {
  67643. show: true,
  67644. // start end
  67645. position: 'start',
  67646. margin: 5,
  67647. // center or left
  67648. align: 'center',
  67649. formatter: null,
  67650. color: '#000'
  67651. },
  67652. // year text style
  67653. yearLabel: {
  67654. show: true,
  67655. // top bottom left right
  67656. position: null,
  67657. margin: 30,
  67658. formatter: null,
  67659. color: '#ccc',
  67660. fontFamily: 'sans-serif',
  67661. fontWeight: 'bolder',
  67662. fontSize: 20
  67663. }
  67664. };
  67665. return CalendarModel;
  67666. }(ComponentModel);
  67667. function mergeAndNormalizeLayoutParams(target, raw) {
  67668. // Normalize cellSize
  67669. var cellSize = target.cellSize;
  67670. var cellSizeArr;
  67671. if (!isArray(cellSize)) {
  67672. cellSizeArr = target.cellSize = [cellSize, cellSize];
  67673. } else {
  67674. cellSizeArr = cellSize;
  67675. }
  67676. if (cellSizeArr.length === 1) {
  67677. cellSizeArr[1] = cellSizeArr[0];
  67678. }
  67679. var ignoreSize = map([0, 1], function (hvIdx) {
  67680. // If user have set `width` or both `left` and `right`, cellSizeArr
  67681. // will be automatically set to 'auto', otherwise the default
  67682. // setting of cellSizeArr will make `width` setting not work.
  67683. if (sizeCalculable(raw, hvIdx)) {
  67684. cellSizeArr[hvIdx] = 'auto';
  67685. }
  67686. return cellSizeArr[hvIdx] != null && cellSizeArr[hvIdx] !== 'auto';
  67687. });
  67688. mergeLayoutParam(target, raw, {
  67689. type: 'box',
  67690. ignoreSize: ignoreSize
  67691. });
  67692. }
  67693. var CalendarView =
  67694. /** @class */
  67695. function (_super) {
  67696. __extends(CalendarView, _super);
  67697. function CalendarView() {
  67698. var _this = _super !== null && _super.apply(this, arguments) || this;
  67699. _this.type = CalendarView.type;
  67700. return _this;
  67701. }
  67702. CalendarView.prototype.render = function (calendarModel, ecModel, api) {
  67703. var group = this.group;
  67704. group.removeAll();
  67705. var coordSys = calendarModel.coordinateSystem; // range info
  67706. var rangeData = coordSys.getRangeInfo();
  67707. var orient = coordSys.getOrient(); // locale
  67708. var localeModel = ecModel.getLocaleModel();
  67709. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  67710. this._renderLines(calendarModel, rangeData, orient, group);
  67711. this._renderYearText(calendarModel, rangeData, orient, group);
  67712. this._renderMonthText(calendarModel, localeModel, orient, group);
  67713. this._renderWeekText(calendarModel, localeModel, rangeData, orient, group);
  67714. }; // render day rect
  67715. CalendarView.prototype._renderDayRect = function (calendarModel, rangeData, group) {
  67716. var coordSys = calendarModel.coordinateSystem;
  67717. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  67718. var sw = coordSys.getCellWidth();
  67719. var sh = coordSys.getCellHeight();
  67720. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  67721. var point = coordSys.dataToRect([i], false).tl; // every rect
  67722. var rect = new Rect({
  67723. shape: {
  67724. x: point[0],
  67725. y: point[1],
  67726. width: sw,
  67727. height: sh
  67728. },
  67729. cursor: 'default',
  67730. style: itemRectStyleModel
  67731. });
  67732. group.add(rect);
  67733. }
  67734. }; // render separate line
  67735. CalendarView.prototype._renderLines = function (calendarModel, rangeData, orient, group) {
  67736. var self = this;
  67737. var coordSys = calendarModel.coordinateSystem;
  67738. var lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle();
  67739. var show = calendarModel.get(['splitLine', 'show']);
  67740. var lineWidth = lineStyleModel.lineWidth;
  67741. this._tlpoints = [];
  67742. this._blpoints = [];
  67743. this._firstDayOfMonth = [];
  67744. this._firstDayPoints = [];
  67745. var firstDay = rangeData.start;
  67746. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  67747. addPoints(firstDay.formatedDate);
  67748. if (i === 0) {
  67749. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  67750. }
  67751. var date = firstDay.date;
  67752. date.setMonth(date.getMonth() + 1);
  67753. firstDay = coordSys.getDateInfo(date);
  67754. }
  67755. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  67756. function addPoints(date) {
  67757. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  67758. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  67759. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  67760. self._tlpoints.push(points[0]);
  67761. self._blpoints.push(points[points.length - 1]);
  67762. show && self._drawSplitline(points, lineStyleModel, group);
  67763. } // render top/left line
  67764. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  67765. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  67766. }; // get points at both ends
  67767. CalendarView.prototype._getEdgesPoints = function (points, lineWidth, orient) {
  67768. var rs = [points[0].slice(), points[points.length - 1].slice()];
  67769. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  67770. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  67771. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  67772. return rs;
  67773. }; // render split line
  67774. CalendarView.prototype._drawSplitline = function (points, lineStyle, group) {
  67775. var poyline = new Polyline({
  67776. z2: 20,
  67777. shape: {
  67778. points: points
  67779. },
  67780. style: lineStyle
  67781. });
  67782. group.add(poyline);
  67783. }; // render month line of one week points
  67784. CalendarView.prototype._getLinePointsOfOneWeek = function (calendarModel, date, orient) {
  67785. var coordSys = calendarModel.coordinateSystem;
  67786. var parsedDate = coordSys.getDateInfo(date);
  67787. var points = [];
  67788. for (var i = 0; i < 7; i++) {
  67789. var tmpD = coordSys.getNextNDay(parsedDate.time, i);
  67790. var point = coordSys.dataToRect([tmpD.time], false);
  67791. points[2 * tmpD.day] = point.tl;
  67792. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  67793. }
  67794. return points;
  67795. };
  67796. CalendarView.prototype._formatterLabel = function (formatter, params) {
  67797. if (isString(formatter) && formatter) {
  67798. return formatTplSimple(formatter, params);
  67799. }
  67800. if (isFunction(formatter)) {
  67801. return formatter(params);
  67802. }
  67803. return params.nameMap;
  67804. };
  67805. CalendarView.prototype._yearTextPositionControl = function (textEl, point, orient, position, margin) {
  67806. var x = point[0];
  67807. var y = point[1];
  67808. var aligns = ['center', 'bottom'];
  67809. if (position === 'bottom') {
  67810. y += margin;
  67811. aligns = ['center', 'top'];
  67812. } else if (position === 'left') {
  67813. x -= margin;
  67814. } else if (position === 'right') {
  67815. x += margin;
  67816. aligns = ['center', 'top'];
  67817. } else {
  67818. // top
  67819. y -= margin;
  67820. }
  67821. var rotate = 0;
  67822. if (position === 'left' || position === 'right') {
  67823. rotate = Math.PI / 2;
  67824. }
  67825. return {
  67826. rotation: rotate,
  67827. x: x,
  67828. y: y,
  67829. style: {
  67830. align: aligns[0],
  67831. verticalAlign: aligns[1]
  67832. }
  67833. };
  67834. }; // render year
  67835. CalendarView.prototype._renderYearText = function (calendarModel, rangeData, orient, group) {
  67836. var yearLabel = calendarModel.getModel('yearLabel');
  67837. if (!yearLabel.get('show')) {
  67838. return;
  67839. }
  67840. var margin = yearLabel.get('margin');
  67841. var pos = yearLabel.get('position');
  67842. if (!pos) {
  67843. pos = orient !== 'horizontal' ? 'top' : 'left';
  67844. }
  67845. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  67846. var xc = (points[0][0] + points[1][0]) / 2;
  67847. var yc = (points[0][1] + points[1][1]) / 2;
  67848. var idx = orient === 'horizontal' ? 0 : 1;
  67849. var posPoints = {
  67850. top: [xc, points[idx][1]],
  67851. bottom: [xc, points[1 - idx][1]],
  67852. left: [points[1 - idx][0], yc],
  67853. right: [points[idx][0], yc]
  67854. };
  67855. var name = rangeData.start.y;
  67856. if (+rangeData.end.y > +rangeData.start.y) {
  67857. name = name + '-' + rangeData.end.y;
  67858. }
  67859. var formatter = yearLabel.get('formatter');
  67860. var params = {
  67861. start: rangeData.start.y,
  67862. end: rangeData.end.y,
  67863. nameMap: name
  67864. };
  67865. var content = this._formatterLabel(formatter, params);
  67866. var yearText = new ZRText({
  67867. z2: 30,
  67868. style: createTextStyle(yearLabel, {
  67869. text: content
  67870. })
  67871. });
  67872. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  67873. group.add(yearText);
  67874. };
  67875. CalendarView.prototype._monthTextPositionControl = function (point, isCenter, orient, position, margin) {
  67876. var align = 'left';
  67877. var vAlign = 'top';
  67878. var x = point[0];
  67879. var y = point[1];
  67880. if (orient === 'horizontal') {
  67881. y = y + margin;
  67882. if (isCenter) {
  67883. align = 'center';
  67884. }
  67885. if (position === 'start') {
  67886. vAlign = 'bottom';
  67887. }
  67888. } else {
  67889. x = x + margin;
  67890. if (isCenter) {
  67891. vAlign = 'middle';
  67892. }
  67893. if (position === 'start') {
  67894. align = 'right';
  67895. }
  67896. }
  67897. return {
  67898. x: x,
  67899. y: y,
  67900. align: align,
  67901. verticalAlign: vAlign
  67902. };
  67903. }; // render month and year text
  67904. CalendarView.prototype._renderMonthText = function (calendarModel, localeModel, orient, group) {
  67905. var monthLabel = calendarModel.getModel('monthLabel');
  67906. if (!monthLabel.get('show')) {
  67907. return;
  67908. }
  67909. var nameMap = monthLabel.get('nameMap');
  67910. var margin = monthLabel.get('margin');
  67911. var pos = monthLabel.get('position');
  67912. var align = monthLabel.get('align');
  67913. var termPoints = [this._tlpoints, this._blpoints];
  67914. if (!nameMap || isString(nameMap)) {
  67915. if (nameMap) {
  67916. // case-sensitive
  67917. localeModel = getLocaleModel(nameMap) || localeModel;
  67918. } // PENDING
  67919. // for ZH locale, original form is `一月` but current form is `1月`
  67920. nameMap = localeModel.get(['time', 'monthAbbr']) || [];
  67921. }
  67922. var idx = pos === 'start' ? 0 : 1;
  67923. var axis = orient === 'horizontal' ? 0 : 1;
  67924. margin = pos === 'start' ? -margin : margin;
  67925. var isCenter = align === 'center';
  67926. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  67927. var tmp = termPoints[idx][i].slice();
  67928. var firstDay = this._firstDayOfMonth[i];
  67929. if (isCenter) {
  67930. var firstDayPoints = this._firstDayPoints[i];
  67931. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  67932. }
  67933. var formatter = monthLabel.get('formatter');
  67934. var name_1 = nameMap[+firstDay.m - 1];
  67935. var params = {
  67936. yyyy: firstDay.y,
  67937. yy: (firstDay.y + '').slice(2),
  67938. MM: firstDay.m,
  67939. M: +firstDay.m,
  67940. nameMap: name_1
  67941. };
  67942. var content = this._formatterLabel(formatter, params);
  67943. var monthText = new ZRText({
  67944. z2: 30,
  67945. style: extend(createTextStyle(monthLabel, {
  67946. text: content
  67947. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin))
  67948. });
  67949. group.add(monthText);
  67950. }
  67951. };
  67952. CalendarView.prototype._weekTextPositionControl = function (point, orient, position, margin, cellSize) {
  67953. var align = 'center';
  67954. var vAlign = 'middle';
  67955. var x = point[0];
  67956. var y = point[1];
  67957. var isStart = position === 'start';
  67958. if (orient === 'horizontal') {
  67959. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  67960. align = isStart ? 'right' : 'left';
  67961. } else {
  67962. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  67963. vAlign = isStart ? 'bottom' : 'top';
  67964. }
  67965. return {
  67966. x: x,
  67967. y: y,
  67968. align: align,
  67969. verticalAlign: vAlign
  67970. };
  67971. }; // render weeks
  67972. CalendarView.prototype._renderWeekText = function (calendarModel, localeModel, rangeData, orient, group) {
  67973. var dayLabel = calendarModel.getModel('dayLabel');
  67974. if (!dayLabel.get('show')) {
  67975. return;
  67976. }
  67977. var coordSys = calendarModel.coordinateSystem;
  67978. var pos = dayLabel.get('position');
  67979. var nameMap = dayLabel.get('nameMap');
  67980. var margin = dayLabel.get('margin');
  67981. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  67982. if (!nameMap || isString(nameMap)) {
  67983. if (nameMap) {
  67984. // case-sensitive
  67985. localeModel = getLocaleModel(nameMap) || localeModel;
  67986. } // Use the first letter of `dayOfWeekAbbr` if `dayOfWeekShort` doesn't exist in the locale file
  67987. var dayOfWeekShort = localeModel.get(['time', 'dayOfWeekShort']);
  67988. nameMap = dayOfWeekShort || map(localeModel.get(['time', 'dayOfWeekAbbr']), function (val) {
  67989. return val[0];
  67990. });
  67991. }
  67992. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  67993. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  67994. margin = parsePercent$1(margin, Math.min(cellSize[1], cellSize[0]));
  67995. if (pos === 'start') {
  67996. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  67997. margin = -margin;
  67998. }
  67999. for (var i = 0; i < 7; i++) {
  68000. var tmpD = coordSys.getNextNDay(start, i);
  68001. var point = coordSys.dataToRect([tmpD.time], false).center;
  68002. var day = i;
  68003. day = Math.abs((i + firstDayOfWeek) % 7);
  68004. var weekText = new ZRText({
  68005. z2: 30,
  68006. style: extend(createTextStyle(dayLabel, {
  68007. text: nameMap[day]
  68008. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize))
  68009. });
  68010. group.add(weekText);
  68011. }
  68012. };
  68013. CalendarView.type = 'calendar';
  68014. return CalendarView;
  68015. }(ComponentView);
  68016. var PROXIMATE_ONE_DAY = 86400000;
  68017. var Calendar =
  68018. /** @class */
  68019. function () {
  68020. function Calendar(calendarModel, ecModel, api) {
  68021. this.type = 'calendar';
  68022. this.dimensions = Calendar.dimensions; // Required in createListFromData
  68023. this.getDimensionsInfo = Calendar.getDimensionsInfo;
  68024. this._model = calendarModel;
  68025. }
  68026. Calendar.getDimensionsInfo = function () {
  68027. return [{
  68028. name: 'time',
  68029. type: 'time'
  68030. }, 'value'];
  68031. };
  68032. Calendar.prototype.getRangeInfo = function () {
  68033. return this._rangeInfo;
  68034. };
  68035. Calendar.prototype.getModel = function () {
  68036. return this._model;
  68037. };
  68038. Calendar.prototype.getRect = function () {
  68039. return this._rect;
  68040. };
  68041. Calendar.prototype.getCellWidth = function () {
  68042. return this._sw;
  68043. };
  68044. Calendar.prototype.getCellHeight = function () {
  68045. return this._sh;
  68046. };
  68047. Calendar.prototype.getOrient = function () {
  68048. return this._orient;
  68049. };
  68050. /**
  68051. * getFirstDayOfWeek
  68052. *
  68053. * @example
  68054. * 0 : start at Sunday
  68055. * 1 : start at Monday
  68056. *
  68057. * @return {number}
  68058. */
  68059. Calendar.prototype.getFirstDayOfWeek = function () {
  68060. return this._firstDayOfWeek;
  68061. };
  68062. /**
  68063. * get date info
  68064. * }
  68065. */
  68066. Calendar.prototype.getDateInfo = function (date) {
  68067. date = parseDate(date);
  68068. var y = date.getFullYear();
  68069. var m = date.getMonth() + 1;
  68070. var mStr = m < 10 ? '0' + m : '' + m;
  68071. var d = date.getDate();
  68072. var dStr = d < 10 ? '0' + d : '' + d;
  68073. var day = date.getDay();
  68074. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  68075. return {
  68076. y: y + '',
  68077. m: mStr,
  68078. d: dStr,
  68079. day: day,
  68080. time: date.getTime(),
  68081. formatedDate: y + '-' + mStr + '-' + dStr,
  68082. date: date
  68083. };
  68084. };
  68085. Calendar.prototype.getNextNDay = function (date, n) {
  68086. n = n || 0;
  68087. if (n === 0) {
  68088. return this.getDateInfo(date);
  68089. }
  68090. date = new Date(this.getDateInfo(date).time);
  68091. date.setDate(date.getDate() + n);
  68092. return this.getDateInfo(date);
  68093. };
  68094. Calendar.prototype.update = function (ecModel, api) {
  68095. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  68096. this._orient = this._model.get('orient');
  68097. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  68098. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  68099. var weeks = this._rangeInfo.weeks || 1;
  68100. var whNames = ['width', 'height'];
  68101. var cellSize = this._model.getCellSize().slice();
  68102. var layoutParams = this._model.getBoxLayoutParams();
  68103. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  68104. each([0, 1], function (idx) {
  68105. if (cellSizeSpecified(cellSize, idx)) {
  68106. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  68107. }
  68108. });
  68109. var whGlobal = {
  68110. width: api.getWidth(),
  68111. height: api.getHeight()
  68112. };
  68113. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  68114. each([0, 1], function (idx) {
  68115. if (!cellSizeSpecified(cellSize, idx)) {
  68116. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  68117. }
  68118. });
  68119. function cellSizeSpecified(cellSize, idx) {
  68120. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  68121. } // Has been calculated out number.
  68122. this._sw = cellSize[0];
  68123. this._sh = cellSize[1];
  68124. };
  68125. /**
  68126. * Convert a time data(time, value) item to (x, y) point.
  68127. */
  68128. // TODO Clamp of calendar is not same with cartesian coordinate systems.
  68129. // It will return NaN if data exceeds.
  68130. Calendar.prototype.dataToPoint = function (data, clamp) {
  68131. isArray(data) && (data = data[0]);
  68132. clamp == null && (clamp = true);
  68133. var dayInfo = this.getDateInfo(data);
  68134. var range = this._rangeInfo;
  68135. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  68136. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  68137. return [NaN, NaN];
  68138. }
  68139. var week = dayInfo.day;
  68140. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  68141. if (this._orient === 'vertical') {
  68142. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  68143. }
  68144. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  68145. };
  68146. /**
  68147. * Convert a (x, y) point to time data
  68148. */
  68149. Calendar.prototype.pointToData = function (point) {
  68150. var date = this.pointToDate(point);
  68151. return date && date.time;
  68152. };
  68153. /**
  68154. * Convert a time date item to (x, y) four point.
  68155. */
  68156. Calendar.prototype.dataToRect = function (data, clamp) {
  68157. var point = this.dataToPoint(data, clamp);
  68158. return {
  68159. contentShape: {
  68160. x: point[0] - (this._sw - this._lineWidth) / 2,
  68161. y: point[1] - (this._sh - this._lineWidth) / 2,
  68162. width: this._sw - this._lineWidth,
  68163. height: this._sh - this._lineWidth
  68164. },
  68165. center: point,
  68166. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  68167. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  68168. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  68169. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  68170. };
  68171. };
  68172. /**
  68173. * Convert a (x, y) point to time date
  68174. *
  68175. * @param {Array} point point
  68176. * @return {Object} date
  68177. */
  68178. Calendar.prototype.pointToDate = function (point) {
  68179. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  68180. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  68181. var range = this._rangeInfo.range;
  68182. if (this._orient === 'vertical') {
  68183. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  68184. }
  68185. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  68186. };
  68187. Calendar.prototype.convertToPixel = function (ecModel, finder, value) {
  68188. var coordSys = getCoordSys$4(finder);
  68189. return coordSys === this ? coordSys.dataToPoint(value) : null;
  68190. };
  68191. Calendar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  68192. var coordSys = getCoordSys$4(finder);
  68193. return coordSys === this ? coordSys.pointToData(pixel) : null;
  68194. };
  68195. Calendar.prototype.containPoint = function (point) {
  68196. console.warn('Not implemented.');
  68197. return false;
  68198. };
  68199. /**
  68200. * initRange
  68201. * Normalize to an [start, end] array
  68202. */
  68203. Calendar.prototype._initRangeOption = function () {
  68204. var range = this._model.get('range');
  68205. var normalizedRange; // Convert [1990] to 1990
  68206. if (isArray(range) && range.length === 1) {
  68207. range = range[0];
  68208. }
  68209. if (!isArray(range)) {
  68210. var rangeStr = range.toString(); // One year.
  68211. if (/^\d{4}$/.test(rangeStr)) {
  68212. normalizedRange = [rangeStr + '-01-01', rangeStr + '-12-31'];
  68213. } // One month
  68214. if (/^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68215. var start = this.getDateInfo(rangeStr);
  68216. var firstDay = start.date;
  68217. firstDay.setMonth(firstDay.getMonth() + 1);
  68218. var end = this.getNextNDay(firstDay, -1);
  68219. normalizedRange = [start.formatedDate, end.formatedDate];
  68220. } // One day
  68221. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr)) {
  68222. normalizedRange = [rangeStr, rangeStr];
  68223. }
  68224. } else {
  68225. normalizedRange = range;
  68226. }
  68227. if (!normalizedRange) {
  68228. if ("development" !== 'production') {
  68229. logError('Invalid date range.');
  68230. } // Not handling it.
  68231. return range;
  68232. }
  68233. var tmp = this._getRangeInfo(normalizedRange);
  68234. if (tmp.start.time > tmp.end.time) {
  68235. normalizedRange.reverse();
  68236. }
  68237. return normalizedRange;
  68238. };
  68239. /**
  68240. * range info
  68241. *
  68242. * @private
  68243. * @param {Array} range range ['2017-01-01', '2017-07-08']
  68244. * If range[0] > range[1], they will not be reversed.
  68245. * @return {Object} obj
  68246. */
  68247. Calendar.prototype._getRangeInfo = function (range) {
  68248. var parsedRange = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  68249. var reversed;
  68250. if (parsedRange[0].time > parsedRange[1].time) {
  68251. reversed = true;
  68252. parsedRange.reverse();
  68253. }
  68254. var allDay = Math.floor(parsedRange[1].time / PROXIMATE_ONE_DAY) - Math.floor(parsedRange[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  68255. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  68256. // Consider case2:
  68257. // Firstly set system timezone as "Time Zone: America/Toronto",
  68258. // ```
  68259. // let first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  68260. // let second = new Date(1478412000000);
  68261. // let allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  68262. // ```
  68263. // will get wrong result because of DST. So we should fix it.
  68264. var date = new Date(parsedRange[0].time);
  68265. var startDateNum = date.getDate();
  68266. var endDateNum = parsedRange[1].date.getDate();
  68267. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  68268. var dateNum = date.getDate();
  68269. if (dateNum !== endDateNum) {
  68270. var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1;
  68271. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0) {
  68272. allDay -= sign;
  68273. date.setDate(dateNum - sign);
  68274. }
  68275. }
  68276. var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7);
  68277. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  68278. reversed && parsedRange.reverse();
  68279. return {
  68280. range: [parsedRange[0].formatedDate, parsedRange[1].formatedDate],
  68281. start: parsedRange[0],
  68282. end: parsedRange[1],
  68283. allDay: allDay,
  68284. weeks: weeks,
  68285. // From 0.
  68286. nthWeek: nthWeek,
  68287. fweek: parsedRange[0].day,
  68288. lweek: parsedRange[1].day
  68289. };
  68290. };
  68291. /**
  68292. * get date by nthWeeks and week day in range
  68293. *
  68294. * @private
  68295. * @param {number} nthWeek the week
  68296. * @param {number} day the week day
  68297. * @param {Array} range [d1, d2]
  68298. * @return {Object}
  68299. */
  68300. Calendar.prototype._getDateByWeeksAndDay = function (nthWeek, day, range) {
  68301. var rangeInfo = this._getRangeInfo(range);
  68302. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  68303. return null;
  68304. }
  68305. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  68306. var date = new Date(rangeInfo.start.time);
  68307. date.setDate(+rangeInfo.start.d + nthDay);
  68308. return this.getDateInfo(date);
  68309. };
  68310. Calendar.create = function (ecModel, api) {
  68311. var calendarList = [];
  68312. ecModel.eachComponent('calendar', function (calendarModel) {
  68313. var calendar = new Calendar(calendarModel, ecModel, api);
  68314. calendarList.push(calendar);
  68315. calendarModel.coordinateSystem = calendar;
  68316. });
  68317. ecModel.eachSeries(function (calendarSeries) {
  68318. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  68319. // Inject coordinate system
  68320. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  68321. }
  68322. });
  68323. return calendarList;
  68324. };
  68325. Calendar.dimensions = ['time', 'value'];
  68326. return Calendar;
  68327. }();
  68328. function getCoordSys$4(finder) {
  68329. var calendarModel = finder.calendarModel;
  68330. var seriesModel = finder.seriesModel;
  68331. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  68332. return coordSys;
  68333. }
  68334. function install$w(registers) {
  68335. registers.registerComponentModel(CalendarModel);
  68336. registers.registerComponentView(CalendarView);
  68337. registers.registerCoordinateSystem('calendar', Calendar);
  68338. }
  68339. function setKeyInfoToNewElOption(resultItem, newElOption) {
  68340. var existElOption = resultItem.existing; // Set id and type after id assigned.
  68341. newElOption.id = resultItem.keyInfo.id;
  68342. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  68343. if (newElOption.parentId == null) {
  68344. var newElParentOption = newElOption.parentOption;
  68345. if (newElParentOption) {
  68346. newElOption.parentId = newElParentOption.id;
  68347. } else if (existElOption) {
  68348. newElOption.parentId = existElOption.parentId;
  68349. }
  68350. } // Clear
  68351. newElOption.parentOption = null;
  68352. }
  68353. function isSetLoc(obj, props) {
  68354. var isSet;
  68355. each(props, function (prop) {
  68356. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  68357. });
  68358. return isSet;
  68359. }
  68360. function mergeNewElOptionToExist(existList, index, newElOption) {
  68361. // Update existing options, for `getOption` feature.
  68362. var newElOptCopy = extend({}, newElOption);
  68363. var existElOption = existList[index];
  68364. var $action = newElOption.$action || 'merge';
  68365. if ($action === 'merge') {
  68366. if (existElOption) {
  68367. if ("development" !== 'production') {
  68368. var newType = newElOption.type;
  68369. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  68370. } // We can ensure that newElOptCopy and existElOption are not
  68371. // the same object, so `merge` will not change newElOptCopy.
  68372. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  68373. mergeLayoutParam(existElOption, newElOptCopy, {
  68374. ignoreSize: true
  68375. }); // Will be used in render.
  68376. copyLayoutParams(newElOption, existElOption); // Copy transition info to new option so it can be used in the transition.
  68377. // DO IT AFTER merge
  68378. copyTransitionInfo(newElOption, existElOption);
  68379. copyTransitionInfo(newElOption, existElOption, 'shape');
  68380. copyTransitionInfo(newElOption, existElOption, 'style');
  68381. copyTransitionInfo(newElOption, existElOption, 'extra'); // Copy clipPath
  68382. newElOption.clipPath = existElOption.clipPath;
  68383. } else {
  68384. existList[index] = newElOptCopy;
  68385. }
  68386. } else if ($action === 'replace') {
  68387. existList[index] = newElOptCopy;
  68388. } else if ($action === 'remove') {
  68389. // null will be cleaned later.
  68390. existElOption && (existList[index] = null);
  68391. }
  68392. }
  68393. var TRANSITION_PROPS_TO_COPY = ['transition', 'enterFrom', 'leaveTo'];
  68394. var ROOT_TRANSITION_PROPS_TO_COPY = TRANSITION_PROPS_TO_COPY.concat(['enterAnimation', 'updateAnimation', 'leaveAnimation']);
  68395. function copyTransitionInfo(target, source, targetProp) {
  68396. if (targetProp) {
  68397. if (!target[targetProp] && source[targetProp]) {
  68398. // TODO avoid creating this empty object when there is no transition configuration.
  68399. target[targetProp] = {};
  68400. }
  68401. target = target[targetProp];
  68402. source = source[targetProp];
  68403. }
  68404. if (!target || !source) {
  68405. return;
  68406. }
  68407. var props = targetProp ? TRANSITION_PROPS_TO_COPY : ROOT_TRANSITION_PROPS_TO_COPY;
  68408. for (var i = 0; i < props.length; i++) {
  68409. var prop = props[i];
  68410. if (target[prop] == null && source[prop] != null) {
  68411. target[prop] = source[prop];
  68412. }
  68413. }
  68414. }
  68415. function setLayoutInfoToExist(existItem, newElOption) {
  68416. if (!existItem) {
  68417. return;
  68418. }
  68419. existItem.hv = newElOption.hv = [// Rigid body, don't care about `width`.
  68420. isSetLoc(newElOption, ['left', 'right']), // Rigid body, don't care about `height`.
  68421. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  68422. if (existItem.type === 'group') {
  68423. var existingGroupOpt = existItem;
  68424. var newGroupOpt = newElOption;
  68425. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  68426. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  68427. }
  68428. }
  68429. var GraphicComponentModel =
  68430. /** @class */
  68431. function (_super) {
  68432. __extends(GraphicComponentModel, _super);
  68433. function GraphicComponentModel() {
  68434. var _this = _super !== null && _super.apply(this, arguments) || this;
  68435. _this.type = GraphicComponentModel.type;
  68436. _this.preventAutoZ = true;
  68437. return _this;
  68438. }
  68439. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  68440. // Prevent default merge to elements
  68441. var elements = this.option.elements;
  68442. this.option.elements = null;
  68443. _super.prototype.mergeOption.call(this, option, ecModel);
  68444. this.option.elements = elements;
  68445. };
  68446. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  68447. var thisOption = this.option;
  68448. var newList = (isInit ? thisOption : newOption).elements;
  68449. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  68450. var flattenedList = [];
  68451. this._flatten(newList, flattenedList, null);
  68452. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  68453. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  68454. each(mappingResult, function (resultItem, index) {
  68455. var newElOption = resultItem.newOption;
  68456. if ("development" !== 'production') {
  68457. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  68458. }
  68459. if (!newElOption) {
  68460. return;
  68461. }
  68462. elOptionsToUpdate.push(newElOption);
  68463. setKeyInfoToNewElOption(resultItem, newElOption);
  68464. mergeNewElOptionToExist(existList, index, newElOption);
  68465. setLayoutInfoToExist(existList[index], newElOption);
  68466. }, this); // Clean
  68467. thisOption.elements = filter(existList, function (item) {
  68468. // $action should be volatile, otherwise option gotten from
  68469. // `getOption` will contain unexpected $action.
  68470. item && delete item.$action;
  68471. return item != null;
  68472. });
  68473. };
  68474. /**
  68475. * Convert
  68476. * [{
  68477. * type: 'group',
  68478. * id: 'xx',
  68479. * children: [{type: 'circle'}, {type: 'polygon'}]
  68480. * }]
  68481. * to
  68482. * [
  68483. * {type: 'group', id: 'xx'},
  68484. * {type: 'circle', parentId: 'xx'},
  68485. * {type: 'polygon', parentId: 'xx'}
  68486. * ]
  68487. */
  68488. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  68489. each(optionList, function (option) {
  68490. if (!option) {
  68491. return;
  68492. }
  68493. if (parentOption) {
  68494. option.parentOption = parentOption;
  68495. }
  68496. result.push(option);
  68497. var children = option.children; // here we don't judge if option.type is `group`
  68498. // when new option doesn't provide `type`, it will cause that the children can't be updated.
  68499. if (children && children.length) {
  68500. this._flatten(children, result, option);
  68501. } // Deleting for JSON output, and for not affecting group creation.
  68502. delete option.children;
  68503. }, this);
  68504. }; // FIXME
  68505. // Pass to view using payload? setOption has a payload?
  68506. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  68507. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  68508. this._elOptionsToUpdate = null;
  68509. return els;
  68510. };
  68511. GraphicComponentModel.type = 'graphic';
  68512. GraphicComponentModel.defaultOption = {
  68513. elements: [] // parentId: null
  68514. };
  68515. return GraphicComponentModel;
  68516. }(ComponentModel);
  68517. var nonShapeGraphicElements = {
  68518. // Reserved but not supported in graphic component.
  68519. path: null,
  68520. compoundPath: null,
  68521. // Supported in graphic component.
  68522. group: Group,
  68523. image: ZRImage,
  68524. text: ZRText
  68525. };
  68526. var inner$e = makeInner(); // ------------------------
  68527. // View
  68528. // ------------------------
  68529. var GraphicComponentView =
  68530. /** @class */
  68531. function (_super) {
  68532. __extends(GraphicComponentView, _super);
  68533. function GraphicComponentView() {
  68534. var _this = _super !== null && _super.apply(this, arguments) || this;
  68535. _this.type = GraphicComponentView.type;
  68536. return _this;
  68537. }
  68538. GraphicComponentView.prototype.init = function () {
  68539. this._elMap = createHashMap();
  68540. };
  68541. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  68542. // Having leveraged between use cases and algorithm complexity, a very
  68543. // simple layout mechanism is used:
  68544. // The size(width/height) can be determined by itself or its parent (not
  68545. // implemented yet), but can not by its children. (Top-down travel)
  68546. // The location(x/y) can be determined by the bounding rect of itself
  68547. // (can including its descendants or not) and the size of its parent.
  68548. // (Bottom-up travel)
  68549. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  68550. // view will be reused.
  68551. if (graphicModel !== this._lastGraphicModel) {
  68552. this._clear();
  68553. }
  68554. this._lastGraphicModel = graphicModel;
  68555. this._updateElements(graphicModel);
  68556. this._relocate(graphicModel, api);
  68557. };
  68558. /**
  68559. * Update graphic elements.
  68560. */
  68561. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  68562. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  68563. if (!elOptionsToUpdate) {
  68564. return;
  68565. }
  68566. var elMap = this._elMap;
  68567. var rootGroup = this.group;
  68568. var globalZ = graphicModel.get('z');
  68569. var globalZLevel = graphicModel.get('zlevel'); // Top-down tranverse to assign graphic settings to each elements.
  68570. each(elOptionsToUpdate, function (elOption) {
  68571. var id = convertOptionIdName(elOption.id, null);
  68572. var elExisting = id != null ? elMap.get(id) : null;
  68573. var parentId = convertOptionIdName(elOption.parentId, null);
  68574. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  68575. var elType = elOption.type;
  68576. var elOptionStyle = elOption.style;
  68577. if (elType === 'text' && elOptionStyle) {
  68578. // In top/bottom mode, textVerticalAlign should not be used, which cause
  68579. // inaccurately locating.
  68580. if (elOption.hv && elOption.hv[1]) {
  68581. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  68582. }
  68583. }
  68584. var textContentOption = elOption.textContent;
  68585. var textConfig = elOption.textConfig;
  68586. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  68587. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  68588. if (!textConfig && convertResult.textConfig) {
  68589. textConfig = elOption.textConfig = convertResult.textConfig;
  68590. }
  68591. if (!textContentOption && convertResult.textContent) {
  68592. textContentOption = convertResult.textContent;
  68593. }
  68594. } // Remove unnecessary props to avoid potential problems.
  68595. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  68596. if ("development" !== 'production') {
  68597. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  68598. }
  68599. var $action = elOption.$action || 'merge';
  68600. var isMerge = $action === 'merge';
  68601. var isReplace = $action === 'replace';
  68602. if (isMerge) {
  68603. var isInit = !elExisting;
  68604. var el_1 = elExisting;
  68605. if (isInit) {
  68606. el_1 = createEl$1(id, targetElParent, elOption.type, elMap);
  68607. } else {
  68608. el_1 && (inner$e(el_1).isNew = false); // Stop and restore before update any other attributes.
  68609. stopPreviousKeyframeAnimationAndRestore(el_1);
  68610. }
  68611. if (el_1) {
  68612. applyUpdateTransition(el_1, elOptionCleaned, graphicModel, {
  68613. isInit: isInit
  68614. });
  68615. updateCommonAttrs(el_1, elOption, globalZ, globalZLevel);
  68616. }
  68617. } else if (isReplace) {
  68618. removeEl(elExisting, elOption, elMap, graphicModel);
  68619. var el_2 = createEl$1(id, targetElParent, elOption.type, elMap);
  68620. if (el_2) {
  68621. applyUpdateTransition(el_2, elOptionCleaned, graphicModel, {
  68622. isInit: true
  68623. });
  68624. updateCommonAttrs(el_2, elOption, globalZ, globalZLevel);
  68625. }
  68626. } else if ($action === 'remove') {
  68627. updateLeaveTo(elExisting, elOption);
  68628. removeEl(elExisting, elOption, elMap, graphicModel);
  68629. }
  68630. var el = elMap.get(id);
  68631. if (el && textContentOption) {
  68632. if (isMerge) {
  68633. var textContentExisting = el.getTextContent();
  68634. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  68635. } else if (isReplace) {
  68636. el.setTextContent(new ZRText(textContentOption));
  68637. }
  68638. }
  68639. if (el) {
  68640. var clipPathOption = elOption.clipPath;
  68641. if (clipPathOption) {
  68642. var clipPathType = clipPathOption.type;
  68643. var clipPath = void 0;
  68644. var isInit = false;
  68645. if (isMerge) {
  68646. var oldClipPath = el.getClipPath();
  68647. isInit = !oldClipPath || inner$e(oldClipPath).type !== clipPathType;
  68648. clipPath = isInit ? newEl(clipPathType) : oldClipPath;
  68649. } else if (isReplace) {
  68650. isInit = true;
  68651. clipPath = newEl(clipPathType);
  68652. }
  68653. el.setClipPath(clipPath);
  68654. applyUpdateTransition(clipPath, clipPathOption, graphicModel, {
  68655. isInit: isInit
  68656. });
  68657. applyKeyframeAnimation(clipPath, clipPathOption.keyframeAnimation, graphicModel);
  68658. }
  68659. var elInner = inner$e(el);
  68660. el.setTextConfig(textConfig);
  68661. elInner.option = elOption;
  68662. setEventData(el, graphicModel, elOption);
  68663. setTooltipConfig({
  68664. el: el,
  68665. componentModel: graphicModel,
  68666. itemName: el.name,
  68667. itemTooltipOption: elOption.tooltip
  68668. });
  68669. applyKeyframeAnimation(el, elOption.keyframeAnimation, graphicModel);
  68670. }
  68671. });
  68672. };
  68673. /**
  68674. * Locate graphic elements.
  68675. */
  68676. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  68677. var elOptions = graphicModel.option.elements;
  68678. var rootGroup = this.group;
  68679. var elMap = this._elMap;
  68680. var apiWidth = api.getWidth();
  68681. var apiHeight = api.getHeight();
  68682. var xy = ['x', 'y']; // Top-down to calculate percentage width/height of group
  68683. for (var i = 0; i < elOptions.length; i++) {
  68684. var elOption = elOptions[i];
  68685. var id = convertOptionIdName(elOption.id, null);
  68686. var el = id != null ? elMap.get(id) : null;
  68687. if (!el || !el.isGroup) {
  68688. continue;
  68689. }
  68690. var parentEl = el.parent;
  68691. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  68692. var elInner = inner$e(el);
  68693. var parentElInner = inner$e(parentEl);
  68694. elInner.width = parsePercent$1(elInner.option.width, isParentRoot ? apiWidth : parentElInner.width) || 0;
  68695. elInner.height = parsePercent$1(elInner.option.height, isParentRoot ? apiHeight : parentElInner.height) || 0;
  68696. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  68697. for (var i = elOptions.length - 1; i >= 0; i--) {
  68698. var elOption = elOptions[i];
  68699. var id = convertOptionIdName(elOption.id, null);
  68700. var el = id != null ? elMap.get(id) : null;
  68701. if (!el) {
  68702. continue;
  68703. }
  68704. var parentEl = el.parent;
  68705. var parentElInner = inner$e(parentEl);
  68706. var containerInfo = parentEl === rootGroup ? {
  68707. width: apiWidth,
  68708. height: apiHeight
  68709. } : {
  68710. width: parentElInner.width,
  68711. height: parentElInner.height
  68712. }; // PENDING
  68713. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  68714. // does not include the rect of [0, 0, group.width, group.height], which
  68715. // is probably weird for users. Should we make a break change for it?
  68716. var layoutPos = {};
  68717. var layouted = positionElement(el, elOption, containerInfo, null, {
  68718. hv: elOption.hv,
  68719. boundingMode: elOption.bounding
  68720. }, layoutPos);
  68721. if (!inner$e(el).isNew && layouted) {
  68722. var transition = elOption.transition;
  68723. var animatePos = {};
  68724. for (var k = 0; k < xy.length; k++) {
  68725. var key = xy[k];
  68726. var val = layoutPos[key];
  68727. if (transition && (isTransitionAll(transition) || indexOf(transition, key) >= 0)) {
  68728. animatePos[key] = val;
  68729. } else {
  68730. el[key] = val;
  68731. }
  68732. }
  68733. updateProps(el, animatePos, graphicModel, 0);
  68734. } else {
  68735. el.attr(layoutPos);
  68736. }
  68737. }
  68738. };
  68739. /**
  68740. * Clear all elements.
  68741. */
  68742. GraphicComponentView.prototype._clear = function () {
  68743. var _this = this;
  68744. var elMap = this._elMap;
  68745. elMap.each(function (el) {
  68746. removeEl(el, inner$e(el).option, elMap, _this._lastGraphicModel);
  68747. });
  68748. this._elMap = createHashMap();
  68749. };
  68750. GraphicComponentView.prototype.dispose = function () {
  68751. this._clear();
  68752. };
  68753. GraphicComponentView.type = 'graphic';
  68754. return GraphicComponentView;
  68755. }(ComponentView);
  68756. function newEl(graphicType) {
  68757. if ("development" !== 'production') {
  68758. assert(graphicType, 'graphic type MUST be set');
  68759. }
  68760. var Clz = hasOwn(nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  68761. // overwritten by users, so do them first.
  68762. ? nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  68763. if ("development" !== 'production') {
  68764. assert(Clz, "graphic type " + graphicType + " can not be found");
  68765. }
  68766. var el = new Clz({});
  68767. inner$e(el).type = graphicType;
  68768. return el;
  68769. }
  68770. function createEl$1(id, targetElParent, graphicType, elMap) {
  68771. var el = newEl(graphicType);
  68772. targetElParent.add(el);
  68773. elMap.set(id, el);
  68774. inner$e(el).id = id;
  68775. inner$e(el).isNew = true;
  68776. return el;
  68777. }
  68778. function removeEl(elExisting, elOption, elMap, graphicModel) {
  68779. var existElParent = elExisting && elExisting.parent;
  68780. if (existElParent) {
  68781. elExisting.type === 'group' && elExisting.traverse(function (el) {
  68782. removeEl(el, elOption, elMap, graphicModel);
  68783. });
  68784. applyLeaveTransition(elExisting, elOption, graphicModel);
  68785. elMap.removeKey(inner$e(elExisting).id);
  68786. }
  68787. }
  68788. function updateCommonAttrs(el, elOption, defaultZ, defaultZlevel) {
  68789. if (!el.isGroup) {
  68790. each([['cursor', Displayable.prototype.cursor], // We should not support configure z and zlevel in the element level.
  68791. // But seems we didn't limit it previously. So here still use it to avoid breaking.
  68792. ['zlevel', defaultZlevel || 0], ['z', defaultZ || 0], // z2 must not be null/undefined, otherwise sort error may occur.
  68793. ['z2', 0]], function (item) {
  68794. var prop = item[0];
  68795. if (hasOwn(elOption, prop)) {
  68796. el[prop] = retrieve2(elOption[prop], item[1]);
  68797. } else if (el[prop] == null) {
  68798. el[prop] = item[1];
  68799. }
  68800. });
  68801. }
  68802. each(keys(elOption), function (key) {
  68803. // Assign event handlers.
  68804. // PENDING: should enumerate all event names or use pattern matching?
  68805. if (key.indexOf('on') === 0) {
  68806. var val = elOption[key];
  68807. el[key] = isFunction(val) ? val : null;
  68808. }
  68809. });
  68810. if (hasOwn(elOption, 'draggable')) {
  68811. el.draggable = elOption.draggable;
  68812. } // Other attributes
  68813. elOption.name != null && (el.name = elOption.name);
  68814. elOption.id != null && (el.id = elOption.id);
  68815. } // Remove unnecessary props to avoid potential problems.
  68816. function getCleanedElOption(elOption) {
  68817. elOption = extend({}, elOption);
  68818. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent', 'clipPath'].concat(LOCATION_PARAMS), function (name) {
  68819. delete elOption[name];
  68820. });
  68821. return elOption;
  68822. }
  68823. function setEventData(el, graphicModel, elOption) {
  68824. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  68825. if (!el.silent && !el.ignore && !eventData) {
  68826. eventData = getECData(el).eventData = {
  68827. componentType: 'graphic',
  68828. componentIndex: graphicModel.componentIndex,
  68829. name: el.name
  68830. };
  68831. } // `elOption.info` enables user to mount some info on
  68832. // elements and use them in event handlers.
  68833. if (eventData) {
  68834. eventData.info = elOption.info;
  68835. }
  68836. }
  68837. function install$x(registers) {
  68838. registers.registerComponentModel(GraphicComponentModel);
  68839. registers.registerComponentView(GraphicComponentView);
  68840. registers.registerPreprocessor(function (option) {
  68841. var graphicOption = option.graphic; // Convert
  68842. // {graphic: [{left: 10, type: 'circle'}, ...]}
  68843. // or
  68844. // {graphic: {left: 10, type: 'circle'}}
  68845. // to
  68846. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  68847. if (isArray(graphicOption)) {
  68848. if (!graphicOption[0] || !graphicOption[0].elements) {
  68849. option.graphic = [{
  68850. elements: graphicOption
  68851. }];
  68852. } else {
  68853. // Only one graphic instance can be instantiated. (We don't
  68854. // want that too many views are created in echarts._viewMap.)
  68855. option.graphic = [option.graphic[0]];
  68856. }
  68857. } else if (graphicOption && !graphicOption.elements) {
  68858. option.graphic = [{
  68859. elements: [graphicOption]
  68860. }];
  68861. }
  68862. });
  68863. }
  68864. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  68865. // FIXME: polar has been broken (but rarely used).
  68866. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  68867. function isCoordSupported(seriesModel) {
  68868. var coordType = seriesModel.get('coordinateSystem');
  68869. return indexOf(SERIES_COORDS, coordType) >= 0;
  68870. }
  68871. function getAxisMainType(axisDim) {
  68872. if ("development" !== 'production') {
  68873. assert(axisDim);
  68874. }
  68875. return axisDim + 'Axis';
  68876. }
  68877. /**
  68878. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  68879. * This function finds all linked dataZoomModels start from the given payload.
  68880. */
  68881. function findEffectedDataZooms(ecModel, payload) {
  68882. // Key: `DataZoomAxisDimension`
  68883. var axisRecords = createHashMap();
  68884. var effectedModels = []; // Key: uid of dataZoomModel
  68885. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  68886. ecModel.eachComponent({
  68887. mainType: 'dataZoom',
  68888. query: payload
  68889. }, function (dataZoomModel) {
  68890. if (!effectedModelMap.get(dataZoomModel.uid)) {
  68891. addToEffected(dataZoomModel);
  68892. }
  68893. }); // Start from the given dataZoomModels, travel the graph to find
  68894. // all of the linked dataZoom models.
  68895. var foundNewLink;
  68896. do {
  68897. foundNewLink = false;
  68898. ecModel.eachComponent('dataZoom', processSingle);
  68899. } while (foundNewLink);
  68900. function processSingle(dataZoomModel) {
  68901. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  68902. addToEffected(dataZoomModel);
  68903. foundNewLink = true;
  68904. }
  68905. }
  68906. function addToEffected(dataZoom) {
  68907. effectedModelMap.set(dataZoom.uid, true);
  68908. effectedModels.push(dataZoom);
  68909. markAxisControlled(dataZoom);
  68910. }
  68911. function isLinked(dataZoomModel) {
  68912. var isLink = false;
  68913. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68914. var axisIdxArr = axisRecords.get(axisDim);
  68915. if (axisIdxArr && axisIdxArr[axisIndex]) {
  68916. isLink = true;
  68917. }
  68918. });
  68919. return isLink;
  68920. }
  68921. function markAxisControlled(dataZoomModel) {
  68922. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68923. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  68924. });
  68925. }
  68926. return effectedModels;
  68927. }
  68928. /**
  68929. * Find the first target coordinate system.
  68930. * Available after model built.
  68931. *
  68932. * @return Like {
  68933. * grid: [
  68934. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  68935. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  68936. * ...
  68937. * ], // cartesians must not be null/undefined.
  68938. * polar: [
  68939. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  68940. * ...
  68941. * ], // polars must not be null/undefined.
  68942. * singleAxis: [
  68943. * {model: coord0, axisModels: [], coordIndex: 0}
  68944. * ]
  68945. * }
  68946. */
  68947. function collectReferCoordSysModelInfo(dataZoomModel) {
  68948. var ecModel = dataZoomModel.ecModel;
  68949. var coordSysInfoWrap = {
  68950. infoList: [],
  68951. infoMap: createHashMap()
  68952. };
  68953. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  68954. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  68955. if (!axisModel) {
  68956. return;
  68957. }
  68958. var coordSysModel = axisModel.getCoordSysModel();
  68959. if (!coordSysModel) {
  68960. return;
  68961. }
  68962. var coordSysUid = coordSysModel.uid;
  68963. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  68964. if (!coordSysInfo) {
  68965. coordSysInfo = {
  68966. model: coordSysModel,
  68967. axisModels: []
  68968. };
  68969. coordSysInfoWrap.infoList.push(coordSysInfo);
  68970. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  68971. }
  68972. coordSysInfo.axisModels.push(axisModel);
  68973. });
  68974. return coordSysInfoWrap;
  68975. }
  68976. var DataZoomAxisInfo =
  68977. /** @class */
  68978. function () {
  68979. function DataZoomAxisInfo() {
  68980. this.indexList = [];
  68981. this.indexMap = [];
  68982. }
  68983. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  68984. // Remove duplication.
  68985. if (!this.indexMap[axisCmptIdx]) {
  68986. this.indexList.push(axisCmptIdx);
  68987. this.indexMap[axisCmptIdx] = true;
  68988. }
  68989. };
  68990. return DataZoomAxisInfo;
  68991. }();
  68992. var DataZoomModel =
  68993. /** @class */
  68994. function (_super) {
  68995. __extends(DataZoomModel, _super);
  68996. function DataZoomModel() {
  68997. var _this = _super !== null && _super.apply(this, arguments) || this;
  68998. _this.type = DataZoomModel.type;
  68999. _this._autoThrottle = true;
  69000. _this._noTarget = true;
  69001. /**
  69002. * It is `[rangeModeForMin, rangeModeForMax]`.
  69003. * The optional values for `rangeMode`:
  69004. * + `'value'` mode: the axis extent will always be determined by
  69005. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  69006. * how data like and how `axis.min` and `axis.max` are.
  69007. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  69008. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  69009. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  69010. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  69011. *
  69012. * For example, when users are using dynamic data (update data periodically via `setOption`),
  69013. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  69014. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  69015. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  69016. */
  69017. _this._rangePropMode = ['percent', 'percent'];
  69018. return _this;
  69019. }
  69020. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  69021. var inputRawOption = retrieveRawOption(option);
  69022. /**
  69023. * Suppose a "main process" start at the point that model prepared (that is,
  69024. * model initialized or merged or method called in `action`).
  69025. * We should keep the `main process` idempotent, that is, given a set of values
  69026. * on `option`, we get the same result.
  69027. *
  69028. * But sometimes, values on `option` will be updated for providing users
  69029. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  69030. * should not be the base/input of the `main process`.
  69031. *
  69032. * So in that case we should save and keep the input of the `main process`
  69033. * separately, called `settledOption`.
  69034. *
  69035. * For example, consider the case:
  69036. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  69037. * where the original input `option.startValue`, `option.endValue` are earsed by
  69038. * calculated value.
  69039. * (Step)2) click the legend to hide and show a series,
  69040. * where the new range is calculated by the earsed `startValue` and `endValue`,
  69041. * which brings incorrect result.
  69042. */
  69043. this.settledOption = inputRawOption;
  69044. this.mergeDefaultAndTheme(option, ecModel);
  69045. this._doInit(inputRawOption);
  69046. };
  69047. DataZoomModel.prototype.mergeOption = function (newOption) {
  69048. var inputRawOption = retrieveRawOption(newOption); // FIX #2591
  69049. merge(this.option, newOption, true);
  69050. merge(this.settledOption, inputRawOption, true);
  69051. this._doInit(inputRawOption);
  69052. };
  69053. DataZoomModel.prototype._doInit = function (inputRawOption) {
  69054. var thisOption = this.option;
  69055. this._setDefaultThrottle(inputRawOption);
  69056. this._updateRangeUse(inputRawOption);
  69057. var settledOption = this.settledOption;
  69058. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69059. // start/end has higher priority over startValue/endValue if they
  69060. // both set, but we should make chart.setOption({endValue: 1000})
  69061. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  69062. if (this._rangePropMode[index] === 'value') {
  69063. thisOption[names[0]] = settledOption[names[0]] = null;
  69064. } // Otherwise do nothing and use the merge result.
  69065. }, this);
  69066. this._resetTarget();
  69067. };
  69068. DataZoomModel.prototype._resetTarget = function () {
  69069. var optionOrient = this.get('orient', true);
  69070. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  69071. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  69072. if (hasAxisSpecified) {
  69073. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  69074. } else {
  69075. this._orient = optionOrient || 'horizontal';
  69076. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  69077. }
  69078. this._noTarget = true;
  69079. targetAxisIndexMap.each(function (axisInfo) {
  69080. if (axisInfo.indexList.length) {
  69081. this._noTarget = false;
  69082. }
  69083. }, this);
  69084. };
  69085. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  69086. var hasAxisSpecified = false;
  69087. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  69088. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  69089. // but do not want use auto mode. Because empty array may be encountered when
  69090. // some error occurred.
  69091. if (!refering.specified) {
  69092. return;
  69093. }
  69094. hasAxisSpecified = true;
  69095. var axisInfo = new DataZoomAxisInfo();
  69096. each(refering.models, function (axisModel) {
  69097. axisInfo.add(axisModel.componentIndex);
  69098. });
  69099. targetAxisIndexMap.set(axisDim, axisInfo);
  69100. }, this);
  69101. return hasAxisSpecified;
  69102. };
  69103. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  69104. var ecModel = this.ecModel;
  69105. var needAuto = true; // Find axis that parallel to dataZoom as default.
  69106. if (needAuto) {
  69107. var axisDim = orient === 'vertical' ? 'y' : 'x';
  69108. var axisModels = ecModel.findComponents({
  69109. mainType: axisDim + 'Axis'
  69110. });
  69111. setParallelAxis(axisModels, axisDim);
  69112. } // Find axis that parallel to dataZoom as default.
  69113. if (needAuto) {
  69114. var axisModels = ecModel.findComponents({
  69115. mainType: 'singleAxis',
  69116. filter: function (axisModel) {
  69117. return axisModel.get('orient', true) === orient;
  69118. }
  69119. });
  69120. setParallelAxis(axisModels, 'single');
  69121. }
  69122. function setParallelAxis(axisModels, axisDim) {
  69123. // At least use the first parallel axis as the target axis.
  69124. var axisModel = axisModels[0];
  69125. if (!axisModel) {
  69126. return;
  69127. }
  69128. var axisInfo = new DataZoomAxisInfo();
  69129. axisInfo.add(axisModel.componentIndex);
  69130. targetAxisIndexMap.set(axisDim, axisInfo);
  69131. needAuto = false; // Find parallel axes in the same grid.
  69132. if (axisDim === 'x' || axisDim === 'y') {
  69133. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  69134. gridModel_1 && each(axisModels, function (axModel) {
  69135. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  69136. axisInfo.add(axModel.componentIndex);
  69137. }
  69138. });
  69139. }
  69140. }
  69141. if (needAuto) {
  69142. // If no parallel axis, find the first category axis as default. (Also consider polar).
  69143. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  69144. if (!needAuto) {
  69145. return;
  69146. }
  69147. var axisModels = ecModel.findComponents({
  69148. mainType: getAxisMainType(axisDim),
  69149. filter: function (axisModel) {
  69150. return axisModel.get('type', true) === 'category';
  69151. }
  69152. });
  69153. if (axisModels[0]) {
  69154. var axisInfo = new DataZoomAxisInfo();
  69155. axisInfo.add(axisModels[0].componentIndex);
  69156. targetAxisIndexMap.set(axisDim, axisInfo);
  69157. needAuto = false;
  69158. }
  69159. }, this);
  69160. }
  69161. };
  69162. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  69163. var dim; // Find the first axis
  69164. this.eachTargetAxis(function (axisDim) {
  69165. !dim && (dim = axisDim);
  69166. }, this);
  69167. return dim === 'y' ? 'vertical' : 'horizontal';
  69168. };
  69169. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  69170. // When first time user set throttle, auto throttle ends.
  69171. if (inputRawOption.hasOwnProperty('throttle')) {
  69172. this._autoThrottle = false;
  69173. }
  69174. if (this._autoThrottle) {
  69175. var globalOption = this.ecModel.option;
  69176. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  69177. }
  69178. };
  69179. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  69180. var rangePropMode = this._rangePropMode;
  69181. var rangeModeInOption = this.get('rangeMode');
  69182. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  69183. var percentSpecified = inputRawOption[names[0]] != null;
  69184. var valueSpecified = inputRawOption[names[1]] != null;
  69185. if (percentSpecified && !valueSpecified) {
  69186. rangePropMode[index] = 'percent';
  69187. } else if (!percentSpecified && valueSpecified) {
  69188. rangePropMode[index] = 'value';
  69189. } else if (rangeModeInOption) {
  69190. rangePropMode[index] = rangeModeInOption[index];
  69191. } else if (percentSpecified) {
  69192. // percentSpecified && valueSpecified
  69193. rangePropMode[index] = 'percent';
  69194. } // else remain its original setting.
  69195. });
  69196. };
  69197. DataZoomModel.prototype.noTarget = function () {
  69198. return this._noTarget;
  69199. };
  69200. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  69201. var firstAxisModel;
  69202. this.eachTargetAxis(function (axisDim, axisIndex) {
  69203. if (firstAxisModel == null) {
  69204. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69205. }
  69206. }, this);
  69207. return firstAxisModel;
  69208. };
  69209. /**
  69210. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  69211. */
  69212. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  69213. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  69214. each(axisInfo.indexList, function (axisIndex) {
  69215. callback.call(context, axisDim, axisIndex);
  69216. });
  69217. });
  69218. };
  69219. /**
  69220. * @return If not found, return null/undefined.
  69221. */
  69222. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  69223. var axisModel = this.getAxisModel(axisDim, axisIndex);
  69224. if (axisModel) {
  69225. return axisModel.__dzAxisProxy;
  69226. }
  69227. };
  69228. /**
  69229. * @return If not found, return null/undefined.
  69230. */
  69231. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  69232. if ("development" !== 'production') {
  69233. assert(axisDim && axisIndex != null);
  69234. }
  69235. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69236. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  69237. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69238. }
  69239. };
  69240. /**
  69241. * If not specified, set to undefined.
  69242. */
  69243. DataZoomModel.prototype.setRawRange = function (opt) {
  69244. var thisOption = this.option;
  69245. var settledOption = this.settledOption;
  69246. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  69247. // Consider the pair <start, startValue>:
  69248. // If one has value and the other one is `null/undefined`, we both set them
  69249. // to `settledOption`. This strategy enables the feature to clear the original
  69250. // value in `settledOption` to `null/undefined`.
  69251. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  69252. // and keep `settledOption` with the original value. This strategy enables users to
  69253. // only set <end or endValue> but not set <start or startValue> when calling
  69254. // `dispatchAction`.
  69255. // The pair <end, endValue> is treated in the same way.
  69256. if (opt[names[0]] != null || opt[names[1]] != null) {
  69257. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  69258. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  69259. }
  69260. }, this);
  69261. this._updateRangeUse(opt);
  69262. };
  69263. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  69264. var option = this.option;
  69265. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  69266. option[name] = opt[name];
  69267. });
  69268. };
  69269. DataZoomModel.prototype.getPercentRange = function () {
  69270. var axisProxy = this.findRepresentativeAxisProxy();
  69271. if (axisProxy) {
  69272. return axisProxy.getDataPercentWindow();
  69273. }
  69274. };
  69275. /**
  69276. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  69277. *
  69278. * @return [startValue, endValue] value can only be '-' or finite number.
  69279. */
  69280. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  69281. if (axisDim == null && axisIndex == null) {
  69282. var axisProxy = this.findRepresentativeAxisProxy();
  69283. if (axisProxy) {
  69284. return axisProxy.getDataValueWindow();
  69285. }
  69286. } else {
  69287. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  69288. }
  69289. };
  69290. /**
  69291. * @param axisModel If axisModel given, find axisProxy
  69292. * corresponding to the axisModel
  69293. */
  69294. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  69295. if (axisModel) {
  69296. return axisModel.__dzAxisProxy;
  69297. } // Find the first hosted axisProxy
  69298. var firstProxy;
  69299. var axisDimList = this._targetAxisInfoMap.keys();
  69300. for (var i = 0; i < axisDimList.length; i++) {
  69301. var axisDim = axisDimList[i];
  69302. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  69303. for (var j = 0; j < axisInfo.indexList.length; j++) {
  69304. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  69305. if (proxy.hostedBy(this)) {
  69306. return proxy;
  69307. }
  69308. if (!firstProxy) {
  69309. firstProxy = proxy;
  69310. }
  69311. }
  69312. } // If no hosted proxy found, still need to return a proxy.
  69313. // This case always happens in toolbox dataZoom, where axes are all hosted by
  69314. // other dataZooms.
  69315. return firstProxy;
  69316. };
  69317. DataZoomModel.prototype.getRangePropMode = function () {
  69318. return this._rangePropMode.slice();
  69319. };
  69320. DataZoomModel.prototype.getOrient = function () {
  69321. if ("development" !== 'production') {
  69322. // Should not be called before initialized.
  69323. assert(this._orient);
  69324. }
  69325. return this._orient;
  69326. };
  69327. DataZoomModel.type = 'dataZoom';
  69328. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  69329. DataZoomModel.defaultOption = {
  69330. // zlevel: 0,
  69331. z: 4,
  69332. filterMode: 'filter',
  69333. start: 0,
  69334. end: 100
  69335. };
  69336. return DataZoomModel;
  69337. }(ComponentModel);
  69338. /**
  69339. * Retrieve those raw params from option, which will be cached separately,
  69340. * because they will be overwritten by normalized/calculated values in the main
  69341. * process.
  69342. */
  69343. function retrieveRawOption(option) {
  69344. var ret = {};
  69345. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  69346. option.hasOwnProperty(name) && (ret[name] = option[name]);
  69347. });
  69348. return ret;
  69349. }
  69350. var SelectDataZoomModel =
  69351. /** @class */
  69352. function (_super) {
  69353. __extends(SelectDataZoomModel, _super);
  69354. function SelectDataZoomModel() {
  69355. var _this = _super !== null && _super.apply(this, arguments) || this;
  69356. _this.type = SelectDataZoomModel.type;
  69357. return _this;
  69358. }
  69359. SelectDataZoomModel.type = 'dataZoom.select';
  69360. return SelectDataZoomModel;
  69361. }(DataZoomModel);
  69362. var DataZoomView =
  69363. /** @class */
  69364. function (_super) {
  69365. __extends(DataZoomView, _super);
  69366. function DataZoomView() {
  69367. var _this = _super !== null && _super.apply(this, arguments) || this;
  69368. _this.type = DataZoomView.type;
  69369. return _this;
  69370. }
  69371. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  69372. this.dataZoomModel = dataZoomModel;
  69373. this.ecModel = ecModel;
  69374. this.api = api;
  69375. };
  69376. DataZoomView.type = 'dataZoom';
  69377. return DataZoomView;
  69378. }(ComponentView);
  69379. var SelectDataZoomView =
  69380. /** @class */
  69381. function (_super) {
  69382. __extends(SelectDataZoomView, _super);
  69383. function SelectDataZoomView() {
  69384. var _this = _super !== null && _super.apply(this, arguments) || this;
  69385. _this.type = SelectDataZoomView.type;
  69386. return _this;
  69387. }
  69388. SelectDataZoomView.type = 'dataZoom.select';
  69389. return SelectDataZoomView;
  69390. }(DataZoomView);
  69391. var each$8 = each;
  69392. var asc$1 = asc;
  69393. /**
  69394. * Operate single axis.
  69395. * One axis can only operated by one axis operator.
  69396. * Different dataZoomModels may be defined to operate the same axis.
  69397. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  69398. * So dataZoomModels share one axisProxy in that case.
  69399. */
  69400. var AxisProxy =
  69401. /** @class */
  69402. function () {
  69403. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  69404. this._dimName = dimName;
  69405. this._axisIndex = axisIndex;
  69406. this.ecModel = ecModel;
  69407. this._dataZoomModel = dataZoomModel; // /**
  69408. // * @readOnly
  69409. // * @private
  69410. // */
  69411. // this.hasSeriesStacked;
  69412. }
  69413. /**
  69414. * Whether the axisProxy is hosted by dataZoomModel.
  69415. */
  69416. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  69417. return this._dataZoomModel === dataZoomModel;
  69418. };
  69419. /**
  69420. * @return Value can only be NaN or finite value.
  69421. */
  69422. AxisProxy.prototype.getDataValueWindow = function () {
  69423. return this._valueWindow.slice();
  69424. };
  69425. /**
  69426. * @return {Array.<number>}
  69427. */
  69428. AxisProxy.prototype.getDataPercentWindow = function () {
  69429. return this._percentWindow.slice();
  69430. };
  69431. AxisProxy.prototype.getTargetSeriesModels = function () {
  69432. var seriesModels = [];
  69433. this.ecModel.eachSeries(function (seriesModel) {
  69434. if (isCoordSupported(seriesModel)) {
  69435. var axisMainType = getAxisMainType(this._dimName);
  69436. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  69437. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  69438. seriesModels.push(seriesModel);
  69439. }
  69440. }
  69441. }, this);
  69442. return seriesModels;
  69443. };
  69444. AxisProxy.prototype.getAxisModel = function () {
  69445. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  69446. };
  69447. AxisProxy.prototype.getMinMaxSpan = function () {
  69448. return clone(this._minMaxSpan);
  69449. };
  69450. /**
  69451. * Only calculate by given range and this._dataExtent, do not change anything.
  69452. */
  69453. AxisProxy.prototype.calculateDataWindow = function (opt) {
  69454. var dataExtent = this._dataExtent;
  69455. var axisModel = this.getAxisModel();
  69456. var scale = axisModel.axis.scale;
  69457. var rangePropMode = this._dataZoomModel.getRangePropMode();
  69458. var percentExtent = [0, 100];
  69459. var percentWindow = [];
  69460. var valueWindow = [];
  69461. var hasPropModeValue;
  69462. each$8(['start', 'end'], function (prop, idx) {
  69463. var boundPercent = opt[prop];
  69464. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  69465. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  69466. // but not min/max of axis, which will be calculated by data window then).
  69467. // The former one is suitable for cases that a dataZoom component controls multiple
  69468. // axes with different unit or extent, and the latter one is suitable for accurate
  69469. // zoom by pixel (e.g., in dataZoomSelect).
  69470. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  69471. // only when setOption or dispatchAction, otherwise it remains its original value.
  69472. // (Why not only record `percentProp` and always map to `valueProp`? Because
  69473. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  69474. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  69475. // data extent. All of values that are overflow the `dataExtent` will be calculated
  69476. // to percent '100%').
  69477. if (rangePropMode[idx] === 'percent') {
  69478. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  69479. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  69480. } else {
  69481. hasPropModeValue = true;
  69482. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  69483. // This calculation can not be inversed, because all of values that
  69484. // are overflow the `dataExtent` will be calculated to percent '100%'
  69485. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  69486. } // valueWindow[idx] = round(boundValue);
  69487. // percentWindow[idx] = round(boundPercent);
  69488. // fallback to extent start/end when parsed value or percent is invalid
  69489. valueWindow[idx] = boundValue == null || isNaN(boundValue) ? dataExtent[idx] : boundValue;
  69490. percentWindow[idx] = boundPercent == null || isNaN(boundPercent) ? percentExtent[idx] : boundPercent;
  69491. });
  69492. asc$1(valueWindow);
  69493. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  69494. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we don't restrict window
  69495. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  69496. // where API is able to initialize/modify the window size even though `zoomLock`
  69497. // specified.
  69498. var spans = this._minMaxSpan;
  69499. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  69500. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  69501. var suffix = toValue ? 'Span' : 'ValueSpan';
  69502. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  69503. for (var i = 0; i < 2; i++) {
  69504. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  69505. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  69506. }
  69507. }
  69508. return {
  69509. valueWindow: valueWindow,
  69510. percentWindow: percentWindow
  69511. };
  69512. };
  69513. /**
  69514. * Notice: reset should not be called before series.restoreData() is called,
  69515. * so it is recommended to be called in "process stage" but not "model init
  69516. * stage".
  69517. */
  69518. AxisProxy.prototype.reset = function (dataZoomModel) {
  69519. if (dataZoomModel !== this._dataZoomModel) {
  69520. return;
  69521. }
  69522. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  69523. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // `calculateDataWindow` uses min/maxSpan.
  69524. this._updateMinMaxSpan();
  69525. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  69526. this._valueWindow = dataWindow.valueWindow;
  69527. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  69528. this._setAxisModel();
  69529. };
  69530. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  69531. if (dataZoomModel !== this._dataZoomModel) {
  69532. return;
  69533. }
  69534. var axisDim = this._dimName;
  69535. var seriesModels = this.getTargetSeriesModels();
  69536. var filterMode = dataZoomModel.get('filterMode');
  69537. var valueWindow = this._valueWindow;
  69538. if (filterMode === 'none') {
  69539. return;
  69540. } // FIXME
  69541. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  69542. // with NaN data, NaN will be filtered and stack will be wrong.
  69543. // So we need to force the mode to be set empty.
  69544. // In fect, it is not a big deal that do not support filterMode-'filter'
  69545. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  69546. // selection" some day, which might need "adapt to data extent on the
  69547. // otherAxis", which is disabled by filterMode-'empty'.
  69548. // But currently, stack has been fixed to based on value but not index,
  69549. // so this is not an issue any more.
  69550. // let otherAxisModel = this.getOtherAxisModel();
  69551. // if (dataZoomModel.get('$fromToolbox')
  69552. // && otherAxisModel
  69553. // && otherAxisModel.hasSeriesStacked
  69554. // ) {
  69555. // filterMode = 'empty';
  69556. // }
  69557. // TODO
  69558. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  69559. each$8(seriesModels, function (seriesModel) {
  69560. var seriesData = seriesModel.getData();
  69561. var dataDims = seriesData.mapDimensionsAll(axisDim);
  69562. if (!dataDims.length) {
  69563. return;
  69564. }
  69565. if (filterMode === 'weakFilter') {
  69566. var store_1 = seriesData.getStore();
  69567. var dataDimIndices_1 = map(dataDims, function (dim) {
  69568. return seriesData.getDimensionIndex(dim);
  69569. }, seriesData);
  69570. seriesData.filterSelf(function (dataIndex) {
  69571. var leftOut;
  69572. var rightOut;
  69573. var hasValue;
  69574. for (var i = 0; i < dataDims.length; i++) {
  69575. var value = store_1.get(dataDimIndices_1[i], dataIndex);
  69576. var thisHasValue = !isNaN(value);
  69577. var thisLeftOut = value < valueWindow[0];
  69578. var thisRightOut = value > valueWindow[1];
  69579. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  69580. return true;
  69581. }
  69582. thisHasValue && (hasValue = true);
  69583. thisLeftOut && (leftOut = true);
  69584. thisRightOut && (rightOut = true);
  69585. } // If both left out and right out, do not filter.
  69586. return hasValue && leftOut && rightOut;
  69587. });
  69588. } else {
  69589. each$8(dataDims, function (dim) {
  69590. if (filterMode === 'empty') {
  69591. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  69592. return !isInWindow(value) ? NaN : value;
  69593. }));
  69594. } else {
  69595. var range = {};
  69596. range[dim] = valueWindow; // console.time('select');
  69597. seriesData.selectRange(range); // console.timeEnd('select');
  69598. }
  69599. });
  69600. }
  69601. each$8(dataDims, function (dim) {
  69602. seriesData.setApproximateExtent(valueWindow, dim);
  69603. });
  69604. });
  69605. function isInWindow(value) {
  69606. return value >= valueWindow[0] && value <= valueWindow[1];
  69607. }
  69608. };
  69609. AxisProxy.prototype._updateMinMaxSpan = function () {
  69610. var minMaxSpan = this._minMaxSpan = {};
  69611. var dataZoomModel = this._dataZoomModel;
  69612. var dataExtent = this._dataExtent;
  69613. each$8(['min', 'max'], function (minMax) {
  69614. var percentSpan = dataZoomModel.get(minMax + 'Span');
  69615. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  69616. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  69617. if (valueSpan != null) {
  69618. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  69619. } else if (percentSpan != null) {
  69620. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  69621. }
  69622. minMaxSpan[minMax + 'Span'] = percentSpan;
  69623. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  69624. }, this);
  69625. };
  69626. AxisProxy.prototype._setAxisModel = function () {
  69627. var axisModel = this.getAxisModel();
  69628. var percentWindow = this._percentWindow;
  69629. var valueWindow = this._valueWindow;
  69630. if (!percentWindow) {
  69631. return;
  69632. } // [0, 500]: arbitrary value, guess axis extent.
  69633. var precision = getPixelPrecision(valueWindow, [0, 500]);
  69634. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  69635. // by series data, which may be a little different from the extent calculated by
  69636. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  69637. // little when zooming. So it will not be fixed until some users require it strongly.
  69638. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  69639. if (percentWindow[0] !== 0) {
  69640. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  69641. }
  69642. if (percentWindow[1] !== 100) {
  69643. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  69644. }
  69645. rawExtentInfo.freeze();
  69646. };
  69647. return AxisProxy;
  69648. }();
  69649. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  69650. var dataExtent = [Infinity, -Infinity];
  69651. each$8(seriesModels, function (seriesModel) {
  69652. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  69653. }); // It is important to get "consistent" extent when more then one axes is
  69654. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  69655. // when zooming. But it is difficult to know what is "consistent", considering
  69656. // axes have different type or even different meanings (For example, two
  69657. // time axes are used to compare data of the same date in different years).
  69658. // So basically dataZoom just obtains extent by series.data (in category axis
  69659. // extent can be obtained from axis.data).
  69660. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  69661. // consistent.
  69662. var axisModel = axisProxy.getAxisModel();
  69663. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  69664. return [rawExtentResult.min, rawExtentResult.max];
  69665. }
  69666. var dataZoomProcessor = {
  69667. // `dataZoomProcessor` will only be performed in needed series. Consider if
  69668. // there is a line series and a pie series, it is better not to update the
  69669. // line series if only pie series is needed to be updated.
  69670. getTargetSeries: function (ecModel) {
  69671. function eachAxisModel(cb) {
  69672. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69673. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69674. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  69675. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  69676. });
  69677. });
  69678. } // FIXME: it brings side-effect to `getTargetSeries`.
  69679. // Prepare axis proxies.
  69680. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69681. // dispose all last axis proxy, in case that some axis are deleted.
  69682. axisModel.__dzAxisProxy = null;
  69683. });
  69684. var proxyList = [];
  69685. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  69686. // Different dataZooms may constrol the same axis. In that case,
  69687. // an axisProxy serves both of them.
  69688. if (!axisModel.__dzAxisProxy) {
  69689. // Use the first dataZoomModel as the main model of axisProxy.
  69690. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  69691. proxyList.push(axisModel.__dzAxisProxy);
  69692. }
  69693. });
  69694. var seriesModelMap = createHashMap();
  69695. each(proxyList, function (axisProxy) {
  69696. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  69697. seriesModelMap.set(seriesModel.uid, seriesModel);
  69698. });
  69699. });
  69700. return seriesModelMap;
  69701. },
  69702. // Consider appendData, where filter should be performed. Because data process is
  69703. // in block mode currently, it is not need to worry about that the overallProgress
  69704. // execute every frame.
  69705. overallReset: function (ecModel, api) {
  69706. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69707. // We calculate window and reset axis here but not in model
  69708. // init stage and not after action dispatch handler, because
  69709. // reset should be called after seriesData.restoreData.
  69710. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69711. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  69712. }); // Caution: data zoom filtering is order sensitive when using
  69713. // percent range and no min/max/scale set on axis.
  69714. // For example, we have dataZoom definition:
  69715. // [
  69716. // {xAxisIndex: 0, start: 30, end: 70},
  69717. // {yAxisIndex: 0, start: 20, end: 80}
  69718. // ]
  69719. // In this case, [20, 80] of y-dataZoom should be based on data
  69720. // that have filtered by x-dataZoom using range of [30, 70],
  69721. // but should not be based on full raw data. Thus sliding
  69722. // x-dataZoom will change both ranges of xAxis and yAxis,
  69723. // while sliding y-dataZoom will only change the range of yAxis.
  69724. // So we should filter x-axis after reset x-axis immediately,
  69725. // and then reset y-axis and filter y-axis.
  69726. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  69727. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  69728. });
  69729. });
  69730. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69731. // Fullfill all of the range props so that user
  69732. // is able to get them from chart.getOption().
  69733. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  69734. if (axisProxy) {
  69735. var percentRange = axisProxy.getDataPercentWindow();
  69736. var valueRange = axisProxy.getDataValueWindow();
  69737. dataZoomModel.setCalculatedRange({
  69738. start: percentRange[0],
  69739. end: percentRange[1],
  69740. startValue: valueRange[0],
  69741. endValue: valueRange[1]
  69742. });
  69743. }
  69744. });
  69745. }
  69746. };
  69747. function installDataZoomAction(registers) {
  69748. registers.registerAction('dataZoom', function (payload, ecModel) {
  69749. var effectedModels = findEffectedDataZooms(ecModel, payload);
  69750. each(effectedModels, function (dataZoomModel) {
  69751. dataZoomModel.setRawRange({
  69752. start: payload.start,
  69753. end: payload.end,
  69754. startValue: payload.startValue,
  69755. endValue: payload.endValue
  69756. });
  69757. });
  69758. });
  69759. }
  69760. var installed = false;
  69761. function installCommon(registers) {
  69762. if (installed) {
  69763. return;
  69764. }
  69765. installed = true;
  69766. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  69767. installDataZoomAction(registers);
  69768. registers.registerSubTypeDefaulter('dataZoom', function () {
  69769. // Default 'slider' when no type specified.
  69770. return 'slider';
  69771. });
  69772. }
  69773. function install$y(registers) {
  69774. registers.registerComponentModel(SelectDataZoomModel);
  69775. registers.registerComponentView(SelectDataZoomView);
  69776. installCommon(registers);
  69777. }
  69778. /*
  69779. * Licensed to the Apache Software Foundation (ASF) under one
  69780. * or more contributor license agreements. See the NOTICE file
  69781. * distributed with this work for additional information
  69782. * regarding copyright ownership. The ASF licenses this file
  69783. * to you under the Apache License, Version 2.0 (the
  69784. * "License"); you may not use this file except in compliance
  69785. * with the License. You may obtain a copy of the License at
  69786. *
  69787. * http://www.apache.org/licenses/LICENSE-2.0
  69788. *
  69789. * Unless required by applicable law or agreed to in writing,
  69790. * software distributed under the License is distributed on an
  69791. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69792. * KIND, either express or implied. See the License for the
  69793. * specific language governing permissions and limitations
  69794. * under the License.
  69795. */
  69796. /**
  69797. * AUTO-GENERATED FILE. DO NOT MODIFY.
  69798. */
  69799. var ToolboxFeature =
  69800. /** @class */
  69801. function () {
  69802. function ToolboxFeature() {}
  69803. return ToolboxFeature;
  69804. }();
  69805. var features = {};
  69806. function registerFeature(name, ctor) {
  69807. features[name] = ctor;
  69808. }
  69809. function getFeature(name) {
  69810. return features[name];
  69811. }
  69812. var ToolboxModel =
  69813. /** @class */
  69814. function (_super) {
  69815. __extends(ToolboxModel, _super);
  69816. function ToolboxModel() {
  69817. var _this = _super !== null && _super.apply(this, arguments) || this;
  69818. _this.type = ToolboxModel.type;
  69819. return _this;
  69820. }
  69821. ToolboxModel.prototype.optionUpdated = function () {
  69822. _super.prototype.optionUpdated.apply(this, arguments);
  69823. var ecModel = this.ecModel;
  69824. each(this.option.feature, function (featureOpt, featureName) {
  69825. var Feature = getFeature(featureName);
  69826. if (Feature) {
  69827. if (Feature.getDefaultOption) {
  69828. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  69829. }
  69830. merge(featureOpt, Feature.defaultOption);
  69831. }
  69832. });
  69833. };
  69834. ToolboxModel.type = 'toolbox';
  69835. ToolboxModel.layoutMode = {
  69836. type: 'box',
  69837. ignoreSize: true
  69838. };
  69839. ToolboxModel.defaultOption = {
  69840. show: true,
  69841. z: 6,
  69842. // zlevel: 0,
  69843. orient: 'horizontal',
  69844. left: 'right',
  69845. top: 'top',
  69846. // right
  69847. // bottom
  69848. backgroundColor: 'transparent',
  69849. borderColor: '#ccc',
  69850. borderRadius: 0,
  69851. borderWidth: 0,
  69852. padding: 5,
  69853. itemSize: 15,
  69854. itemGap: 8,
  69855. showTitle: true,
  69856. iconStyle: {
  69857. borderColor: '#666',
  69858. color: 'none'
  69859. },
  69860. emphasis: {
  69861. iconStyle: {
  69862. borderColor: '#3E98C5'
  69863. }
  69864. },
  69865. // textStyle: {},
  69866. // feature
  69867. tooltip: {
  69868. show: false,
  69869. position: 'bottom'
  69870. }
  69871. };
  69872. return ToolboxModel;
  69873. }(ComponentModel);
  69874. /**
  69875. * Layout list like component.
  69876. * It will box layout each items in group of component and then position the whole group in the viewport
  69877. * @param {module:zrender/group/Group} group
  69878. * @param {module:echarts/model/Component} componentModel
  69879. * @param {module:echarts/ExtensionAPI}
  69880. */
  69881. function layout$3(group, componentModel, api) {
  69882. var boxLayoutParams = componentModel.getBoxLayoutParams();
  69883. var padding = componentModel.get('padding');
  69884. var viewportSize = {
  69885. width: api.getWidth(),
  69886. height: api.getHeight()
  69887. };
  69888. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  69889. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  69890. positionElement(group, boxLayoutParams, viewportSize, padding);
  69891. }
  69892. function makeBackground(rect, componentModel) {
  69893. var padding = normalizeCssArray$1(componentModel.get('padding'));
  69894. var style = componentModel.getItemStyle(['color', 'opacity']);
  69895. style.fill = componentModel.get('backgroundColor');
  69896. rect = new Rect({
  69897. shape: {
  69898. x: rect.x - padding[3],
  69899. y: rect.y - padding[0],
  69900. width: rect.width + padding[1] + padding[3],
  69901. height: rect.height + padding[0] + padding[2],
  69902. r: componentModel.get('borderRadius')
  69903. },
  69904. style: style,
  69905. silent: true,
  69906. z2: -1
  69907. }); // FIXME
  69908. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  69909. // and background rect when setting like `left: 0`, `top: 0`.
  69910. // graphic.subPixelOptimizeRect(rect);
  69911. return rect;
  69912. }
  69913. var ToolboxView =
  69914. /** @class */
  69915. function (_super) {
  69916. __extends(ToolboxView, _super);
  69917. function ToolboxView() {
  69918. return _super !== null && _super.apply(this, arguments) || this;
  69919. }
  69920. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  69921. var group = this.group;
  69922. group.removeAll();
  69923. if (!toolboxModel.get('show')) {
  69924. return;
  69925. }
  69926. var itemSize = +toolboxModel.get('itemSize');
  69927. var isVertical = toolboxModel.get('orient') === 'vertical';
  69928. var featureOpts = toolboxModel.get('feature') || {};
  69929. var features = this._features || (this._features = {});
  69930. var featureNames = [];
  69931. each(featureOpts, function (opt, name) {
  69932. featureNames.push(name);
  69933. });
  69934. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  69935. this._featureNames = featureNames;
  69936. function processFeature(newIndex, oldIndex) {
  69937. var featureName = featureNames[newIndex];
  69938. var oldName = featureNames[oldIndex];
  69939. var featureOpt = featureOpts[featureName];
  69940. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  69941. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  69942. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  69943. featureOpt.title = payload.newTitle;
  69944. }
  69945. if (featureName && !oldName) {
  69946. // Create
  69947. if (isUserFeatureName(featureName)) {
  69948. feature = {
  69949. onclick: featureModel.option.onclick,
  69950. featureName: featureName
  69951. };
  69952. } else {
  69953. var Feature = getFeature(featureName);
  69954. if (!Feature) {
  69955. return;
  69956. }
  69957. feature = new Feature();
  69958. }
  69959. features[featureName] = feature;
  69960. } else {
  69961. feature = features[oldName]; // If feature does not exist.
  69962. if (!feature) {
  69963. return;
  69964. }
  69965. }
  69966. feature.uid = getUID('toolbox-feature');
  69967. feature.model = featureModel;
  69968. feature.ecModel = ecModel;
  69969. feature.api = api;
  69970. var isToolboxFeature = feature instanceof ToolboxFeature;
  69971. if (!featureName && oldName) {
  69972. isToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  69973. return;
  69974. }
  69975. if (!featureModel.get('show') || isToolboxFeature && feature.unusable) {
  69976. isToolboxFeature && feature.remove && feature.remove(ecModel, api);
  69977. return;
  69978. }
  69979. createIconPaths(featureModel, feature, featureName);
  69980. featureModel.setIconStatus = function (iconName, status) {
  69981. var option = this.option;
  69982. var iconPaths = this.iconPaths;
  69983. option.iconStatus = option.iconStatus || {};
  69984. option.iconStatus[iconName] = status;
  69985. if (iconPaths[iconName]) {
  69986. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  69987. }
  69988. };
  69989. if (feature instanceof ToolboxFeature) {
  69990. if (feature.render) {
  69991. feature.render(featureModel, ecModel, api, payload);
  69992. }
  69993. }
  69994. }
  69995. function createIconPaths(featureModel, feature, featureName) {
  69996. var iconStyleModel = featureModel.getModel('iconStyle');
  69997. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has multiple icons, they are organized as
  69998. // {
  69999. // icon: {
  70000. // foo: '',
  70001. // bar: ''
  70002. // },
  70003. // title: {
  70004. // foo: '',
  70005. // bar: ''
  70006. // }
  70007. // }
  70008. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  70009. var titles = featureModel.get('title') || {};
  70010. var iconsMap;
  70011. var titlesMap;
  70012. if (isString(icons)) {
  70013. iconsMap = {};
  70014. iconsMap[featureName] = icons;
  70015. } else {
  70016. iconsMap = icons;
  70017. }
  70018. if (isString(titles)) {
  70019. titlesMap = {};
  70020. titlesMap[featureName] = titles;
  70021. } else {
  70022. titlesMap = titles;
  70023. }
  70024. var iconPaths = featureModel.iconPaths = {};
  70025. each(iconsMap, function (iconStr, iconName) {
  70026. var path = createIcon(iconStr, {}, {
  70027. x: -itemSize / 2,
  70028. y: -itemSize / 2,
  70029. width: itemSize,
  70030. height: itemSize
  70031. }); // TODO handling image
  70032. path.setStyle(iconStyleModel.getItemStyle());
  70033. var pathEmphasisState = path.ensureState('emphasis');
  70034. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  70035. var textContent = new ZRText({
  70036. style: {
  70037. text: titlesMap[iconName],
  70038. align: iconStyleEmphasisModel.get('textAlign'),
  70039. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  70040. padding: iconStyleEmphasisModel.get('textPadding'),
  70041. fill: null
  70042. },
  70043. ignore: true
  70044. });
  70045. path.setTextContent(textContent);
  70046. setTooltipConfig({
  70047. el: path,
  70048. componentModel: toolboxModel,
  70049. itemName: iconName,
  70050. formatterParamsExtra: {
  70051. title: titlesMap[iconName]
  70052. }
  70053. });
  70054. path.__title = titlesMap[iconName];
  70055. path.on('mouseover', function () {
  70056. // Should not reuse above hoverStyle, which might be modified.
  70057. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  70058. var defaultTextPosition = isVertical ? toolboxModel.get('right') == null && toolboxModel.get('left') !== 'right' ? 'right' : 'left' : toolboxModel.get('bottom') == null && toolboxModel.get('top') !== 'bottom' ? 'bottom' : 'top';
  70059. textContent.setStyle({
  70060. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  70061. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  70062. });
  70063. path.setTextConfig({
  70064. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  70065. });
  70066. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  70067. // There are flags managed by the echarts.
  70068. api.enterEmphasis(this);
  70069. }).on('mouseout', function () {
  70070. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  70071. api.leaveEmphasis(this);
  70072. }
  70073. textContent.hide();
  70074. });
  70075. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  70076. group.add(path);
  70077. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  70078. iconPaths[iconName] = path;
  70079. });
  70080. }
  70081. layout$3(group, toolboxModel, api); // Render background after group is layout
  70082. // FIXME
  70083. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  70084. isVertical || group.eachChild(function (icon) {
  70085. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  70086. // TODO simplify code?
  70087. var emphasisState = icon.ensureState('emphasis');
  70088. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  70089. var textContent = icon.getTextContent();
  70090. var emphasisTextState = textContent && textContent.ensureState('emphasis'); // May be background element
  70091. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  70092. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  70093. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  70094. var offsetX = icon.x + group.x;
  70095. var offsetY = icon.y + group.y + itemSize;
  70096. var needPutOnTop = false;
  70097. if (offsetY + rect.height > api.getHeight()) {
  70098. emphasisTextConfig.position = 'top';
  70099. needPutOnTop = true;
  70100. }
  70101. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 10;
  70102. if (offsetX + rect.width / 2 > api.getWidth()) {
  70103. emphasisTextConfig.position = ['100%', topOffset];
  70104. emphasisTextStyle.align = 'right';
  70105. } else if (offsetX - rect.width / 2 < 0) {
  70106. emphasisTextConfig.position = [0, topOffset];
  70107. emphasisTextStyle.align = 'left';
  70108. }
  70109. }
  70110. });
  70111. };
  70112. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  70113. each(this._features, function (feature) {
  70114. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  70115. });
  70116. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  70117. // zrUtil.each(this._features, function (feature) {
  70118. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  70119. // });
  70120. // },
  70121. ToolboxView.prototype.remove = function (ecModel, api) {
  70122. each(this._features, function (feature) {
  70123. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  70124. });
  70125. this.group.removeAll();
  70126. };
  70127. ToolboxView.prototype.dispose = function (ecModel, api) {
  70128. each(this._features, function (feature) {
  70129. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  70130. });
  70131. };
  70132. ToolboxView.type = 'toolbox';
  70133. return ToolboxView;
  70134. }(ComponentView);
  70135. function isUserFeatureName(featureName) {
  70136. return featureName.indexOf('my') === 0;
  70137. }
  70138. /* global window, document */
  70139. var SaveAsImage =
  70140. /** @class */
  70141. function (_super) {
  70142. __extends(SaveAsImage, _super);
  70143. function SaveAsImage() {
  70144. return _super !== null && _super.apply(this, arguments) || this;
  70145. }
  70146. SaveAsImage.prototype.onclick = function (ecModel, api) {
  70147. var model = this.model;
  70148. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  70149. var isSvg = api.getZr().painter.getType() === 'svg';
  70150. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  70151. var url = api.getConnectedDataURL({
  70152. type: type,
  70153. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  70154. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  70155. excludeComponents: model.get('excludeComponents'),
  70156. pixelRatio: model.get('pixelRatio')
  70157. });
  70158. var browser = env.browser; // Chrome, Firefox, New Edge
  70159. if (isFunction(MouseEvent) && (browser.newEdge || !browser.ie && !browser.edge)) {
  70160. var $a = document.createElement('a');
  70161. $a.download = title + '.' + type;
  70162. $a.target = '_blank';
  70163. $a.href = url;
  70164. var evt = new MouseEvent('click', {
  70165. // some micro front-end framework, window maybe is a Proxy
  70166. view: document.defaultView,
  70167. bubbles: true,
  70168. cancelable: false
  70169. });
  70170. $a.dispatchEvent(evt);
  70171. } // IE or old Edge
  70172. else {
  70173. // @ts-ignore
  70174. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  70175. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  70176. var base64Encoded = parts[0].indexOf('base64') > -1;
  70177. var bstr = isSvg // should decode the svg data uri first
  70178. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  70179. // otherwise, like `svg` data uri exported by zrender,
  70180. // there will be an error, for it's not encoded with base64.
  70181. // (just a url-encoded string through `encodeURIComponent`)
  70182. base64Encoded && (bstr = window.atob(bstr));
  70183. var filename = title + '.' + type; // @ts-ignore
  70184. if (window.navigator.msSaveOrOpenBlob) {
  70185. var n = bstr.length;
  70186. var u8arr = new Uint8Array(n);
  70187. while (n--) {
  70188. u8arr[n] = bstr.charCodeAt(n);
  70189. }
  70190. var blob = new Blob([u8arr]); // @ts-ignore
  70191. window.navigator.msSaveOrOpenBlob(blob, filename);
  70192. } else {
  70193. var frame = document.createElement('iframe');
  70194. document.body.appendChild(frame);
  70195. var cw = frame.contentWindow;
  70196. var doc = cw.document;
  70197. doc.open('image/svg+xml', 'replace');
  70198. doc.write(bstr);
  70199. doc.close();
  70200. cw.focus();
  70201. doc.execCommand('SaveAs', true, filename);
  70202. document.body.removeChild(frame);
  70203. }
  70204. } else {
  70205. var lang = model.get('lang');
  70206. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  70207. var tab = window.open();
  70208. tab.document.write(html);
  70209. tab.document.title = title;
  70210. }
  70211. }
  70212. };
  70213. SaveAsImage.getDefaultOption = function (ecModel) {
  70214. var defaultOption = {
  70215. show: true,
  70216. 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',
  70217. title: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'title']),
  70218. type: 'png',
  70219. // Default use option.backgroundColor
  70220. // backgroundColor: '#fff',
  70221. connectedBackgroundColor: '#fff',
  70222. name: '',
  70223. excludeComponents: ['toolbox'],
  70224. // use current pixel ratio of device by default
  70225. // pixelRatio: 1,
  70226. lang: ecModel.getLocaleModel().get(['toolbox', 'saveAsImage', 'lang'])
  70227. };
  70228. return defaultOption;
  70229. };
  70230. return SaveAsImage;
  70231. }(ToolboxFeature);
  70232. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  70233. var radioTypes = [['line', 'bar'], ['stack']];
  70234. var MagicType =
  70235. /** @class */
  70236. function (_super) {
  70237. __extends(MagicType, _super);
  70238. function MagicType() {
  70239. return _super !== null && _super.apply(this, arguments) || this;
  70240. }
  70241. MagicType.prototype.getIcons = function () {
  70242. var model = this.model;
  70243. var availableIcons = model.get('icon');
  70244. var icons = {};
  70245. each(model.get('type'), function (type) {
  70246. if (availableIcons[type]) {
  70247. icons[type] = availableIcons[type];
  70248. }
  70249. });
  70250. return icons;
  70251. };
  70252. MagicType.getDefaultOption = function (ecModel) {
  70253. var defaultOption = {
  70254. show: true,
  70255. type: [],
  70256. // Icon group
  70257. icon: {
  70258. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  70259. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  70260. // eslint-disable-next-line
  70261. 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
  70262. },
  70263. // `line`, `bar`, `stack`, `tiled`
  70264. title: ecModel.getLocaleModel().get(['toolbox', 'magicType', 'title']),
  70265. option: {},
  70266. seriesIndex: {}
  70267. };
  70268. return defaultOption;
  70269. };
  70270. MagicType.prototype.onclick = function (ecModel, api, type) {
  70271. var model = this.model;
  70272. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  70273. if (!seriesOptGenreator[type]) {
  70274. return;
  70275. }
  70276. var newOption = {
  70277. series: []
  70278. };
  70279. var generateNewSeriesTypes = function (seriesModel) {
  70280. var seriesType = seriesModel.subType;
  70281. var seriesId = seriesModel.id;
  70282. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  70283. if (newSeriesOpt) {
  70284. // PENDING If merge original option?
  70285. defaults(newSeriesOpt, seriesModel.option);
  70286. newOption.series.push(newSeriesOpt);
  70287. } // Modify boundaryGap
  70288. var coordSys = seriesModel.coordinateSystem;
  70289. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  70290. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  70291. if (categoryAxis) {
  70292. var axisDim = categoryAxis.dim;
  70293. var axisType = axisDim + 'Axis';
  70294. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  70295. var axisIndex = axisModel.componentIndex;
  70296. newOption[axisType] = newOption[axisType] || [];
  70297. for (var i = 0; i <= axisIndex; i++) {
  70298. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  70299. }
  70300. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  70301. }
  70302. }
  70303. };
  70304. each(radioTypes, function (radio) {
  70305. if (indexOf(radio, type) >= 0) {
  70306. each(radio, function (item) {
  70307. model.setIconStatus(item, 'normal');
  70308. });
  70309. }
  70310. });
  70311. model.setIconStatus(type, 'emphasis');
  70312. ecModel.eachComponent({
  70313. mainType: 'series',
  70314. query: seriesIndex == null ? null : {
  70315. seriesIndex: seriesIndex
  70316. }
  70317. }, generateNewSeriesTypes);
  70318. var newTitle;
  70319. var currentType = type; // Change title of stack
  70320. if (type === 'stack') {
  70321. // use titles in model instead of ecModel
  70322. // as stack and tiled appears in pair, just flip them
  70323. // no need of checking stack state
  70324. newTitle = merge({
  70325. stack: model.option.title.tiled,
  70326. tiled: model.option.title.stack
  70327. }, model.option.title);
  70328. if (model.get(['iconStatus', type]) !== 'emphasis') {
  70329. currentType = 'tiled';
  70330. }
  70331. }
  70332. api.dispatchAction({
  70333. type: 'changeMagicType',
  70334. currentType: currentType,
  70335. newOption: newOption,
  70336. newTitle: newTitle,
  70337. featureName: 'magicType'
  70338. });
  70339. };
  70340. return MagicType;
  70341. }(ToolboxFeature);
  70342. var seriesOptGenreator = {
  70343. 'line': function (seriesType, seriesId, seriesModel, model) {
  70344. if (seriesType === 'bar') {
  70345. return merge({
  70346. id: seriesId,
  70347. type: 'line',
  70348. // Preserve data related option
  70349. data: seriesModel.get('data'),
  70350. stack: seriesModel.get('stack'),
  70351. markPoint: seriesModel.get('markPoint'),
  70352. markLine: seriesModel.get('markLine')
  70353. }, model.get(['option', 'line']) || {}, true);
  70354. }
  70355. },
  70356. 'bar': function (seriesType, seriesId, seriesModel, model) {
  70357. if (seriesType === 'line') {
  70358. return merge({
  70359. id: seriesId,
  70360. type: 'bar',
  70361. // Preserve data related option
  70362. data: seriesModel.get('data'),
  70363. stack: seriesModel.get('stack'),
  70364. markPoint: seriesModel.get('markPoint'),
  70365. markLine: seriesModel.get('markLine')
  70366. }, model.get(['option', 'bar']) || {}, true);
  70367. }
  70368. },
  70369. 'stack': function (seriesType, seriesId, seriesModel, model) {
  70370. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  70371. if (seriesType === 'line' || seriesType === 'bar') {
  70372. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  70373. return merge({
  70374. id: seriesId,
  70375. stack: isStack ? '' : INNER_STACK_KEYWORD
  70376. }, model.get(['option', 'stack']) || {}, true);
  70377. }
  70378. }
  70379. }; // TODO: SELF REGISTERED.
  70380. registerAction({
  70381. type: 'changeMagicType',
  70382. event: 'magicTypeChanged',
  70383. update: 'prepareAndUpdate'
  70384. }, function (payload, ecModel) {
  70385. ecModel.mergeOption(payload.newOption);
  70386. });
  70387. /* global document */
  70388. var BLOCK_SPLITER = new Array(60).join('-');
  70389. var ITEM_SPLITER = '\t';
  70390. /**
  70391. * Group series into two types
  70392. * 1. on category axis, like line, bar
  70393. * 2. others, like scatter, pie
  70394. */
  70395. function groupSeries(ecModel) {
  70396. var seriesGroupByCategoryAxis = {};
  70397. var otherSeries = [];
  70398. var meta = [];
  70399. ecModel.eachRawSeries(function (seriesModel) {
  70400. var coordSys = seriesModel.coordinateSystem;
  70401. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  70402. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  70403. var baseAxis = coordSys.getBaseAxis();
  70404. if (baseAxis.type === 'category') {
  70405. var key = baseAxis.dim + '_' + baseAxis.index;
  70406. if (!seriesGroupByCategoryAxis[key]) {
  70407. seriesGroupByCategoryAxis[key] = {
  70408. categoryAxis: baseAxis,
  70409. valueAxis: coordSys.getOtherAxis(baseAxis),
  70410. series: []
  70411. };
  70412. meta.push({
  70413. axisDim: baseAxis.dim,
  70414. axisIndex: baseAxis.index
  70415. });
  70416. }
  70417. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  70418. } else {
  70419. otherSeries.push(seriesModel);
  70420. }
  70421. } else {
  70422. otherSeries.push(seriesModel);
  70423. }
  70424. });
  70425. return {
  70426. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  70427. other: otherSeries,
  70428. meta: meta
  70429. };
  70430. }
  70431. /**
  70432. * Assemble content of series on cateogory axis
  70433. * @inner
  70434. */
  70435. function assembleSeriesWithCategoryAxis(groups) {
  70436. var tables = [];
  70437. each(groups, function (group, key) {
  70438. var categoryAxis = group.categoryAxis;
  70439. var valueAxis = group.valueAxis;
  70440. var valueAxisDim = valueAxis.dim;
  70441. var headers = [' '].concat(map(group.series, function (series) {
  70442. return series.name;
  70443. })); // @ts-ignore TODO Polar
  70444. var columns = [categoryAxis.model.getCategories()];
  70445. each(group.series, function (series) {
  70446. var rawData = series.getRawData();
  70447. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  70448. return val;
  70449. }));
  70450. }); // Assemble table content
  70451. var lines = [headers.join(ITEM_SPLITER)];
  70452. for (var i = 0; i < columns[0].length; i++) {
  70453. var items = [];
  70454. for (var j = 0; j < columns.length; j++) {
  70455. items.push(columns[j][i]);
  70456. }
  70457. lines.push(items.join(ITEM_SPLITER));
  70458. }
  70459. tables.push(lines.join('\n'));
  70460. });
  70461. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  70462. }
  70463. /**
  70464. * Assemble content of other series
  70465. */
  70466. function assembleOtherSeries(series) {
  70467. return map(series, function (series) {
  70468. var data = series.getRawData();
  70469. var lines = [series.name];
  70470. var vals = [];
  70471. data.each(data.dimensions, function () {
  70472. var argLen = arguments.length;
  70473. var dataIndex = arguments[argLen - 1];
  70474. var name = data.getName(dataIndex);
  70475. for (var i = 0; i < argLen - 1; i++) {
  70476. vals[i] = arguments[i];
  70477. }
  70478. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  70479. });
  70480. return lines.join('\n');
  70481. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  70482. }
  70483. function getContentFromModel(ecModel) {
  70484. var result = groupSeries(ecModel);
  70485. return {
  70486. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  70487. return !!str.replace(/[\n\t\s]/g, '');
  70488. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  70489. meta: result.meta
  70490. };
  70491. }
  70492. function trim$1(str) {
  70493. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  70494. }
  70495. /**
  70496. * If a block is tsv format
  70497. */
  70498. function isTSVFormat(block) {
  70499. // Simple method to find out if a block is tsv format
  70500. var firstLine = block.slice(0, block.indexOf('\n'));
  70501. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  70502. return true;
  70503. }
  70504. }
  70505. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  70506. /**
  70507. * @param {string} tsv
  70508. * @return {Object}
  70509. */
  70510. function parseTSVContents(tsv) {
  70511. var tsvLines = tsv.split(/\n+/g);
  70512. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  70513. var categories = [];
  70514. var series = map(headers, function (header) {
  70515. return {
  70516. name: header,
  70517. data: []
  70518. };
  70519. });
  70520. for (var i = 0; i < tsvLines.length; i++) {
  70521. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  70522. categories.push(items.shift());
  70523. for (var j = 0; j < items.length; j++) {
  70524. series[j] && (series[j].data[i] = items[j]);
  70525. }
  70526. }
  70527. return {
  70528. series: series,
  70529. categories: categories
  70530. };
  70531. }
  70532. function parseListContents(str) {
  70533. var lines = str.split(/\n+/g);
  70534. var seriesName = trim$1(lines.shift());
  70535. var data = [];
  70536. for (var i = 0; i < lines.length; i++) {
  70537. // if line is empty, ignore it.
  70538. // there is a case that a user forgot to delete `\n`.
  70539. var line = trim$1(lines[i]);
  70540. if (!line) {
  70541. continue;
  70542. }
  70543. var items = line.split(itemSplitRegex);
  70544. var name_1 = '';
  70545. var value = void 0;
  70546. var hasName = false;
  70547. if (isNaN(items[0])) {
  70548. // First item is name
  70549. hasName = true;
  70550. name_1 = items[0];
  70551. items = items.slice(1);
  70552. data[i] = {
  70553. name: name_1,
  70554. value: []
  70555. };
  70556. value = data[i].value;
  70557. } else {
  70558. value = data[i] = [];
  70559. }
  70560. for (var j = 0; j < items.length; j++) {
  70561. value.push(+items[j]);
  70562. }
  70563. if (value.length === 1) {
  70564. hasName ? data[i].value = value[0] : data[i] = value[0];
  70565. }
  70566. }
  70567. return {
  70568. name: seriesName,
  70569. data: data
  70570. };
  70571. }
  70572. function parseContents(str, blockMetaList) {
  70573. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  70574. var newOption = {
  70575. series: []
  70576. };
  70577. each(blocks, function (block, idx) {
  70578. if (isTSVFormat(block)) {
  70579. var result = parseTSVContents(block);
  70580. var blockMeta = blockMetaList[idx];
  70581. var axisKey = blockMeta.axisDim + 'Axis';
  70582. if (blockMeta) {
  70583. newOption[axisKey] = newOption[axisKey] || [];
  70584. newOption[axisKey][blockMeta.axisIndex] = {
  70585. data: result.categories
  70586. };
  70587. newOption.series = newOption.series.concat(result.series);
  70588. }
  70589. } else {
  70590. var result = parseListContents(block);
  70591. newOption.series.push(result);
  70592. }
  70593. });
  70594. return newOption;
  70595. }
  70596. var DataView =
  70597. /** @class */
  70598. function (_super) {
  70599. __extends(DataView, _super);
  70600. function DataView() {
  70601. return _super !== null && _super.apply(this, arguments) || this;
  70602. }
  70603. DataView.prototype.onclick = function (ecModel, api) {
  70604. // FIXME: better way?
  70605. setTimeout(function () {
  70606. api.dispatchAction({
  70607. type: 'hideTip'
  70608. });
  70609. });
  70610. var container = api.getDom();
  70611. var model = this.model;
  70612. if (this._dom) {
  70613. container.removeChild(this._dom);
  70614. }
  70615. var root = document.createElement('div'); // use padding to avoid 5px whitespace
  70616. root.style.cssText = 'position:absolute;top:0;bottom:0;left:0;right:0;padding:5px';
  70617. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  70618. var header = document.createElement('h4');
  70619. var lang = model.get('lang') || [];
  70620. header.innerHTML = lang[0] || model.get('title');
  70621. header.style.cssText = 'margin:10px 20px';
  70622. header.style.color = model.get('textColor');
  70623. var viewMain = document.createElement('div');
  70624. var textarea = document.createElement('textarea');
  70625. viewMain.style.cssText = 'overflow:auto';
  70626. var optionToContent = model.get('optionToContent');
  70627. var contentToOption = model.get('contentToOption');
  70628. var result = getContentFromModel(ecModel);
  70629. if (isFunction(optionToContent)) {
  70630. var htmlOrDom = optionToContent(api.getOption());
  70631. if (isString(htmlOrDom)) {
  70632. viewMain.innerHTML = htmlOrDom;
  70633. } else if (isDom(htmlOrDom)) {
  70634. viewMain.appendChild(htmlOrDom);
  70635. }
  70636. } else {
  70637. // Use default textarea
  70638. textarea.readOnly = model.get('readOnly');
  70639. var style = textarea.style; // eslint-disable-next-line max-len
  70640. 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';
  70641. style.color = model.get('textColor');
  70642. style.borderColor = model.get('textareaBorderColor');
  70643. style.backgroundColor = model.get('textareaColor');
  70644. textarea.value = result.value;
  70645. viewMain.appendChild(textarea);
  70646. }
  70647. var blockMetaList = result.meta;
  70648. var buttonContainer = document.createElement('div');
  70649. buttonContainer.style.cssText = 'position:absolute;bottom:5px;left:0;right:0'; // eslint-disable-next-line max-len
  70650. var buttonStyle = 'float:right;margin-right:20px;border:none;cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  70651. var closeButton = document.createElement('div');
  70652. var refreshButton = document.createElement('div');
  70653. buttonStyle += ';background-color:' + model.get('buttonColor');
  70654. buttonStyle += ';color:' + model.get('buttonTextColor');
  70655. var self = this;
  70656. function close() {
  70657. container.removeChild(root);
  70658. self._dom = null;
  70659. }
  70660. addEventListener(closeButton, 'click', close);
  70661. addEventListener(refreshButton, 'click', function () {
  70662. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  70663. if ("development" !== 'production') {
  70664. // eslint-disable-next-line
  70665. warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  70666. }
  70667. close();
  70668. return;
  70669. }
  70670. var newOption;
  70671. try {
  70672. if (isFunction(contentToOption)) {
  70673. newOption = contentToOption(viewMain, api.getOption());
  70674. } else {
  70675. newOption = parseContents(textarea.value, blockMetaList);
  70676. }
  70677. } catch (e) {
  70678. close();
  70679. throw new Error('Data view format error ' + e);
  70680. }
  70681. if (newOption) {
  70682. api.dispatchAction({
  70683. type: 'changeDataView',
  70684. newOption: newOption
  70685. });
  70686. }
  70687. close();
  70688. });
  70689. closeButton.innerHTML = lang[1];
  70690. refreshButton.innerHTML = lang[2];
  70691. refreshButton.style.cssText = closeButton.style.cssText = buttonStyle;
  70692. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  70693. buttonContainer.appendChild(closeButton);
  70694. root.appendChild(header);
  70695. root.appendChild(viewMain);
  70696. root.appendChild(buttonContainer);
  70697. viewMain.style.height = container.clientHeight - 80 + 'px';
  70698. container.appendChild(root);
  70699. this._dom = root;
  70700. };
  70701. DataView.prototype.remove = function (ecModel, api) {
  70702. this._dom && api.getDom().removeChild(this._dom);
  70703. };
  70704. DataView.prototype.dispose = function (ecModel, api) {
  70705. this.remove(ecModel, api);
  70706. };
  70707. DataView.getDefaultOption = function (ecModel) {
  70708. var defaultOption = {
  70709. show: true,
  70710. readOnly: false,
  70711. optionToContent: null,
  70712. contentToOption: null,
  70713. // eslint-disable-next-line
  70714. 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',
  70715. title: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'title']),
  70716. lang: ecModel.getLocaleModel().get(['toolbox', 'dataView', 'lang']),
  70717. backgroundColor: '#fff',
  70718. textColor: '#000',
  70719. textareaColor: '#fff',
  70720. textareaBorderColor: '#333',
  70721. buttonColor: '#c23531',
  70722. buttonTextColor: '#fff'
  70723. };
  70724. return defaultOption;
  70725. };
  70726. return DataView;
  70727. }(ToolboxFeature);
  70728. /**
  70729. * @inner
  70730. */
  70731. function tryMergeDataOption(newData, originalData) {
  70732. return map(newData, function (newVal, idx) {
  70733. var original = originalData && originalData[idx];
  70734. if (isObject(original) && !isArray(original)) {
  70735. var newValIsObject = isObject(newVal) && !isArray(newVal);
  70736. if (!newValIsObject) {
  70737. newVal = {
  70738. value: newVal
  70739. };
  70740. } // original data has name but new data has no name
  70741. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  70742. newVal = defaults(newVal, original);
  70743. shouldDeleteName && delete newVal.name;
  70744. return newVal;
  70745. } else {
  70746. return newVal;
  70747. }
  70748. });
  70749. } // TODO: SELF REGISTERED.
  70750. registerAction({
  70751. type: 'changeDataView',
  70752. event: 'dataViewChanged',
  70753. update: 'prepareAndUpdate'
  70754. }, function (payload, ecModel) {
  70755. var newSeriesOptList = [];
  70756. each(payload.newOption.series, function (seriesOpt) {
  70757. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  70758. if (!seriesModel) {
  70759. // New created series
  70760. // Geuss the series type
  70761. newSeriesOptList.push(extend({
  70762. // Default is scatter
  70763. type: 'scatter'
  70764. }, seriesOpt));
  70765. } else {
  70766. var originalData = seriesModel.get('data');
  70767. newSeriesOptList.push({
  70768. name: seriesOpt.name,
  70769. data: tryMergeDataOption(seriesOpt.data, originalData)
  70770. });
  70771. }
  70772. });
  70773. ecModel.mergeOption(defaults({
  70774. series: newSeriesOptList
  70775. }, payload.newOption));
  70776. });
  70777. var each$9 = each;
  70778. var inner$f = makeInner();
  70779. /**
  70780. * @param ecModel
  70781. * @param newSnapshot key is dataZoomId
  70782. */
  70783. function push(ecModel, newSnapshot) {
  70784. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  70785. // complete an range with current range.
  70786. each$9(newSnapshot, function (batchItem, dataZoomId) {
  70787. var i = storedSnapshots.length - 1;
  70788. for (; i >= 0; i--) {
  70789. var snapshot = storedSnapshots[i];
  70790. if (snapshot[dataZoomId]) {
  70791. break;
  70792. }
  70793. }
  70794. if (i < 0) {
  70795. // No origin range set, create one by current range.
  70796. var dataZoomModel = ecModel.queryComponents({
  70797. mainType: 'dataZoom',
  70798. subType: 'select',
  70799. id: dataZoomId
  70800. })[0];
  70801. if (dataZoomModel) {
  70802. var percentRange = dataZoomModel.getPercentRange();
  70803. storedSnapshots[0][dataZoomId] = {
  70804. dataZoomId: dataZoomId,
  70805. start: percentRange[0],
  70806. end: percentRange[1]
  70807. };
  70808. }
  70809. }
  70810. });
  70811. storedSnapshots.push(newSnapshot);
  70812. }
  70813. function pop(ecModel) {
  70814. var storedSnapshots = getStoreSnapshots(ecModel);
  70815. var head = storedSnapshots[storedSnapshots.length - 1];
  70816. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  70817. var snapshot = {};
  70818. each$9(head, function (batchItem, dataZoomId) {
  70819. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  70820. batchItem = storedSnapshots[i][dataZoomId];
  70821. if (batchItem) {
  70822. snapshot[dataZoomId] = batchItem;
  70823. break;
  70824. }
  70825. }
  70826. });
  70827. return snapshot;
  70828. }
  70829. function clear$1(ecModel) {
  70830. inner$f(ecModel).snapshots = null;
  70831. }
  70832. function count(ecModel) {
  70833. return getStoreSnapshots(ecModel).length;
  70834. }
  70835. /**
  70836. * History length of each dataZoom may be different.
  70837. * this._history[0] is used to store origin range.
  70838. */
  70839. function getStoreSnapshots(ecModel) {
  70840. var store = inner$f(ecModel);
  70841. if (!store.snapshots) {
  70842. store.snapshots = [{}];
  70843. }
  70844. return store.snapshots;
  70845. }
  70846. var RestoreOption =
  70847. /** @class */
  70848. function (_super) {
  70849. __extends(RestoreOption, _super);
  70850. function RestoreOption() {
  70851. return _super !== null && _super.apply(this, arguments) || this;
  70852. }
  70853. RestoreOption.prototype.onclick = function (ecModel, api) {
  70854. clear$1(ecModel);
  70855. api.dispatchAction({
  70856. type: 'restore',
  70857. from: this.uid
  70858. });
  70859. };
  70860. RestoreOption.getDefaultOption = function (ecModel) {
  70861. var defaultOption = {
  70862. show: true,
  70863. // eslint-disable-next-line
  70864. 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',
  70865. title: ecModel.getLocaleModel().get(['toolbox', 'restore', 'title'])
  70866. };
  70867. return defaultOption;
  70868. };
  70869. return RestoreOption;
  70870. }(ToolboxFeature); // TODO: SELF REGISTERED.
  70871. registerAction({
  70872. type: 'restore',
  70873. event: 'restore',
  70874. update: 'prepareAndUpdate'
  70875. }, function (payload, ecModel) {
  70876. ecModel.resetOption('recreate');
  70877. });
  70878. // how to genarialize to more coordinate systems.
  70879. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  70880. var BrushTargetManager =
  70881. /** @class */
  70882. function () {
  70883. /**
  70884. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  70885. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  70886. * @param opt.include include coordinate system types.
  70887. */
  70888. function BrushTargetManager(finder, ecModel, opt) {
  70889. var _this = this;
  70890. this._targetInfoList = [];
  70891. var foundCpts = parseFinder$1(ecModel, finder);
  70892. each(targetInfoBuilders, function (builder, type) {
  70893. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  70894. builder(foundCpts, _this._targetInfoList);
  70895. }
  70896. });
  70897. }
  70898. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  70899. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70900. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  70901. if (!area.coordRange) {
  70902. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  70903. // rebuild range by coordRange accrately, which may bring trouble when
  70904. // brushing only one item. So we use __rangeOffset to rebuilding range
  70905. // by coordRange. And this it only used in brush component so it is no
  70906. // need to be adapted to coordRanges.
  70907. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  70908. area.__rangeOffset = {
  70909. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  70910. xyMinMax: result.xyMinMax
  70911. };
  70912. }
  70913. });
  70914. return areas;
  70915. };
  70916. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  70917. each(areas, function (area) {
  70918. var targetInfo = this.findTargetInfo(area, ecModel);
  70919. if (targetInfo && targetInfo !== true) {
  70920. each(targetInfo.coordSyses, function (coordSys) {
  70921. var result = coordConvert[area.brushType](1, coordSys, area.range, true);
  70922. cb(area, result.values, coordSys, ecModel);
  70923. });
  70924. }
  70925. }, this);
  70926. };
  70927. /**
  70928. * the `areas` is `BrushModel.areas`.
  70929. * Called in layout stage.
  70930. * convert `area.coordRange` to global range and set panelId to `area.range`.
  70931. */
  70932. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  70933. each(areas, function (area) {
  70934. var targetInfo = this.findTargetInfo(area, ecModel);
  70935. if ("development" !== 'production') {
  70936. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  70937. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  70938. }
  70939. area.range = area.range || []; // convert coordRange to global range and set panelId.
  70940. if (targetInfo && targetInfo !== true) {
  70941. area.panelId = targetInfo.panelId; // (1) area.range should always be calculate from coordRange but does
  70942. // not keep its original value, for the sake of the dataZoom scenario,
  70943. // where area.coordRange remains unchanged but area.range may be changed.
  70944. // (2) Only support converting one coordRange to pixel range in brush
  70945. // component. So do not consider `coordRanges`.
  70946. // (3) About __rangeOffset, see comment above.
  70947. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  70948. var rangeOffset = area.__rangeOffset;
  70949. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  70950. }
  70951. }, this);
  70952. };
  70953. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  70954. return map(this._targetInfoList, function (targetInfo) {
  70955. var rect = targetInfo.getPanelRect();
  70956. return {
  70957. panelId: targetInfo.panelId,
  70958. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  70959. clipPath: makeRectPanelClipPath(rect),
  70960. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  70961. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  70962. };
  70963. });
  70964. };
  70965. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  70966. // Check whether area is bound in coord, and series do not belong to that coord.
  70967. // If do not do this check, some brush (like lineX) will controll all axes.
  70968. var targetInfo = this.findTargetInfo(area, ecModel);
  70969. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  70970. };
  70971. /**
  70972. * If return Object, a coord found.
  70973. * If return true, global found.
  70974. * Otherwise nothing found.
  70975. */
  70976. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  70977. var targetInfoList = this._targetInfoList;
  70978. var foundCpts = parseFinder$1(ecModel, area);
  70979. for (var i = 0; i < targetInfoList.length; i++) {
  70980. var targetInfo = targetInfoList[i];
  70981. var areaPanelId = area.panelId;
  70982. if (areaPanelId) {
  70983. if (targetInfo.panelId === areaPanelId) {
  70984. return targetInfo;
  70985. }
  70986. } else {
  70987. for (var j = 0; j < targetInfoMatchers.length; j++) {
  70988. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  70989. return targetInfo;
  70990. }
  70991. }
  70992. }
  70993. }
  70994. return true;
  70995. };
  70996. return BrushTargetManager;
  70997. }();
  70998. function formatMinMax(minMax) {
  70999. minMax[0] > minMax[1] && minMax.reverse();
  71000. return minMax;
  71001. }
  71002. function parseFinder$1(ecModel, finder) {
  71003. return parseFinder(ecModel, finder, {
  71004. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  71005. });
  71006. }
  71007. var targetInfoBuilders = {
  71008. grid: function (foundCpts, targetInfoList) {
  71009. var xAxisModels = foundCpts.xAxisModels;
  71010. var yAxisModels = foundCpts.yAxisModels;
  71011. var gridModels = foundCpts.gridModels; // Remove duplicated.
  71012. var gridModelMap = createHashMap();
  71013. var xAxesHas = {};
  71014. var yAxesHas = {};
  71015. if (!xAxisModels && !yAxisModels && !gridModels) {
  71016. return;
  71017. }
  71018. each(xAxisModels, function (axisModel) {
  71019. var gridModel = axisModel.axis.grid.model;
  71020. gridModelMap.set(gridModel.id, gridModel);
  71021. xAxesHas[gridModel.id] = true;
  71022. });
  71023. each(yAxisModels, function (axisModel) {
  71024. var gridModel = axisModel.axis.grid.model;
  71025. gridModelMap.set(gridModel.id, gridModel);
  71026. yAxesHas[gridModel.id] = true;
  71027. });
  71028. each(gridModels, function (gridModel) {
  71029. gridModelMap.set(gridModel.id, gridModel);
  71030. xAxesHas[gridModel.id] = true;
  71031. yAxesHas[gridModel.id] = true;
  71032. });
  71033. gridModelMap.each(function (gridModel) {
  71034. var grid = gridModel.coordinateSystem;
  71035. var cartesians = [];
  71036. each(grid.getCartesians(), function (cartesian, index) {
  71037. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  71038. cartesians.push(cartesian);
  71039. }
  71040. });
  71041. targetInfoList.push({
  71042. panelId: 'grid--' + gridModel.id,
  71043. gridModel: gridModel,
  71044. coordSysModel: gridModel,
  71045. // Use the first one as the representitive coordSys.
  71046. coordSys: cartesians[0],
  71047. coordSyses: cartesians,
  71048. getPanelRect: panelRectBuilders.grid,
  71049. xAxisDeclared: xAxesHas[gridModel.id],
  71050. yAxisDeclared: yAxesHas[gridModel.id]
  71051. });
  71052. });
  71053. },
  71054. geo: function (foundCpts, targetInfoList) {
  71055. each(foundCpts.geoModels, function (geoModel) {
  71056. var coordSys = geoModel.coordinateSystem;
  71057. targetInfoList.push({
  71058. panelId: 'geo--' + geoModel.id,
  71059. geoModel: geoModel,
  71060. coordSysModel: geoModel,
  71061. coordSys: coordSys,
  71062. coordSyses: [coordSys],
  71063. getPanelRect: panelRectBuilders.geo
  71064. });
  71065. });
  71066. }
  71067. };
  71068. var targetInfoMatchers = [// grid
  71069. function (foundCpts, targetInfo) {
  71070. var xAxisModel = foundCpts.xAxisModel;
  71071. var yAxisModel = foundCpts.yAxisModel;
  71072. var gridModel = foundCpts.gridModel;
  71073. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  71074. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  71075. return gridModel && gridModel === targetInfo.gridModel;
  71076. }, // geo
  71077. function (foundCpts, targetInfo) {
  71078. var geoModel = foundCpts.geoModel;
  71079. return geoModel && geoModel === targetInfo.geoModel;
  71080. }];
  71081. var panelRectBuilders = {
  71082. grid: function () {
  71083. // grid is not Transformable.
  71084. return this.coordSys.master.getRect().clone();
  71085. },
  71086. geo: function () {
  71087. var coordSys = this.coordSys;
  71088. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  71089. rect.applyTransform(getTransform(coordSys));
  71090. return rect;
  71091. }
  71092. };
  71093. var coordConvert = {
  71094. lineX: curry(axisConvert, 0),
  71095. lineY: curry(axisConvert, 1),
  71096. rect: function (to, coordSys, rangeOrCoordRange, clamp) {
  71097. var xminymin = to ? coordSys.pointToData([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]], clamp);
  71098. var xmaxymax = to ? coordSys.pointToData([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp) : coordSys.dataToPoint([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]], clamp);
  71099. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  71100. return {
  71101. values: values,
  71102. xyMinMax: values
  71103. };
  71104. },
  71105. polygon: function (to, coordSys, rangeOrCoordRange, clamp) {
  71106. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  71107. var values = map(rangeOrCoordRange, function (item) {
  71108. var p = to ? coordSys.pointToData(item, clamp) : coordSys.dataToPoint(item, clamp);
  71109. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  71110. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  71111. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  71112. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  71113. return p;
  71114. });
  71115. return {
  71116. values: values,
  71117. xyMinMax: xyMinMax
  71118. };
  71119. }
  71120. };
  71121. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  71122. if ("development" !== 'production') {
  71123. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  71124. }
  71125. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  71126. var values = formatMinMax(map([0, 1], function (i) {
  71127. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]), true) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  71128. }));
  71129. var xyMinMax = [];
  71130. xyMinMax[axisNameIndex] = values;
  71131. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  71132. return {
  71133. values: values,
  71134. xyMinMax: xyMinMax
  71135. };
  71136. }
  71137. var diffProcessor = {
  71138. lineX: curry(axisDiffProcessor, 0),
  71139. lineY: curry(axisDiffProcessor, 1),
  71140. rect: function (values, refer, scales) {
  71141. 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]]];
  71142. },
  71143. polygon: function (values, refer, scales) {
  71144. return map(values, function (item, idx) {
  71145. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  71146. });
  71147. }
  71148. };
  71149. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  71150. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  71151. } // We have to process scale caused by dataZoom manually,
  71152. // although it might be not accurate.
  71153. // Return [0~1, 0~1]
  71154. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  71155. var sizeCurr = getSize$1(xyMinMaxCurr);
  71156. var sizeOrigin = getSize$1(xyMinMaxOrigin);
  71157. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  71158. isNaN(scales[0]) && (scales[0] = 1);
  71159. isNaN(scales[1]) && (scales[1] = 1);
  71160. return scales;
  71161. }
  71162. function getSize$1(xyMinMax) {
  71163. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  71164. }
  71165. var each$a = each;
  71166. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  71167. var DataZoomFeature =
  71168. /** @class */
  71169. function (_super) {
  71170. __extends(DataZoomFeature, _super);
  71171. function DataZoomFeature() {
  71172. return _super !== null && _super.apply(this, arguments) || this;
  71173. }
  71174. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  71175. if (!this._brushController) {
  71176. this._brushController = new BrushController(api.getZr());
  71177. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  71178. }
  71179. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  71180. updateBackBtnStatus(featureModel, ecModel);
  71181. };
  71182. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  71183. handlers$1[type].call(this);
  71184. };
  71185. DataZoomFeature.prototype.remove = function (ecModel, api) {
  71186. this._brushController && this._brushController.unmount();
  71187. };
  71188. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  71189. this._brushController && this._brushController.dispose();
  71190. };
  71191. DataZoomFeature.prototype._onBrush = function (eventParam) {
  71192. var areas = eventParam.areas;
  71193. if (!eventParam.isEnd || !areas.length) {
  71194. return;
  71195. }
  71196. var snapshot = {};
  71197. var ecModel = this.ecModel;
  71198. this._brushController.updateCovers([]); // remove cover
  71199. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  71200. include: ['grid']
  71201. });
  71202. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  71203. if (coordSys.type !== 'cartesian2d') {
  71204. return;
  71205. }
  71206. var brushType = area.brushType;
  71207. if (brushType === 'rect') {
  71208. setBatch('x', coordSys, coordRange[0]);
  71209. setBatch('y', coordSys, coordRange[1]);
  71210. } else {
  71211. setBatch({
  71212. lineX: 'x',
  71213. lineY: 'y'
  71214. }[brushType], coordSys, coordRange);
  71215. }
  71216. });
  71217. push(ecModel, snapshot);
  71218. this._dispatchZoomAction(snapshot);
  71219. function setBatch(dimName, coordSys, minMax) {
  71220. var axis = coordSys.getAxis(dimName);
  71221. var axisModel = axis.model;
  71222. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  71223. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  71224. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  71225. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  71226. }
  71227. dataZoomModel && (snapshot[dataZoomModel.id] = {
  71228. dataZoomId: dataZoomModel.id,
  71229. startValue: minMax[0],
  71230. endValue: minMax[1]
  71231. });
  71232. }
  71233. function findDataZoom(dimName, axisModel, ecModel) {
  71234. var found;
  71235. ecModel.eachComponent({
  71236. mainType: 'dataZoom',
  71237. subType: 'select'
  71238. }, function (dzModel) {
  71239. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  71240. has && (found = dzModel);
  71241. });
  71242. return found;
  71243. }
  71244. };
  71245. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  71246. var batch = []; // Convert from hash map to array.
  71247. each$a(snapshot, function (batchItem, dataZoomId) {
  71248. batch.push(clone(batchItem));
  71249. });
  71250. batch.length && this.api.dispatchAction({
  71251. type: 'dataZoom',
  71252. from: this.uid,
  71253. batch: batch
  71254. });
  71255. };
  71256. DataZoomFeature.getDefaultOption = function (ecModel) {
  71257. var defaultOption = {
  71258. show: true,
  71259. filterMode: 'filter',
  71260. // Icon group
  71261. icon: {
  71262. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  71263. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  71264. },
  71265. // `zoom`, `back`
  71266. title: ecModel.getLocaleModel().get(['toolbox', 'dataZoom', 'title']),
  71267. brushStyle: {
  71268. borderWidth: 0,
  71269. color: 'rgba(210,219,238,0.2)'
  71270. }
  71271. };
  71272. return defaultOption;
  71273. };
  71274. return DataZoomFeature;
  71275. }(ToolboxFeature);
  71276. var handlers$1 = {
  71277. zoom: function () {
  71278. var nextActive = !this._isZoomActive;
  71279. this.api.dispatchAction({
  71280. type: 'takeGlobalCursor',
  71281. key: 'dataZoomSelect',
  71282. dataZoomSelectActive: nextActive
  71283. });
  71284. },
  71285. back: function () {
  71286. this._dispatchZoomAction(pop(this.ecModel));
  71287. }
  71288. };
  71289. function makeAxisFinder(dzFeatureModel) {
  71290. var setting = {
  71291. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  71292. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  71293. xAxisId: dzFeatureModel.get('xAxisId', true),
  71294. yAxisId: dzFeatureModel.get('yAxisId', true)
  71295. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  71296. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  71297. // Some old cases set like this below to close yAxis control but leave xAxis control:
  71298. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  71299. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  71300. setting.xAxisIndex = 'all';
  71301. }
  71302. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  71303. setting.yAxisIndex = 'all';
  71304. }
  71305. return setting;
  71306. }
  71307. function updateBackBtnStatus(featureModel, ecModel) {
  71308. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  71309. }
  71310. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  71311. var zoomActive = view._isZoomActive;
  71312. if (payload && payload.type === 'takeGlobalCursor') {
  71313. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  71314. }
  71315. view._isZoomActive = zoomActive;
  71316. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  71317. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  71318. include: ['grid']
  71319. });
  71320. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  71321. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  71322. });
  71323. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  71324. brushType: 'auto',
  71325. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  71326. } : false);
  71327. }
  71328. registerInternalOptionCreator('dataZoom', function (ecModel) {
  71329. var toolboxModel = ecModel.getComponent('toolbox', 0);
  71330. var featureDataZoomPath = ['feature', 'dataZoom'];
  71331. if (!toolboxModel || toolboxModel.get(featureDataZoomPath) == null) {
  71332. return;
  71333. }
  71334. var dzFeatureModel = toolboxModel.getModel(featureDataZoomPath);
  71335. var dzOptions = [];
  71336. var finder = makeAxisFinder(dzFeatureModel);
  71337. var finderResult = parseFinder(ecModel, finder);
  71338. each$a(finderResult.xAxisModels, function (axisModel) {
  71339. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  71340. });
  71341. each$a(finderResult.yAxisModels, function (axisModel) {
  71342. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  71343. });
  71344. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  71345. var axisIndex = axisModel.componentIndex;
  71346. var newOpt = {
  71347. type: 'select',
  71348. $fromToolbox: true,
  71349. // Default to be filter
  71350. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  71351. // Id for merge mapping.
  71352. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  71353. };
  71354. newOpt[axisIndexPropName] = axisIndex;
  71355. dzOptions.push(newOpt);
  71356. }
  71357. return dzOptions;
  71358. });
  71359. function install$z(registers) {
  71360. registers.registerComponentModel(ToolboxModel);
  71361. registers.registerComponentView(ToolboxView);
  71362. registerFeature('saveAsImage', SaveAsImage);
  71363. registerFeature('magicType', MagicType);
  71364. registerFeature('dataView', DataView);
  71365. registerFeature('dataZoom', DataZoomFeature);
  71366. registerFeature('restore', RestoreOption);
  71367. use(install$y);
  71368. }
  71369. var TooltipModel =
  71370. /** @class */
  71371. function (_super) {
  71372. __extends(TooltipModel, _super);
  71373. function TooltipModel() {
  71374. var _this = _super !== null && _super.apply(this, arguments) || this;
  71375. _this.type = TooltipModel.type;
  71376. return _this;
  71377. }
  71378. TooltipModel.type = 'tooltip';
  71379. TooltipModel.dependencies = ['axisPointer'];
  71380. TooltipModel.defaultOption = {
  71381. // zlevel: 0,
  71382. z: 60,
  71383. show: true,
  71384. // tooltip main content
  71385. showContent: true,
  71386. // 'trigger' only works on coordinate system.
  71387. // 'item' | 'axis' | 'none'
  71388. trigger: 'item',
  71389. // 'click' | 'mousemove' | 'none'
  71390. triggerOn: 'mousemove|click',
  71391. alwaysShowContent: false,
  71392. displayMode: 'single',
  71393. renderMode: 'auto',
  71394. // whether restraint content inside viewRect.
  71395. // If renderMode: 'richText', default true.
  71396. // If renderMode: 'html', defaut false (for backward compat).
  71397. confine: null,
  71398. showDelay: 0,
  71399. hideDelay: 100,
  71400. // Animation transition time, unit is second
  71401. transitionDuration: 0.4,
  71402. enterable: false,
  71403. backgroundColor: '#fff',
  71404. // box shadow
  71405. shadowBlur: 10,
  71406. shadowColor: 'rgba(0, 0, 0, .2)',
  71407. shadowOffsetX: 1,
  71408. shadowOffsetY: 2,
  71409. // tooltip border radius, unit is px, default is 4
  71410. borderRadius: 4,
  71411. // tooltip border width, unit is px, default is 0 (no border)
  71412. borderWidth: 1,
  71413. // Tooltip inside padding, default is 5 for all direction
  71414. // Array is allowed to set up, right, bottom, left, same with css
  71415. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  71416. padding: null,
  71417. // Extra css text
  71418. extraCssText: '',
  71419. // axis indicator, trigger by axis
  71420. axisPointer: {
  71421. // default is line
  71422. // legal values: 'line' | 'shadow' | 'cross'
  71423. type: 'line',
  71424. // Valid when type is line, appoint tooltip line locate on which line. Optional
  71425. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  71426. // default is 'auto', chose the axis which type is category.
  71427. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  71428. axis: 'auto',
  71429. animation: 'auto',
  71430. animationDurationUpdate: 200,
  71431. animationEasingUpdate: 'exponentialOut',
  71432. crossStyle: {
  71433. color: '#999',
  71434. width: 1,
  71435. type: 'dashed',
  71436. // TODO formatter
  71437. textStyle: {}
  71438. } // lineStyle and shadowStyle should not be specified here,
  71439. // otherwise it will always override those styles on option.axisPointer.
  71440. },
  71441. textStyle: {
  71442. color: '#666',
  71443. fontSize: 14
  71444. }
  71445. };
  71446. return TooltipModel;
  71447. }(ComponentModel);
  71448. /* global document */
  71449. function shouldTooltipConfine(tooltipModel) {
  71450. var confineOption = tooltipModel.get('confine');
  71451. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  71452. : tooltipModel.get('renderMode') === 'richText';
  71453. }
  71454. function testStyle(styleProps) {
  71455. if (!env.domSupported) {
  71456. return;
  71457. }
  71458. var style = document.documentElement.style;
  71459. for (var i = 0, len = styleProps.length; i < len; i++) {
  71460. if (styleProps[i] in style) {
  71461. return styleProps[i];
  71462. }
  71463. }
  71464. }
  71465. var TRANSFORM_VENDOR = testStyle(['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
  71466. var TRANSITION_VENDOR = testStyle(['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
  71467. function toCSSVendorPrefix(styleVendor, styleProp) {
  71468. if (!styleVendor) {
  71469. return styleProp;
  71470. }
  71471. styleProp = toCamelCase(styleProp, true);
  71472. var idx = styleVendor.indexOf(styleProp);
  71473. styleVendor = idx === -1 ? styleProp : "-" + styleVendor.slice(0, idx) + "-" + styleProp;
  71474. return styleVendor.toLowerCase();
  71475. }
  71476. function getComputedStyle(el, style) {
  71477. var stl = el.currentStyle || document.defaultView && document.defaultView.getComputedStyle(el);
  71478. return stl ? style ? stl[style] : stl : null;
  71479. }
  71480. /* global document, window */
  71481. var CSS_TRANSITION_VENDOR = toCSSVendorPrefix(TRANSITION_VENDOR, 'transition');
  71482. var CSS_TRANSFORM_VENDOR = toCSSVendorPrefix(TRANSFORM_VENDOR, 'transform'); // eslint-disable-next-line
  71483. var gCssText = "position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;" + (env.transform3dSupported ? 'will-change:transform;' : '');
  71484. function mirrorPos(pos) {
  71485. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  71486. return pos;
  71487. }
  71488. function assembleArrow(tooltipModel, borderColor, arrowPosition) {
  71489. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  71490. return '';
  71491. }
  71492. var backgroundColor = tooltipModel.get('backgroundColor');
  71493. var borderWidth = tooltipModel.get('borderWidth');
  71494. borderColor = convertToColorString(borderColor);
  71495. var arrowPos = mirrorPos(arrowPosition);
  71496. var arrowSize = Math.max(Math.round(borderWidth) * 1.5, 6);
  71497. var positionStyle = '';
  71498. var transformStyle = CSS_TRANSFORM_VENDOR + ':';
  71499. var rotateDeg;
  71500. if (indexOf(['left', 'right'], arrowPos) > -1) {
  71501. positionStyle += 'top:50%';
  71502. transformStyle += "translateY(-50%) rotate(" + (rotateDeg = arrowPos === 'left' ? -225 : -45) + "deg)";
  71503. } else {
  71504. positionStyle += 'left:50%';
  71505. transformStyle += "translateX(-50%) rotate(" + (rotateDeg = arrowPos === 'top' ? 225 : 45) + "deg)";
  71506. }
  71507. var rotateRadian = rotateDeg * Math.PI / 180;
  71508. var arrowWH = arrowSize + borderWidth;
  71509. var rotatedWH = arrowWH * Math.abs(Math.cos(rotateRadian)) + arrowWH * Math.abs(Math.sin(rotateRadian));
  71510. var arrowOffset = Math.round(((rotatedWH - Math.SQRT2 * borderWidth) / 2 + Math.SQRT2 * borderWidth - (rotatedWH - arrowWH) / 2) * 100) / 100;
  71511. positionStyle += ";" + arrowPos + ":-" + arrowOffset + "px";
  71512. var borderStyle = borderColor + " solid " + borderWidth + "px;";
  71513. var styleCss = ["position:absolute;width:" + arrowSize + "px;height:" + arrowSize + "px;z-index:-1;", positionStyle + ";" + transformStyle + ";", "border-bottom:" + borderStyle, "border-right:" + borderStyle, "background-color:" + backgroundColor + ";"];
  71514. return "<div style=\"" + styleCss.join('') + "\"></div>";
  71515. }
  71516. function assembleTransition(duration, onlyFade) {
  71517. var transitionCurve = 'cubic-bezier(0.23,1,0.32,1)';
  71518. var transitionOption = " " + duration / 2 + "s " + transitionCurve;
  71519. var transitionText = "opacity" + transitionOption + ",visibility" + transitionOption;
  71520. if (!onlyFade) {
  71521. transitionOption = " " + duration + "s " + transitionCurve;
  71522. transitionText += env.transformSupported ? "," + CSS_TRANSFORM_VENDOR + transitionOption : ",left" + transitionOption + ",top" + transitionOption;
  71523. }
  71524. return CSS_TRANSITION_VENDOR + ':' + transitionText;
  71525. }
  71526. function assembleTransform(x, y, toString) {
  71527. // If using float on style, the final width of the dom might
  71528. // keep changing slightly while mouse move. So `toFixed(0)` them.
  71529. var x0 = x.toFixed(0) + 'px';
  71530. var y0 = y.toFixed(0) + 'px'; // not support transform, use `left` and `top` instead.
  71531. if (!env.transformSupported) {
  71532. return toString ? "top:" + y0 + ";left:" + x0 + ";" : [['top', y0], ['left', x0]];
  71533. } // support transform
  71534. var is3d = env.transform3dSupported;
  71535. var translate = "translate" + (is3d ? '3d' : '') + "(" + x0 + "," + y0 + (is3d ? ',0' : '') + ")";
  71536. return toString ? 'top:0;left:0;' + CSS_TRANSFORM_VENDOR + ':' + translate + ';' : [['top', 0], ['left', 0], [TRANSFORM_VENDOR, translate]];
  71537. }
  71538. /**
  71539. * @param {Object} textStyle
  71540. * @return {string}
  71541. * @inner
  71542. */
  71543. function assembleFont(textStyleModel) {
  71544. var cssText = [];
  71545. var fontSize = textStyleModel.get('fontSize');
  71546. var color = textStyleModel.getTextColor();
  71547. color && cssText.push('color:' + color);
  71548. cssText.push('font:' + textStyleModel.getFont());
  71549. fontSize // @ts-ignore, leave it to the tooltip refactor.
  71550. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  71551. var shadowColor = textStyleModel.get('textShadowColor');
  71552. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  71553. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  71554. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  71555. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  71556. each(['decoration', 'align'], function (name) {
  71557. var val = textStyleModel.get(name);
  71558. val && cssText.push('text-' + name + ':' + val);
  71559. });
  71560. return cssText.join(';');
  71561. }
  71562. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  71563. var cssText = [];
  71564. var transitionDuration = tooltipModel.get('transitionDuration');
  71565. var backgroundColor = tooltipModel.get('backgroundColor');
  71566. var shadowBlur = tooltipModel.get('shadowBlur');
  71567. var shadowColor = tooltipModel.get('shadowColor');
  71568. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  71569. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  71570. var textStyleModel = tooltipModel.getModel('textStyle');
  71571. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  71572. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  71573. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  71574. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  71575. if (backgroundColor) {
  71576. cssText.push('background-color:' + backgroundColor);
  71577. } // Border style
  71578. each(['width', 'color', 'radius'], function (name) {
  71579. var borderName = 'border-' + name;
  71580. var camelCase = toCamelCase(borderName);
  71581. var val = tooltipModel.get(camelCase);
  71582. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  71583. }); // Text style
  71584. cssText.push(assembleFont(textStyleModel)); // Padding
  71585. if (padding != null) {
  71586. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  71587. }
  71588. return cssText.join(';') + ';';
  71589. } // If not able to make, do not modify the input `out`.
  71590. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  71591. var zrPainter = zr && zr.painter;
  71592. if (appendToBody) {
  71593. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  71594. if (zrViewportRoot) {
  71595. // Some APPs might use scale on body, so we support CSS transform here.
  71596. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  71597. }
  71598. } else {
  71599. out[0] = zrX;
  71600. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  71601. // the sibling of canvas root. So padding of ec container
  71602. // should be considered here.
  71603. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  71604. if (viewportRootOffset) {
  71605. out[0] += viewportRootOffset.offsetLeft;
  71606. out[1] += viewportRootOffset.offsetTop;
  71607. }
  71608. }
  71609. out[2] = out[0] / zr.getWidth();
  71610. out[3] = out[1] / zr.getHeight();
  71611. }
  71612. var TooltipHTMLContent =
  71613. /** @class */
  71614. function () {
  71615. function TooltipHTMLContent(container, api, opt) {
  71616. this._show = false;
  71617. this._styleCoord = [0, 0, 0, 0];
  71618. this._enterable = true;
  71619. this._alwaysShowContent = false;
  71620. this._firstShow = true;
  71621. this._longHide = true;
  71622. if (env.wxa) {
  71623. return null;
  71624. }
  71625. var el = document.createElement('div'); // TODO: TYPE
  71626. el.domBelongToZr = true;
  71627. this.el = el;
  71628. var zr = this._zr = api.getZr();
  71629. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  71630. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  71631. if (appendToBody) {
  71632. document.body.appendChild(el);
  71633. } else {
  71634. container.appendChild(el);
  71635. }
  71636. this._container = container; // FIXME
  71637. // Is it needed to trigger zr event manually if
  71638. // the browser do not support `pointer-events: none`.
  71639. var self = this;
  71640. el.onmouseenter = function () {
  71641. // clear the timeout in hideLater and keep showing tooltip
  71642. if (self._enterable) {
  71643. clearTimeout(self._hideTimeout);
  71644. self._show = true;
  71645. }
  71646. self._inContent = true;
  71647. };
  71648. el.onmousemove = function (e) {
  71649. e = e || window.event;
  71650. if (!self._enterable) {
  71651. // `pointer-events: none` is set to tooltip content div
  71652. // if `enterable` is set as `false`, and `el.onmousemove`
  71653. // can not be triggered. But in browser that do not
  71654. // support `pointer-events`, we need to do this:
  71655. // Try trigger zrender event to avoid mouse
  71656. // in and out shape too frequently
  71657. var handler = zr.handler;
  71658. var zrViewportRoot = zr.painter.getViewportRoot();
  71659. normalizeEvent(zrViewportRoot, e, true);
  71660. handler.dispatch('mousemove', e);
  71661. }
  71662. };
  71663. el.onmouseleave = function () {
  71664. // set `_inContent` to `false` before `hideLater`
  71665. self._inContent = false;
  71666. if (self._enterable) {
  71667. if (self._show) {
  71668. self.hideLater(self._hideDelay);
  71669. }
  71670. }
  71671. };
  71672. }
  71673. /**
  71674. * Update when tooltip is rendered
  71675. */
  71676. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  71677. // FIXME
  71678. // Move this logic to ec main?
  71679. var container = this._container;
  71680. var position = getComputedStyle(container, 'position');
  71681. var domStyle = container.style;
  71682. if (domStyle.position !== 'absolute' && position !== 'absolute') {
  71683. domStyle.position = 'relative';
  71684. } // move tooltip if chart resized
  71685. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71686. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71687. this._alwaysShowContent = alwaysShowContent; // update className
  71688. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  71689. // PENDING
  71690. // this.hide();
  71691. };
  71692. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  71693. clearTimeout(this._hideTimeout);
  71694. clearTimeout(this._longHideTimeout);
  71695. var el = this.el;
  71696. var style = el.style;
  71697. var styleCoord = this._styleCoord;
  71698. if (!el.innerHTML) {
  71699. style.display = 'none';
  71700. } else {
  71701. style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // initial transform
  71702. + 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
  71703. // triggered by canvas, and cause some unexpectable result like dragging
  71704. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  71705. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  71706. // scenario.
  71707. + (";pointer-events:" + (this._enterable ? 'auto' : 'none'));
  71708. }
  71709. this._show = true;
  71710. this._firstShow = false;
  71711. this._longHide = false;
  71712. };
  71713. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  71714. var el = this.el;
  71715. if (content == null) {
  71716. el.innerHTML = '';
  71717. return;
  71718. }
  71719. var arrow = '';
  71720. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  71721. arrow = assembleArrow(tooltipModel, borderColor, arrowPosition);
  71722. }
  71723. if (isString(content)) {
  71724. el.innerHTML = content + arrow;
  71725. } else if (content) {
  71726. // Clear previous
  71727. el.innerHTML = '';
  71728. if (!isArray(content)) {
  71729. content = [content];
  71730. }
  71731. for (var i = 0; i < content.length; i++) {
  71732. if (isDom(content[i]) && content[i].parentNode !== el) {
  71733. el.appendChild(content[i]);
  71734. }
  71735. } // no arrow if empty
  71736. if (arrow && el.childNodes.length) {
  71737. // no need to create a new parent element, but it's not supported by IE 10 and older.
  71738. // const arrowEl = document.createRange().createContextualFragment(arrow);
  71739. var arrowEl = document.createElement('div');
  71740. arrowEl.innerHTML = arrow;
  71741. el.appendChild(arrowEl);
  71742. }
  71743. }
  71744. };
  71745. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  71746. this._enterable = enterable;
  71747. };
  71748. TooltipHTMLContent.prototype.getSize = function () {
  71749. var el = this.el;
  71750. return [el.offsetWidth, el.offsetHeight];
  71751. };
  71752. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  71753. var styleCoord = this._styleCoord;
  71754. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  71755. if (styleCoord[0] != null && styleCoord[1] != null) {
  71756. var style_1 = this.el.style;
  71757. var transforms = assembleTransform(styleCoord[0], styleCoord[1]);
  71758. each(transforms, function (transform) {
  71759. style_1[transform[0]] = transform[1];
  71760. });
  71761. }
  71762. };
  71763. /**
  71764. * when `alwaysShowContent` is true,
  71765. * move the tooltip after chart resized
  71766. */
  71767. TooltipHTMLContent.prototype._moveIfResized = function () {
  71768. // The ratio of left to width
  71769. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71770. var ratioY = this._styleCoord[3];
  71771. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71772. };
  71773. TooltipHTMLContent.prototype.hide = function () {
  71774. var _this = this;
  71775. var style = this.el.style;
  71776. style.visibility = 'hidden';
  71777. style.opacity = '0';
  71778. env.transform3dSupported && (style.willChange = '');
  71779. this._show = false;
  71780. this._longHideTimeout = setTimeout(function () {
  71781. return _this._longHide = true;
  71782. }, 500);
  71783. };
  71784. TooltipHTMLContent.prototype.hideLater = function (time) {
  71785. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71786. if (time) {
  71787. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71788. this._show = false;
  71789. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71790. } else {
  71791. this.hide();
  71792. }
  71793. }
  71794. };
  71795. TooltipHTMLContent.prototype.isShow = function () {
  71796. return this._show;
  71797. };
  71798. TooltipHTMLContent.prototype.dispose = function () {
  71799. this.el.parentNode.removeChild(this.el);
  71800. };
  71801. return TooltipHTMLContent;
  71802. }();
  71803. var TooltipRichContent =
  71804. /** @class */
  71805. function () {
  71806. function TooltipRichContent(api) {
  71807. this._show = false;
  71808. this._styleCoord = [0, 0, 0, 0];
  71809. this._alwaysShowContent = false;
  71810. this._enterable = true;
  71811. this._zr = api.getZr();
  71812. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  71813. }
  71814. /**
  71815. * Update when tooltip is rendered
  71816. */
  71817. TooltipRichContent.prototype.update = function (tooltipModel) {
  71818. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  71819. alwaysShowContent && this._moveIfResized(); // update alwaysShowContent
  71820. this._alwaysShowContent = alwaysShowContent;
  71821. };
  71822. TooltipRichContent.prototype.show = function () {
  71823. if (this._hideTimeout) {
  71824. clearTimeout(this._hideTimeout);
  71825. }
  71826. this.el.show();
  71827. this._show = true;
  71828. };
  71829. /**
  71830. * Set tooltip content
  71831. */
  71832. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  71833. var _this = this;
  71834. if (isObject(content)) {
  71835. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  71836. }
  71837. if (this.el) {
  71838. this._zr.remove(this.el);
  71839. }
  71840. var textStyleModel = tooltipModel.getModel('textStyle');
  71841. this.el = new ZRText({
  71842. style: {
  71843. rich: markupStyleCreator.richTextStyles,
  71844. text: content,
  71845. lineHeight: 22,
  71846. borderWidth: 1,
  71847. borderColor: borderColor,
  71848. textShadowColor: textStyleModel.get('textShadowColor'),
  71849. fill: tooltipModel.get(['textStyle', 'color']),
  71850. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  71851. verticalAlign: 'top',
  71852. align: 'left'
  71853. },
  71854. z: tooltipModel.get('z')
  71855. });
  71856. each(['backgroundColor', 'borderRadius', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'], function (propName) {
  71857. _this.el.style[propName] = tooltipModel.get(propName);
  71858. });
  71859. each(['textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'], function (propName) {
  71860. _this.el.style[propName] = textStyleModel.get(propName) || 0;
  71861. });
  71862. this._zr.add(this.el);
  71863. var self = this;
  71864. this.el.on('mouseover', function () {
  71865. // clear the timeout in hideLater and keep showing tooltip
  71866. if (self._enterable) {
  71867. clearTimeout(self._hideTimeout);
  71868. self._show = true;
  71869. }
  71870. self._inContent = true;
  71871. });
  71872. this.el.on('mouseout', function () {
  71873. if (self._enterable) {
  71874. if (self._show) {
  71875. self.hideLater(self._hideDelay);
  71876. }
  71877. }
  71878. self._inContent = false;
  71879. });
  71880. };
  71881. TooltipRichContent.prototype.setEnterable = function (enterable) {
  71882. this._enterable = enterable;
  71883. };
  71884. TooltipRichContent.prototype.getSize = function () {
  71885. var el = this.el;
  71886. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  71887. // if overflow, it will be cut. So calculate them accurately.
  71888. var shadowOuterSize = calcShadowOuterSize(el.style);
  71889. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  71890. };
  71891. TooltipRichContent.prototype.moveTo = function (x, y) {
  71892. var el = this.el;
  71893. if (el) {
  71894. var styleCoord = this._styleCoord;
  71895. makeStyleCoord$1(styleCoord, this._zr, x, y);
  71896. x = styleCoord[0];
  71897. y = styleCoord[1];
  71898. var style = el.style;
  71899. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  71900. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  71901. el.x = x + borderWidth + shadowOuterSize.left;
  71902. el.y = y + borderWidth + shadowOuterSize.top;
  71903. el.markRedraw();
  71904. }
  71905. };
  71906. /**
  71907. * when `alwaysShowContent` is true,
  71908. * move the tooltip after chart resized
  71909. */
  71910. TooltipRichContent.prototype._moveIfResized = function () {
  71911. // The ratio of left to width
  71912. var ratioX = this._styleCoord[2]; // The ratio of top to height
  71913. var ratioY = this._styleCoord[3];
  71914. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  71915. };
  71916. TooltipRichContent.prototype.hide = function () {
  71917. if (this.el) {
  71918. this.el.hide();
  71919. }
  71920. this._show = false;
  71921. };
  71922. TooltipRichContent.prototype.hideLater = function (time) {
  71923. if (this._show && !(this._inContent && this._enterable) && !this._alwaysShowContent) {
  71924. if (time) {
  71925. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  71926. this._show = false;
  71927. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  71928. } else {
  71929. this.hide();
  71930. }
  71931. }
  71932. };
  71933. TooltipRichContent.prototype.isShow = function () {
  71934. return this._show;
  71935. };
  71936. TooltipRichContent.prototype.dispose = function () {
  71937. this._zr.remove(this.el);
  71938. };
  71939. return TooltipRichContent;
  71940. }();
  71941. function mathMaxWith0(val) {
  71942. return Math.max(0, val);
  71943. }
  71944. function calcShadowOuterSize(style) {
  71945. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  71946. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  71947. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  71948. return {
  71949. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  71950. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  71951. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  71952. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  71953. };
  71954. }
  71955. function makeStyleCoord$1(out, zr, zrX, zrY) {
  71956. out[0] = zrX;
  71957. out[1] = zrY;
  71958. out[2] = out[0] / zr.getWidth();
  71959. out[3] = out[1] / zr.getHeight();
  71960. }
  71961. var proxyRect = new Rect({
  71962. shape: {
  71963. x: -1,
  71964. y: -1,
  71965. width: 2,
  71966. height: 2
  71967. }
  71968. });
  71969. var TooltipView =
  71970. /** @class */
  71971. function (_super) {
  71972. __extends(TooltipView, _super);
  71973. function TooltipView() {
  71974. var _this = _super !== null && _super.apply(this, arguments) || this;
  71975. _this.type = TooltipView.type;
  71976. return _this;
  71977. }
  71978. TooltipView.prototype.init = function (ecModel, api) {
  71979. if (env.node || !api.getDom()) {
  71980. return;
  71981. }
  71982. var tooltipModel = ecModel.getComponent('tooltip');
  71983. var renderMode = this._renderMode = getTooltipRenderMode(tooltipModel.get('renderMode'));
  71984. this._tooltipContent = renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  71985. appendToBody: tooltipModel.get('appendToBody', true)
  71986. });
  71987. };
  71988. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  71989. if (env.node || !api.getDom()) {
  71990. return;
  71991. } // Reset
  71992. this.group.removeAll();
  71993. this._tooltipModel = tooltipModel;
  71994. this._ecModel = ecModel;
  71995. this._api = api;
  71996. var tooltipContent = this._tooltipContent;
  71997. tooltipContent.update(tooltipModel);
  71998. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  71999. this._initGlobalListener();
  72000. this._keepShow(); // PENDING
  72001. // `mousemove` event will be triggered very frequently when the mouse moves fast,
  72002. // which causes that the `updatePosition` function was also called frequently.
  72003. // In Chrome with devtools open and Firefox, tooltip looks laggy and shakes. See #14695 #16101
  72004. // To avoid frequent triggering,
  72005. // consider throttling it in 50ms when transition is enabled
  72006. if (this._renderMode !== 'richText' && tooltipModel.get('transitionDuration')) {
  72007. createOrUpdate(this, '_updatePosition', 50, 'fixRate');
  72008. } else {
  72009. clear(this, '_updatePosition');
  72010. }
  72011. };
  72012. TooltipView.prototype._initGlobalListener = function () {
  72013. var tooltipModel = this._tooltipModel;
  72014. var triggerOn = tooltipModel.get('triggerOn');
  72015. register('itemTooltip', this._api, bind(function (currTrigger, e, dispatchAction) {
  72016. // If 'none', it is not controlled by mouse totally.
  72017. if (triggerOn !== 'none') {
  72018. if (triggerOn.indexOf(currTrigger) >= 0) {
  72019. this._tryShow(e, dispatchAction);
  72020. } else if (currTrigger === 'leave') {
  72021. this._hide(dispatchAction);
  72022. }
  72023. }
  72024. }, this));
  72025. };
  72026. TooltipView.prototype._keepShow = function () {
  72027. var tooltipModel = this._tooltipModel;
  72028. var ecModel = this._ecModel;
  72029. var api = this._api;
  72030. var triggerOn = tooltipModel.get('triggerOn'); // Try to keep the tooltip show when refreshing
  72031. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  72032. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  72033. // which is not expected.
  72034. && triggerOn !== 'none' && triggerOn !== 'click') {
  72035. var self_1 = this;
  72036. clearTimeout(this._refreshUpdateTimeout);
  72037. this._refreshUpdateTimeout = setTimeout(function () {
  72038. // Show tip next tick after other charts are rendered
  72039. // In case highlight action has wrong result
  72040. // FIXME
  72041. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  72042. x: self_1._lastX,
  72043. y: self_1._lastY,
  72044. dataByCoordSys: self_1._lastDataByCoordSys
  72045. });
  72046. });
  72047. }
  72048. };
  72049. /**
  72050. * Show tip manually by
  72051. * dispatchAction({
  72052. * type: 'showTip',
  72053. * x: 10,
  72054. * y: 10
  72055. * });
  72056. * Or
  72057. * dispatchAction({
  72058. * type: 'showTip',
  72059. * seriesIndex: 0,
  72060. * dataIndex or dataIndexInside or name
  72061. * });
  72062. *
  72063. * TODO Batch
  72064. */
  72065. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  72066. if (payload.from === this.uid || env.node || !api.getDom()) {
  72067. return;
  72068. }
  72069. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  72070. this._ticket = ''; // When triggered from axisPointer.
  72071. var dataByCoordSys = payload.dataByCoordSys;
  72072. var cmptRef = findComponentReference(payload, ecModel, api);
  72073. if (cmptRef) {
  72074. var rect = cmptRef.el.getBoundingRect().clone();
  72075. rect.applyTransform(cmptRef.el.transform);
  72076. this._tryShow({
  72077. offsetX: rect.x + rect.width / 2,
  72078. offsetY: rect.y + rect.height / 2,
  72079. target: cmptRef.el,
  72080. position: payload.position,
  72081. // When manully trigger, the mouse is not on the el, so we'd better to
  72082. // position tooltip on the bottom of the el and display arrow is possible.
  72083. positionDefault: 'bottom'
  72084. }, dispatchAction);
  72085. } else if (payload.tooltip && payload.x != null && payload.y != null) {
  72086. var el = proxyRect;
  72087. el.x = payload.x;
  72088. el.y = payload.y;
  72089. el.update();
  72090. getECData(el).tooltipConfig = {
  72091. name: null,
  72092. option: payload.tooltip
  72093. }; // Manually show tooltip while view is not using zrender elements.
  72094. this._tryShow({
  72095. offsetX: payload.x,
  72096. offsetY: payload.y,
  72097. target: el
  72098. }, dispatchAction);
  72099. } else if (dataByCoordSys) {
  72100. this._tryShow({
  72101. offsetX: payload.x,
  72102. offsetY: payload.y,
  72103. position: payload.position,
  72104. dataByCoordSys: dataByCoordSys,
  72105. tooltipOption: payload.tooltipOption
  72106. }, dispatchAction);
  72107. } else if (payload.seriesIndex != null) {
  72108. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  72109. return;
  72110. }
  72111. var pointInfo = findPointFromSeries(payload, ecModel);
  72112. var cx = pointInfo.point[0];
  72113. var cy = pointInfo.point[1];
  72114. if (cx != null && cy != null) {
  72115. this._tryShow({
  72116. offsetX: cx,
  72117. offsetY: cy,
  72118. target: pointInfo.el,
  72119. position: payload.position,
  72120. // When manully trigger, the mouse is not on the el, so we'd better to
  72121. // position tooltip on the bottom of the el and display arrow is possible.
  72122. positionDefault: 'bottom'
  72123. }, dispatchAction);
  72124. }
  72125. } else if (payload.x != null && payload.y != null) {
  72126. // FIXME
  72127. // should wrap dispatchAction like `axisPointer/globalListener` ?
  72128. api.dispatchAction({
  72129. type: 'updateAxisPointer',
  72130. x: payload.x,
  72131. y: payload.y
  72132. });
  72133. this._tryShow({
  72134. offsetX: payload.x,
  72135. offsetY: payload.y,
  72136. position: payload.position,
  72137. target: api.getZr().findHover(payload.x, payload.y).target
  72138. }, dispatchAction);
  72139. }
  72140. };
  72141. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  72142. var tooltipContent = this._tooltipContent;
  72143. if (this._tooltipModel) {
  72144. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  72145. }
  72146. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  72147. if (payload.from !== this.uid) {
  72148. this._hide(makeDispatchAction$1(payload, api));
  72149. }
  72150. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  72151. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  72152. // and tooltip.
  72153. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  72154. var seriesIndex = payload.seriesIndex;
  72155. var dataIndex = payload.dataIndex; // @ts-ignore
  72156. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  72157. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  72158. return;
  72159. }
  72160. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  72161. if (!seriesModel) {
  72162. return;
  72163. }
  72164. var data = seriesModel.getData();
  72165. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model], this._tooltipModel);
  72166. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  72167. return;
  72168. }
  72169. api.dispatchAction({
  72170. type: 'updateAxisPointer',
  72171. seriesIndex: seriesIndex,
  72172. dataIndex: dataIndex,
  72173. position: payload.position
  72174. });
  72175. return true;
  72176. };
  72177. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  72178. var el = e.target;
  72179. var tooltipModel = this._tooltipModel;
  72180. if (!tooltipModel) {
  72181. return;
  72182. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  72183. this._lastX = e.offsetX;
  72184. this._lastY = e.offsetY;
  72185. var dataByCoordSys = e.dataByCoordSys;
  72186. if (dataByCoordSys && dataByCoordSys.length) {
  72187. this._showAxisTooltip(dataByCoordSys, e);
  72188. } else if (el) {
  72189. this._lastDataByCoordSys = null;
  72190. var seriesDispatcher_1;
  72191. var cmptDispatcher_1;
  72192. findEventDispatcher(el, function (target) {
  72193. // Always show item tooltip if mouse is on the element with dataIndex
  72194. if (getECData(target).dataIndex != null) {
  72195. seriesDispatcher_1 = target;
  72196. return true;
  72197. } // Tooltip provided directly. Like legend.
  72198. if (getECData(target).tooltipConfig != null) {
  72199. cmptDispatcher_1 = target;
  72200. return true;
  72201. }
  72202. }, true);
  72203. if (seriesDispatcher_1) {
  72204. this._showSeriesItemTooltip(e, seriesDispatcher_1, dispatchAction);
  72205. } else if (cmptDispatcher_1) {
  72206. this._showComponentItemTooltip(e, cmptDispatcher_1, dispatchAction);
  72207. } else {
  72208. this._hide(dispatchAction);
  72209. }
  72210. } else {
  72211. this._lastDataByCoordSys = null;
  72212. this._hide(dispatchAction);
  72213. }
  72214. };
  72215. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  72216. // showDelay is used in this case: tooltip.enterable is set
  72217. // as true. User intent to move mouse into tooltip and click
  72218. // something. `showDelay` makes it easier to enter the content
  72219. // but tooltip do not move immediately.
  72220. var delay = tooltipModel.get('showDelay');
  72221. cb = bind(cb, this);
  72222. clearTimeout(this._showTimout);
  72223. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  72224. };
  72225. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  72226. var ecModel = this._ecModel;
  72227. var globalTooltipModel = this._tooltipModel;
  72228. var point = [e.offsetX, e.offsetY];
  72229. var singleTooltipModel = buildTooltipModel([e.tooltipOption], globalTooltipModel);
  72230. var renderMode = this._renderMode;
  72231. var cbParamsList = [];
  72232. var articleMarkup = createTooltipMarkup('section', {
  72233. blocks: [],
  72234. noHeader: true
  72235. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  72236. var markupTextArrLegacy = [];
  72237. var markupStyleCreator = new TooltipMarkupStyleCreator();
  72238. each(dataByCoordSys, function (itemCoordSys) {
  72239. each(itemCoordSys.dataByAxis, function (axisItem) {
  72240. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  72241. var axisValue = axisItem.value;
  72242. if (!axisModel || axisValue == null) {
  72243. return;
  72244. }
  72245. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  72246. var axisSectionMarkup = createTooltipMarkup('section', {
  72247. header: axisValueLabel,
  72248. noHeader: !trim(axisValueLabel),
  72249. sortBlocks: true,
  72250. blocks: []
  72251. });
  72252. articleMarkup.blocks.push(axisSectionMarkup);
  72253. each(axisItem.seriesDataIndices, function (idxItem) {
  72254. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  72255. var dataIndex = idxItem.dataIndexInside;
  72256. var cbParams = series.getDataParams(dataIndex); // Can't find data.
  72257. if (cbParams.dataIndex < 0) {
  72258. return;
  72259. }
  72260. cbParams.axisDim = axisItem.axisDim;
  72261. cbParams.axisIndex = axisItem.axisIndex;
  72262. cbParams.axisType = axisItem.axisType;
  72263. cbParams.axisId = axisItem.axisId;
  72264. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  72265. value: axisValue
  72266. });
  72267. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  72268. // text in `formatter` callback and use those markers style.
  72269. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  72270. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  72271. var frag = seriesTooltipResult.frag;
  72272. if (frag) {
  72273. var valueFormatter = buildTooltipModel([series], globalTooltipModel).get('valueFormatter');
  72274. axisSectionMarkup.blocks.push(valueFormatter ? extend({
  72275. valueFormatter: valueFormatter
  72276. }, frag) : frag);
  72277. }
  72278. if (seriesTooltipResult.text) {
  72279. markupTextArrLegacy.push(seriesTooltipResult.text);
  72280. }
  72281. cbParamsList.push(cbParams);
  72282. });
  72283. });
  72284. }); // In most cases, the second axis is displays upper on the first one.
  72285. // So we reverse it to look better.
  72286. articleMarkup.blocks.reverse();
  72287. markupTextArrLegacy.reverse();
  72288. var positionExpr = e.position;
  72289. var orderMode = singleTooltipModel.get('order');
  72290. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  72291. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  72292. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  72293. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  72294. this._showOrMove(singleTooltipModel, function () {
  72295. if (this._updateContentNotChangedOnAxis(dataByCoordSys, cbParamsList)) {
  72296. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  72297. } else {
  72298. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  72299. }
  72300. }); // Do not trigger events here, because this branch only be entered
  72301. // from dispatchAction.
  72302. };
  72303. TooltipView.prototype._showSeriesItemTooltip = function (e, dispatcher, dispatchAction) {
  72304. var ecModel = this._ecModel;
  72305. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  72306. // Used when mouseover on a element like markPoint or edge
  72307. // In which case, the data is not main data in series.
  72308. var seriesIndex = ecData.seriesIndex;
  72309. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  72310. var dataModel = ecData.dataModel || seriesModel;
  72311. var dataIndex = ecData.dataIndex;
  72312. var dataType = ecData.dataType;
  72313. var data = dataModel.getData(dataType);
  72314. var renderMode = this._renderMode;
  72315. var positionDefault = e.positionDefault;
  72316. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model], this._tooltipModel, positionDefault ? {
  72317. position: positionDefault
  72318. } : null);
  72319. var tooltipTrigger = tooltipModel.get('trigger');
  72320. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  72321. return;
  72322. }
  72323. var params = dataModel.getDataParams(dataIndex, dataType);
  72324. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  72325. // text in `formatter` callback and use those markers style.
  72326. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  72327. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  72328. var orderMode = tooltipModel.get('order');
  72329. var valueFormatter = tooltipModel.get('valueFormatter');
  72330. var frag = seriesTooltipResult.frag;
  72331. var markupText = frag ? buildTooltipMarkup(valueFormatter ? extend({
  72332. valueFormatter: valueFormatter
  72333. }, frag) : frag, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.text;
  72334. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  72335. this._showOrMove(tooltipModel, function () {
  72336. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  72337. }); // FIXME
  72338. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  72339. dispatchAction({
  72340. type: 'showTip',
  72341. dataIndexInside: dataIndex,
  72342. dataIndex: data.getRawIndex(dataIndex),
  72343. seriesIndex: seriesIndex,
  72344. from: this.uid
  72345. });
  72346. };
  72347. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  72348. var ecData = getECData(el);
  72349. var tooltipConfig = ecData.tooltipConfig;
  72350. var tooltipOpt = tooltipConfig.option || {};
  72351. if (isString(tooltipOpt)) {
  72352. var content = tooltipOpt;
  72353. tooltipOpt = {
  72354. content: content,
  72355. // Fixed formatter
  72356. formatter: content
  72357. };
  72358. }
  72359. var tooltipModelCascade = [tooltipOpt];
  72360. var cmpt = this._ecModel.getComponent(ecData.componentMainType, ecData.componentIndex);
  72361. if (cmpt) {
  72362. tooltipModelCascade.push(cmpt);
  72363. } // In most cases, component tooltip formatter has different params with series tooltip formatter,
  72364. // so that they cannot share the same formatter. Since the global tooltip formatter is used for series
  72365. // by convention, we do not use it as the default formatter for component.
  72366. tooltipModelCascade.push({
  72367. formatter: tooltipOpt.content
  72368. });
  72369. var positionDefault = e.positionDefault;
  72370. var subTooltipModel = buildTooltipModel(tooltipModelCascade, this._tooltipModel, positionDefault ? {
  72371. position: positionDefault
  72372. } : null);
  72373. var defaultHtml = subTooltipModel.get('content');
  72374. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  72375. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  72376. // only works on coordinate system. In fact, we have not found case
  72377. // that requires setting `trigger` nothing on component yet.
  72378. this._showOrMove(subTooltipModel, function () {
  72379. // Use formatterParams from element defined in component
  72380. // Avoid users modify it.
  72381. var formatterParams = clone(subTooltipModel.get('formatterParams') || {});
  72382. this._showTooltipContent(subTooltipModel, defaultHtml, formatterParams, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  72383. }); // If not dispatch showTip, tip may be hide triggered by axis.
  72384. dispatchAction({
  72385. type: 'showTip',
  72386. from: this.uid
  72387. });
  72388. };
  72389. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  72390. // Instead of top level tooltip.
  72391. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  72392. // Reset ticket
  72393. this._ticket = '';
  72394. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  72395. return;
  72396. }
  72397. var tooltipContent = this._tooltipContent;
  72398. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  72399. var formatter = tooltipModel.get('formatter');
  72400. positionExpr = positionExpr || tooltipModel.get('position');
  72401. var html = defaultHtml;
  72402. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  72403. var nearPointColor = nearPoint.color;
  72404. if (formatter) {
  72405. if (isString(formatter)) {
  72406. var useUTC = tooltipModel.ecModel.get('useUTC');
  72407. var params0 = isArray(params) ? params[0] : params;
  72408. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  72409. html = formatter;
  72410. if (isTimeAxis) {
  72411. html = format(params0.axisValue, html, useUTC);
  72412. }
  72413. html = formatTpl(html, params, true);
  72414. } else if (isFunction(formatter)) {
  72415. var callback = bind(function (cbTicket, html) {
  72416. if (cbTicket === this._ticket) {
  72417. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72418. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72419. }
  72420. }, this);
  72421. this._ticket = asyncTicket;
  72422. html = formatter(params, asyncTicket, callback);
  72423. } else {
  72424. html = formatter;
  72425. }
  72426. }
  72427. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPointColor, positionExpr);
  72428. tooltipContent.show(tooltipModel, nearPointColor);
  72429. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  72430. };
  72431. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  72432. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  72433. return {
  72434. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  72435. };
  72436. }
  72437. if (!isArray(tooltipDataParams)) {
  72438. return {
  72439. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  72440. };
  72441. }
  72442. };
  72443. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  72444. y, // Mouse y
  72445. content, params, el) {
  72446. var viewWidth = this._api.getWidth();
  72447. var viewHeight = this._api.getHeight();
  72448. positionExpr = positionExpr || tooltipModel.get('position');
  72449. var contentSize = content.getSize();
  72450. var align = tooltipModel.get('align');
  72451. var vAlign = tooltipModel.get('verticalAlign');
  72452. var rect = el && el.getBoundingRect().clone();
  72453. el && rect.applyTransform(el.transform);
  72454. if (isFunction(positionExpr)) {
  72455. // Callback of position can be an array or a string specify the position
  72456. positionExpr = positionExpr([x, y], params, content.el, rect, {
  72457. viewSize: [viewWidth, viewHeight],
  72458. contentSize: contentSize.slice()
  72459. });
  72460. }
  72461. if (isArray(positionExpr)) {
  72462. x = parsePercent$1(positionExpr[0], viewWidth);
  72463. y = parsePercent$1(positionExpr[1], viewHeight);
  72464. } else if (isObject(positionExpr)) {
  72465. var boxLayoutPosition = positionExpr;
  72466. boxLayoutPosition.width = contentSize[0];
  72467. boxLayoutPosition.height = contentSize[1];
  72468. var layoutRect = getLayoutRect(boxLayoutPosition, {
  72469. width: viewWidth,
  72470. height: viewHeight
  72471. });
  72472. x = layoutRect.x;
  72473. y = layoutRect.y;
  72474. align = null; // When positionExpr is left/top/right/bottom,
  72475. // align and verticalAlign will not work.
  72476. vAlign = null;
  72477. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  72478. else if (isString(positionExpr) && el) {
  72479. var pos = calcTooltipPosition(positionExpr, rect, contentSize, tooltipModel.get('borderWidth'));
  72480. x = pos[0];
  72481. y = pos[1];
  72482. } else {
  72483. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  72484. x = pos[0];
  72485. y = pos[1];
  72486. }
  72487. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  72488. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  72489. if (shouldTooltipConfine(tooltipModel)) {
  72490. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  72491. x = pos[0];
  72492. y = pos[1];
  72493. }
  72494. content.moveTo(x, y);
  72495. }; // FIXME
  72496. // Should we remove this but leave this to user?
  72497. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys, cbParamsList) {
  72498. var lastCoordSys = this._lastDataByCoordSys;
  72499. var lastCbParamsList = this._cbParamsList;
  72500. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  72501. contentNotChanged && each(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  72502. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  72503. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  72504. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  72505. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  72506. contentNotChanged && each(lastDataByAxis, function (lastItem, indexAxis) {
  72507. var thisItem = thisDataByAxis[indexAxis] || {};
  72508. var lastIndices = lastItem.seriesDataIndices || [];
  72509. var newIndices = thisItem.seriesDataIndices || [];
  72510. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  72511. contentNotChanged && each(lastIndices, function (lastIdxItem, j) {
  72512. var newIdxItem = newIndices[j];
  72513. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  72514. }); // check is cbParams data value changed
  72515. lastCbParamsList && each(lastItem.seriesDataIndices, function (idxItem) {
  72516. var seriesIdx = idxItem.seriesIndex;
  72517. var cbParams = cbParamsList[seriesIdx];
  72518. var lastCbParams = lastCbParamsList[seriesIdx];
  72519. if (cbParams && lastCbParams && lastCbParams.data !== cbParams.data) {
  72520. contentNotChanged = false;
  72521. }
  72522. });
  72523. });
  72524. });
  72525. this._lastDataByCoordSys = dataByCoordSys;
  72526. this._cbParamsList = cbParamsList;
  72527. return !!contentNotChanged;
  72528. };
  72529. TooltipView.prototype._hide = function (dispatchAction) {
  72530. // Do not directly hideLater here, because this behavior may be prevented
  72531. // in dispatchAction when showTip is dispatched.
  72532. // FIXME
  72533. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  72534. this._lastDataByCoordSys = null;
  72535. dispatchAction({
  72536. type: 'hideTip',
  72537. from: this.uid
  72538. });
  72539. };
  72540. TooltipView.prototype.dispose = function (ecModel, api) {
  72541. if (env.node || !api.getDom()) {
  72542. return;
  72543. }
  72544. clear(this, '_updatePosition');
  72545. this._tooltipContent.dispose();
  72546. unregister('itemTooltip', api);
  72547. };
  72548. TooltipView.type = 'tooltip';
  72549. return TooltipView;
  72550. }(ComponentView);
  72551. /**
  72552. * From top to bottom. (the last one should be globalTooltipModel);
  72553. */
  72554. function buildTooltipModel(modelCascade, globalTooltipModel, defaultTooltipOption) {
  72555. // Last is always tooltip model.
  72556. var ecModel = globalTooltipModel.ecModel;
  72557. var resultModel;
  72558. if (defaultTooltipOption) {
  72559. resultModel = new Model(defaultTooltipOption, ecModel, ecModel);
  72560. resultModel = new Model(globalTooltipModel.option, resultModel, ecModel);
  72561. } else {
  72562. resultModel = globalTooltipModel;
  72563. }
  72564. for (var i = modelCascade.length - 1; i >= 0; i--) {
  72565. var tooltipOpt = modelCascade[i];
  72566. if (tooltipOpt) {
  72567. if (tooltipOpt instanceof Model) {
  72568. tooltipOpt = tooltipOpt.get('tooltip', true);
  72569. } // In each data item tooltip can be simply write:
  72570. // {
  72571. // value: 10,
  72572. // tooltip: 'Something you need to know'
  72573. // }
  72574. if (isString(tooltipOpt)) {
  72575. tooltipOpt = {
  72576. formatter: tooltipOpt
  72577. };
  72578. }
  72579. if (tooltipOpt) {
  72580. resultModel = new Model(tooltipOpt, resultModel, ecModel);
  72581. }
  72582. }
  72583. }
  72584. return resultModel;
  72585. }
  72586. function makeDispatchAction$1(payload, api) {
  72587. return payload.dispatchAction || bind(api.dispatchAction, api);
  72588. }
  72589. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  72590. var size = content.getSize();
  72591. var width = size[0];
  72592. var height = size[1];
  72593. if (gapH != null) {
  72594. // Add extra 2 pixels for this case:
  72595. // At present the "values" in default tooltip are using CSS `float: right`.
  72596. // When the right edge of the tooltip box is on the right side of the
  72597. // viewport, the `float` layout might push the "values" to the second line.
  72598. if (x + width + gapH + 2 > viewWidth) {
  72599. x -= width + gapH;
  72600. } else {
  72601. x += gapH;
  72602. }
  72603. }
  72604. if (gapV != null) {
  72605. if (y + height + gapV > viewHeight) {
  72606. y -= height + gapV;
  72607. } else {
  72608. y += gapV;
  72609. }
  72610. }
  72611. return [x, y];
  72612. }
  72613. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  72614. var size = content.getSize();
  72615. var width = size[0];
  72616. var height = size[1];
  72617. x = Math.min(x + width, viewWidth) - width;
  72618. y = Math.min(y + height, viewHeight) - height;
  72619. x = Math.max(x, 0);
  72620. y = Math.max(y, 0);
  72621. return [x, y];
  72622. }
  72623. function calcTooltipPosition(position, rect, contentSize, borderWidth) {
  72624. var domWidth = contentSize[0];
  72625. var domHeight = contentSize[1];
  72626. var offset = Math.ceil(Math.SQRT2 * borderWidth) + 8;
  72627. var x = 0;
  72628. var y = 0;
  72629. var rectWidth = rect.width;
  72630. var rectHeight = rect.height;
  72631. switch (position) {
  72632. case 'inside':
  72633. x = rect.x + rectWidth / 2 - domWidth / 2;
  72634. y = rect.y + rectHeight / 2 - domHeight / 2;
  72635. break;
  72636. case 'top':
  72637. x = rect.x + rectWidth / 2 - domWidth / 2;
  72638. y = rect.y - domHeight - offset;
  72639. break;
  72640. case 'bottom':
  72641. x = rect.x + rectWidth / 2 - domWidth / 2;
  72642. y = rect.y + rectHeight + offset;
  72643. break;
  72644. case 'left':
  72645. x = rect.x - domWidth - offset;
  72646. y = rect.y + rectHeight / 2 - domHeight / 2;
  72647. break;
  72648. case 'right':
  72649. x = rect.x + rectWidth + offset;
  72650. y = rect.y + rectHeight / 2 - domHeight / 2;
  72651. }
  72652. return [x, y];
  72653. }
  72654. function isCenterAlign(align) {
  72655. return align === 'center' || align === 'middle';
  72656. }
  72657. /**
  72658. * Find target component by payload like:
  72659. * ```js
  72660. * { legendId: 'some_id', name: 'xxx' }
  72661. * { toolboxIndex: 1, name: 'xxx' }
  72662. * { geoName: 'some_name', name: 'xxx' }
  72663. * ```
  72664. * PENDING: at present only
  72665. *
  72666. * If not found, return null/undefined.
  72667. */
  72668. function findComponentReference(payload, ecModel, api) {
  72669. var queryOptionMap = preParseFinder(payload).queryOptionMap;
  72670. var componentMainType = queryOptionMap.keys()[0];
  72671. if (!componentMainType || componentMainType === 'series') {
  72672. return;
  72673. }
  72674. var queryResult = queryReferringComponents(ecModel, componentMainType, queryOptionMap.get(componentMainType), {
  72675. useDefault: false,
  72676. enableAll: false,
  72677. enableNone: false
  72678. });
  72679. var model = queryResult.models[0];
  72680. if (!model) {
  72681. return;
  72682. }
  72683. var view = api.getViewOfComponentModel(model);
  72684. var el;
  72685. view.group.traverse(function (subEl) {
  72686. var tooltipConfig = getECData(subEl).tooltipConfig;
  72687. if (tooltipConfig && tooltipConfig.name === payload.name) {
  72688. el = subEl;
  72689. return true; // stop
  72690. }
  72691. });
  72692. if (el) {
  72693. return {
  72694. componentMainType: componentMainType,
  72695. componentIndex: model.componentIndex,
  72696. el: el
  72697. };
  72698. }
  72699. }
  72700. function install$A(registers) {
  72701. use(install$s);
  72702. registers.registerComponentModel(TooltipModel);
  72703. registers.registerComponentView(TooltipView);
  72704. /**
  72705. * @action
  72706. * @property {string} type
  72707. * @property {number} seriesIndex
  72708. * @property {number} dataIndex
  72709. * @property {number} [x]
  72710. * @property {number} [y]
  72711. */
  72712. registers.registerAction({
  72713. type: 'showTip',
  72714. event: 'showTip',
  72715. update: 'tooltip:manuallyShowTip'
  72716. }, noop);
  72717. registers.registerAction({
  72718. type: 'hideTip',
  72719. event: 'hideTip',
  72720. update: 'tooltip:manuallyHideTip'
  72721. }, noop);
  72722. }
  72723. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  72724. function brushPreprocessor(option, isNew) {
  72725. var brushComponents = normalizeToArray(option ? option.brush : []);
  72726. if (!brushComponents.length) {
  72727. return;
  72728. }
  72729. var brushComponentSpecifiedBtns = [];
  72730. each(brushComponents, function (brushOpt) {
  72731. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  72732. if (tbs instanceof Array) {
  72733. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  72734. }
  72735. });
  72736. var toolbox = option && option.toolbox;
  72737. if (isArray(toolbox)) {
  72738. toolbox = toolbox[0];
  72739. }
  72740. if (!toolbox) {
  72741. toolbox = {
  72742. feature: {}
  72743. };
  72744. option.toolbox = [toolbox];
  72745. }
  72746. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  72747. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  72748. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  72749. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  72750. removeDuplicate(brushTypes);
  72751. if (isNew && !brushTypes.length) {
  72752. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  72753. }
  72754. }
  72755. function removeDuplicate(arr) {
  72756. var map = {};
  72757. each(arr, function (val) {
  72758. map[val] = 1;
  72759. });
  72760. arr.length = 0;
  72761. each(map, function (flag, val) {
  72762. arr.push(val);
  72763. });
  72764. }
  72765. var each$b = each;
  72766. function hasKeys(obj) {
  72767. if (obj) {
  72768. for (var name_1 in obj) {
  72769. if (obj.hasOwnProperty(name_1)) {
  72770. return true;
  72771. }
  72772. }
  72773. }
  72774. }
  72775. function createVisualMappings(option, stateList, supplementVisualOption) {
  72776. var visualMappings = {};
  72777. each$b(stateList, function (state) {
  72778. var mappings = visualMappings[state] = createMappings();
  72779. each$b(option[state], function (visualData, visualType) {
  72780. if (!VisualMapping.isValidType(visualType)) {
  72781. return;
  72782. }
  72783. var mappingOption = {
  72784. type: visualType,
  72785. visual: visualData
  72786. };
  72787. supplementVisualOption && supplementVisualOption(mappingOption, state);
  72788. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  72789. // is not supported, such as rendering using gradient color.
  72790. if (visualType === 'opacity') {
  72791. mappingOption = clone(mappingOption);
  72792. mappingOption.type = 'colorAlpha';
  72793. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  72794. }
  72795. });
  72796. });
  72797. return visualMappings;
  72798. function createMappings() {
  72799. var Creater = function () {}; // Make sure hidden fields will not be visited by
  72800. // object iteration (with hasOwnProperty checking).
  72801. Creater.prototype.__hidden = Creater.prototype;
  72802. var obj = new Creater();
  72803. return obj;
  72804. }
  72805. }
  72806. function replaceVisualOption(thisOption, newOption, keys) {
  72807. // Visual attributes merge is not supported, otherwise it
  72808. // brings overcomplicated merge logic. See #2853. So if
  72809. // newOption has anyone of these keys, all of these keys
  72810. // will be reset. Otherwise, all keys remain.
  72811. var has;
  72812. each(keys, function (key) {
  72813. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72814. has = true;
  72815. }
  72816. });
  72817. has && each(keys, function (key) {
  72818. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  72819. thisOption[key] = clone(newOption[key]);
  72820. } else {
  72821. delete thisOption[key];
  72822. }
  72823. });
  72824. }
  72825. /**
  72826. * @param stateList
  72827. * @param visualMappings
  72828. * @param list
  72829. * @param getValueState param: valueOrIndex, return: state.
  72830. * @param scope Scope for getValueState
  72831. * @param dimension Concrete dimension, if used.
  72832. */
  72833. // ???! handle brush?
  72834. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  72835. var visualTypesMap = {};
  72836. each(stateList, function (state) {
  72837. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72838. visualTypesMap[state] = visualTypes;
  72839. });
  72840. var dataIndex;
  72841. function getVisual(key) {
  72842. return getItemVisualFromData(data, dataIndex, key);
  72843. }
  72844. function setVisual(key, value) {
  72845. setItemVisualFromData(data, dataIndex, key, value);
  72846. }
  72847. if (dimension == null) {
  72848. data.each(eachItem);
  72849. } else {
  72850. data.each([dimension], eachItem);
  72851. }
  72852. function eachItem(valueOrIndex, index) {
  72853. dataIndex = dimension == null ? valueOrIndex // First argument is index
  72854. : index;
  72855. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72856. // @ts-ignore
  72857. if (rawDataItem && rawDataItem.visualMap === false) {
  72858. return;
  72859. }
  72860. var valueState = getValueState.call(scope, valueOrIndex);
  72861. var mappings = visualMappings[valueState];
  72862. var visualTypes = visualTypesMap[valueState];
  72863. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72864. var type = visualTypes[i];
  72865. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  72866. }
  72867. }
  72868. }
  72869. /**
  72870. * @param data
  72871. * @param stateList
  72872. * @param visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  72873. * @param getValueState param: valueOrIndex, return: state.
  72874. * @param dim dimension or dimension index.
  72875. */
  72876. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  72877. var visualTypesMap = {};
  72878. each(stateList, function (state) {
  72879. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  72880. visualTypesMap[state] = visualTypes;
  72881. });
  72882. return {
  72883. progress: function progress(params, data) {
  72884. var dimIndex;
  72885. if (dim != null) {
  72886. dimIndex = data.getDimensionIndex(dim);
  72887. }
  72888. function getVisual(key) {
  72889. return getItemVisualFromData(data, dataIndex, key);
  72890. }
  72891. function setVisual(key, value) {
  72892. setItemVisualFromData(data, dataIndex, key, value);
  72893. }
  72894. var dataIndex;
  72895. var store = data.getStore();
  72896. while ((dataIndex = params.next()) != null) {
  72897. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  72898. // @ts-ignore
  72899. if (rawDataItem && rawDataItem.visualMap === false) {
  72900. continue;
  72901. }
  72902. var value = dim != null ? store.get(dimIndex, dataIndex) : dataIndex;
  72903. var valueState = getValueState(value);
  72904. var mappings = visualMappings[valueState];
  72905. var visualTypes = visualTypesMap[valueState];
  72906. for (var i = 0, len = visualTypes.length; i < len; i++) {
  72907. var type = visualTypes[i];
  72908. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  72909. }
  72910. }
  72911. }
  72912. };
  72913. }
  72914. function makeBrushCommonSelectorForSeries(area) {
  72915. var brushType = area.brushType; // Do not use function binding or curry for performance.
  72916. var selectors = {
  72917. point: function (itemLayout) {
  72918. return selector[brushType].point(itemLayout, selectors, area);
  72919. },
  72920. rect: function (itemLayout) {
  72921. return selector[brushType].rect(itemLayout, selectors, area);
  72922. }
  72923. };
  72924. return selectors;
  72925. }
  72926. var selector = {
  72927. lineX: getLineSelectors(0),
  72928. lineY: getLineSelectors(1),
  72929. rect: {
  72930. point: function (itemLayout, selectors, area) {
  72931. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  72932. },
  72933. rect: function (itemLayout, selectors, area) {
  72934. return itemLayout && area.boundingRect.intersect(itemLayout);
  72935. }
  72936. },
  72937. polygon: {
  72938. point: function (itemLayout, selectors, area) {
  72939. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$2(area.range, itemLayout[0], itemLayout[1]);
  72940. },
  72941. rect: function (itemLayout, selectors, area) {
  72942. var points = area.range;
  72943. if (!itemLayout || points.length <= 1) {
  72944. return false;
  72945. }
  72946. var x = itemLayout.x;
  72947. var y = itemLayout.y;
  72948. var width = itemLayout.width;
  72949. var height = itemLayout.height;
  72950. var p = points[0];
  72951. 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)) {
  72952. return true;
  72953. }
  72954. }
  72955. }
  72956. };
  72957. function getLineSelectors(xyIndex) {
  72958. var xy = ['x', 'y'];
  72959. var wh = ['width', 'height'];
  72960. return {
  72961. point: function (itemLayout, selectors, area) {
  72962. if (itemLayout) {
  72963. var range = area.range;
  72964. var p = itemLayout[xyIndex];
  72965. return inLineRange(p, range);
  72966. }
  72967. },
  72968. rect: function (itemLayout, selectors, area) {
  72969. if (itemLayout) {
  72970. var range = area.range;
  72971. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  72972. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  72973. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  72974. }
  72975. }
  72976. };
  72977. }
  72978. function inLineRange(p, range) {
  72979. return range[0] <= p && p <= range[1];
  72980. }
  72981. var STATE_LIST = ['inBrush', 'outOfBrush'];
  72982. var DISPATCH_METHOD = '__ecBrushSelect';
  72983. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  72984. function layoutCovers(ecModel) {
  72985. ecModel.eachComponent({
  72986. mainType: 'brush'
  72987. }, function (brushModel) {
  72988. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  72989. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  72990. });
  72991. }
  72992. /**
  72993. * Register the visual encoding if this modules required.
  72994. */
  72995. function brushVisual(ecModel, api, payload) {
  72996. var brushSelected = [];
  72997. var throttleType;
  72998. var throttleDelay;
  72999. ecModel.eachComponent({
  73000. mainType: 'brush'
  73001. }, function (brushModel) {
  73002. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  73003. brushType: false
  73004. });
  73005. });
  73006. layoutCovers(ecModel);
  73007. ecModel.eachComponent({
  73008. mainType: 'brush'
  73009. }, function (brushModel, brushIndex) {
  73010. var thisBrushSelected = {
  73011. brushId: brushModel.id,
  73012. brushIndex: brushIndex,
  73013. brushName: brushModel.name,
  73014. areas: clone(brushModel.areas),
  73015. selected: []
  73016. }; // Every brush component exists in event params, convenient
  73017. // for user to find by index.
  73018. brushSelected.push(thisBrushSelected);
  73019. var brushOption = brushModel.option;
  73020. var brushLink = brushOption.brushLink;
  73021. var linkedSeriesMap = [];
  73022. var selectedDataIndexForLink = [];
  73023. var rangeInfoBySeries = [];
  73024. var hasBrushExists = false;
  73025. if (!brushIndex) {
  73026. // Only the first throttle setting works.
  73027. throttleType = brushOption.throttleType;
  73028. throttleDelay = brushOption.throttleDelay;
  73029. } // Add boundingRect and selectors to range.
  73030. var areas = map(brushModel.areas, function (area) {
  73031. var builder = boundingRectBuilders[area.brushType];
  73032. var selectableArea = defaults({
  73033. boundingRect: builder ? builder(area) : void 0
  73034. }, area);
  73035. selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
  73036. return selectableArea;
  73037. });
  73038. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  73039. mappingOption.mappingMethod = 'fixed';
  73040. });
  73041. isArray(brushLink) && each(brushLink, function (seriesIndex) {
  73042. linkedSeriesMap[seriesIndex] = 1;
  73043. });
  73044. function linkOthers(seriesIndex) {
  73045. return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
  73046. } // If no supported brush or no brush on the series,
  73047. // all visuals should be in original state.
  73048. function brushed(rangeInfoList) {
  73049. return !!rangeInfoList.length;
  73050. }
  73051. /**
  73052. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  73053. *
  73054. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  73055. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  73056. * └!hasBrushExist┘ └nothing.
  73057. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  73058. * └!hasBrushExist┘ └nothing.
  73059. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  73060. * !brushed┘ └nothing.
  73061. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  73062. */
  73063. // Step A
  73064. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  73065. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  73066. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  73067. });
  73068. function stepAParallel(seriesModel, seriesIndex) {
  73069. var coordSys = seriesModel.coordinateSystem;
  73070. hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
  73071. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  73072. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  73073. });
  73074. }
  73075. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  73076. if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
  73077. return;
  73078. }
  73079. each(areas, function (area) {
  73080. if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
  73081. rangeInfoList.push(area);
  73082. }
  73083. hasBrushExists = hasBrushExists || brushed(rangeInfoList);
  73084. });
  73085. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  73086. var data_1 = seriesModel.getData();
  73087. data_1.each(function (dataIndex) {
  73088. if (checkInRange(seriesModel, rangeInfoList, data_1, dataIndex)) {
  73089. selectedDataIndexForLink[dataIndex] = 1;
  73090. }
  73091. });
  73092. }
  73093. } // Step B
  73094. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  73095. var seriesBrushSelected = {
  73096. seriesId: seriesModel.id,
  73097. seriesIndex: seriesIndex,
  73098. seriesName: seriesModel.name,
  73099. dataIndex: []
  73100. }; // Every series exists in event params, convenient
  73101. // for user to find series by seriesIndex.
  73102. thisBrushSelected.selected.push(seriesBrushSelected);
  73103. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  73104. var data = seriesModel.getData();
  73105. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  73106. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  73107. } : function (dataIndex) {
  73108. return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  73109. }; // If no supported brush or no brush, all visuals are in original state.
  73110. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  73111. });
  73112. });
  73113. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  73114. }
  73115. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  73116. // This event will not be triggered when `setOpion`, otherwise dead lock may
  73117. // triggered when do `setOption` in event listener, which we do not find
  73118. // satisfactory way to solve yet. Some considered resolutions:
  73119. // (a) Diff with prevoius selected data ant only trigger event when changed.
  73120. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  73121. // also detect value changes in selected data) might bring complexity or fragility.
  73122. // (b) Use spectial param like `silent` to suppress event triggering.
  73123. // But such kind of volatile param may be weird in `setOption`.
  73124. if (!payload) {
  73125. return;
  73126. }
  73127. var zr = api.getZr();
  73128. if (zr[DISPATCH_FLAG]) {
  73129. return;
  73130. }
  73131. if (!zr[DISPATCH_METHOD]) {
  73132. zr[DISPATCH_METHOD] = doDispatch;
  73133. }
  73134. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  73135. fn(api, brushSelected);
  73136. }
  73137. function doDispatch(api, brushSelected) {
  73138. if (!api.isDisposed()) {
  73139. var zr = api.getZr();
  73140. zr[DISPATCH_FLAG] = true;
  73141. api.dispatchAction({
  73142. type: 'brushSelect',
  73143. batch: brushSelected
  73144. });
  73145. zr[DISPATCH_FLAG] = false;
  73146. }
  73147. }
  73148. function checkInRange(seriesModel, rangeInfoList, data, dataIndex) {
  73149. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  73150. var area = rangeInfoList[i];
  73151. if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) {
  73152. return true;
  73153. }
  73154. }
  73155. }
  73156. function brushModelNotControll(brushModel, seriesIndex) {
  73157. var seriesIndices = brushModel.option.seriesIndex;
  73158. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  73159. }
  73160. var boundingRectBuilders = {
  73161. rect: function (area) {
  73162. return getBoundingRectFromMinMax(area.range);
  73163. },
  73164. polygon: function (area) {
  73165. var minMax;
  73166. var range = area.range;
  73167. for (var i = 0, len = range.length; i < len; i++) {
  73168. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  73169. var rg = range[i];
  73170. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  73171. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  73172. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  73173. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  73174. }
  73175. return minMax && getBoundingRectFromMinMax(minMax);
  73176. }
  73177. };
  73178. function getBoundingRectFromMinMax(minMax) {
  73179. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  73180. }
  73181. var BrushView =
  73182. /** @class */
  73183. function (_super) {
  73184. __extends(BrushView, _super);
  73185. function BrushView() {
  73186. var _this = _super !== null && _super.apply(this, arguments) || this;
  73187. _this.type = BrushView.type;
  73188. return _this;
  73189. }
  73190. BrushView.prototype.init = function (ecModel, api) {
  73191. this.ecModel = ecModel;
  73192. this.api = api;
  73193. this.model;
  73194. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  73195. };
  73196. BrushView.prototype.render = function (brushModel, ecModel, api, payload) {
  73197. this.model = brushModel;
  73198. this._updateController(brushModel, ecModel, api, payload);
  73199. };
  73200. BrushView.prototype.updateTransform = function (brushModel, ecModel, api, payload) {
  73201. // PENDING: `updateTransform` is a little tricky, whose layout need
  73202. // to be calculate mandatorily and other stages will not be performed.
  73203. // Take care the correctness of the logic. See #11754 .
  73204. layoutCovers(ecModel);
  73205. this._updateController(brushModel, ecModel, api, payload);
  73206. };
  73207. BrushView.prototype.updateVisual = function (brushModel, ecModel, api, payload) {
  73208. this.updateTransform(brushModel, ecModel, api, payload);
  73209. };
  73210. BrushView.prototype.updateView = function (brushModel, ecModel, api, payload) {
  73211. this._updateController(brushModel, ecModel, api, payload);
  73212. };
  73213. BrushView.prototype._updateController = function (brushModel, ecModel, api, payload) {
  73214. // Do not update controller when drawing.
  73215. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  73216. }; // updateLayout: updateController,
  73217. // updateVisual: updateController,
  73218. BrushView.prototype.dispose = function () {
  73219. this._brushController.dispose();
  73220. };
  73221. BrushView.prototype._onBrush = function (eventParam) {
  73222. var modelId = this.model.id;
  73223. var areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  73224. // emits the same params with the last drag move event, and
  73225. // may have some delay when using touch pad, which makes
  73226. // animation not smooth (when using debounce).
  73227. (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({
  73228. type: 'brush',
  73229. brushId: modelId,
  73230. areas: clone(areas),
  73231. $from: modelId
  73232. });
  73233. eventParam.isEnd && this.api.dispatchAction({
  73234. type: 'brushEnd',
  73235. brushId: modelId,
  73236. areas: clone(areas),
  73237. $from: modelId
  73238. });
  73239. };
  73240. BrushView.type = 'brush';
  73241. return BrushView;
  73242. }(ComponentView);
  73243. var DEFAULT_OUT_OF_BRUSH_COLOR = '#ddd';
  73244. var BrushModel =
  73245. /** @class */
  73246. function (_super) {
  73247. __extends(BrushModel, _super);
  73248. function BrushModel() {
  73249. var _this = _super !== null && _super.apply(this, arguments) || this;
  73250. _this.type = BrushModel.type;
  73251. /**
  73252. * @readOnly
  73253. */
  73254. _this.areas = [];
  73255. /**
  73256. * Current brush painting area settings.
  73257. * @readOnly
  73258. */
  73259. _this.brushOption = {};
  73260. return _this;
  73261. }
  73262. BrushModel.prototype.optionUpdated = function (newOption, isInit) {
  73263. var thisOption = this.option;
  73264. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  73265. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  73266. thisOption.outOfBrush = thisOption.outOfBrush || {
  73267. color: DEFAULT_OUT_OF_BRUSH_COLOR
  73268. };
  73269. if (!inBrush.hasOwnProperty('liftZ')) {
  73270. // Bigger than the highlight z lift, otherwise it will
  73271. // be effected by the highlight z when brush.
  73272. inBrush.liftZ = 5;
  73273. }
  73274. };
  73275. /**
  73276. * If `areas` is null/undefined, range state remain.
  73277. */
  73278. BrushModel.prototype.setAreas = function (areas) {
  73279. if ("development" !== 'production') {
  73280. assert(isArray(areas));
  73281. each(areas, function (area) {
  73282. assert(area.brushType, 'Illegal areas');
  73283. });
  73284. } // If areas is null/undefined, range state remain.
  73285. // This helps user to dispatchAction({type: 'brush'}) with no areas
  73286. // set but just want to get the current brush select info from a `brush` event.
  73287. if (!areas) {
  73288. return;
  73289. }
  73290. this.areas = map(areas, function (area) {
  73291. return generateBrushOption(this.option, area);
  73292. }, this);
  73293. };
  73294. /**
  73295. * Set the current painting brush option.
  73296. */
  73297. BrushModel.prototype.setBrushOption = function (brushOption) {
  73298. this.brushOption = generateBrushOption(this.option, brushOption);
  73299. this.brushType = this.brushOption.brushType;
  73300. };
  73301. BrushModel.type = 'brush';
  73302. BrushModel.dependencies = ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'];
  73303. BrushModel.defaultOption = {
  73304. seriesIndex: 'all',
  73305. brushType: 'rect',
  73306. brushMode: 'single',
  73307. transformable: true,
  73308. brushStyle: {
  73309. borderWidth: 1,
  73310. color: 'rgba(210,219,238,0.3)',
  73311. borderColor: '#D2DBEE'
  73312. },
  73313. throttleType: 'fixRate',
  73314. throttleDelay: 0,
  73315. removeOnClick: true,
  73316. z: 10000
  73317. };
  73318. return BrushModel;
  73319. }(ComponentModel);
  73320. function generateBrushOption(option, brushOption) {
  73321. return merge({
  73322. brushType: option.brushType,
  73323. brushMode: option.brushMode,
  73324. transformable: option.transformable,
  73325. brushStyle: new Model(option.brushStyle).getItemStyle(),
  73326. removeOnClick: option.removeOnClick,
  73327. z: option.z
  73328. }, brushOption, true);
  73329. }
  73330. var ICON_TYPES = ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'];
  73331. var BrushFeature =
  73332. /** @class */
  73333. function (_super) {
  73334. __extends(BrushFeature, _super);
  73335. function BrushFeature() {
  73336. return _super !== null && _super.apply(this, arguments) || this;
  73337. }
  73338. BrushFeature.prototype.render = function (featureModel, ecModel, api) {
  73339. var brushType;
  73340. var brushMode;
  73341. var isBrushed;
  73342. ecModel.eachComponent({
  73343. mainType: 'brush'
  73344. }, function (brushModel) {
  73345. brushType = brushModel.brushType;
  73346. brushMode = brushModel.brushOption.brushMode || 'single';
  73347. isBrushed = isBrushed || !!brushModel.areas.length;
  73348. });
  73349. this._brushType = brushType;
  73350. this._brushMode = brushMode;
  73351. each(featureModel.get('type', true), function (type) {
  73352. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  73353. });
  73354. };
  73355. BrushFeature.prototype.updateView = function (featureModel, ecModel, api) {
  73356. this.render(featureModel, ecModel, api);
  73357. };
  73358. BrushFeature.prototype.getIcons = function () {
  73359. var model = this.model;
  73360. var availableIcons = model.get('icon', true);
  73361. var icons = {};
  73362. each(model.get('type', true), function (type) {
  73363. if (availableIcons[type]) {
  73364. icons[type] = availableIcons[type];
  73365. }
  73366. });
  73367. return icons;
  73368. };
  73369. BrushFeature.prototype.onclick = function (ecModel, api, type) {
  73370. var brushType = this._brushType;
  73371. var brushMode = this._brushMode;
  73372. if (type === 'clear') {
  73373. // Trigger parallel action firstly
  73374. api.dispatchAction({
  73375. type: 'axisAreaSelect',
  73376. intervals: []
  73377. });
  73378. api.dispatchAction({
  73379. type: 'brush',
  73380. command: 'clear',
  73381. // Clear all areas of all brush components.
  73382. areas: []
  73383. });
  73384. } else {
  73385. api.dispatchAction({
  73386. type: 'takeGlobalCursor',
  73387. key: 'brush',
  73388. brushOption: {
  73389. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  73390. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  73391. }
  73392. });
  73393. }
  73394. };
  73395. BrushFeature.getDefaultOption = function (ecModel) {
  73396. var defaultOption = {
  73397. show: true,
  73398. type: ICON_TYPES.slice(),
  73399. icon: {
  73400. /* eslint-disable */
  73401. 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',
  73402. 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',
  73403. 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',
  73404. 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',
  73405. 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',
  73406. 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
  73407. /* eslint-enable */
  73408. },
  73409. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  73410. title: ecModel.getLocaleModel().get(['toolbox', 'brush', 'title'])
  73411. };
  73412. return defaultOption;
  73413. };
  73414. return BrushFeature;
  73415. }(ToolboxFeature);
  73416. function install$B(registers) {
  73417. registers.registerComponentView(BrushView);
  73418. registers.registerComponentModel(BrushModel);
  73419. registers.registerPreprocessor(brushPreprocessor);
  73420. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual);
  73421. registers.registerAction({
  73422. type: 'brush',
  73423. event: 'brush',
  73424. update: 'updateVisual'
  73425. }, function (payload, ecModel) {
  73426. ecModel.eachComponent({
  73427. mainType: 'brush',
  73428. query: payload
  73429. }, function (brushModel) {
  73430. brushModel.setAreas(payload.areas);
  73431. });
  73432. });
  73433. /**
  73434. * payload: {
  73435. * brushComponents: [
  73436. * {
  73437. * brushId,
  73438. * brushIndex,
  73439. * brushName,
  73440. * series: [
  73441. * {
  73442. * seriesId,
  73443. * seriesIndex,
  73444. * seriesName,
  73445. * rawIndices: [21, 34, ...]
  73446. * },
  73447. * ...
  73448. * ]
  73449. * },
  73450. * ...
  73451. * ]
  73452. * }
  73453. */
  73454. registers.registerAction({
  73455. type: 'brushSelect',
  73456. event: 'brushSelected',
  73457. update: 'none'
  73458. }, noop);
  73459. registers.registerAction({
  73460. type: 'brushEnd',
  73461. event: 'brushEnd',
  73462. update: 'none'
  73463. }, noop);
  73464. registerFeature('brush', BrushFeature);
  73465. }
  73466. var TitleModel =
  73467. /** @class */
  73468. function (_super) {
  73469. __extends(TitleModel, _super);
  73470. function TitleModel() {
  73471. var _this = _super !== null && _super.apply(this, arguments) || this;
  73472. _this.type = TitleModel.type;
  73473. _this.layoutMode = {
  73474. type: 'box',
  73475. ignoreSize: true
  73476. };
  73477. return _this;
  73478. }
  73479. TitleModel.type = 'title';
  73480. TitleModel.defaultOption = {
  73481. // zlevel: 0,
  73482. z: 6,
  73483. show: true,
  73484. text: '',
  73485. target: 'blank',
  73486. subtext: '',
  73487. subtarget: 'blank',
  73488. left: 0,
  73489. top: 0,
  73490. backgroundColor: 'rgba(0,0,0,0)',
  73491. borderColor: '#ccc',
  73492. borderWidth: 0,
  73493. padding: 5,
  73494. itemGap: 10,
  73495. textStyle: {
  73496. fontSize: 18,
  73497. fontWeight: 'bold',
  73498. color: '#464646'
  73499. },
  73500. subtextStyle: {
  73501. fontSize: 12,
  73502. color: '#6E7079'
  73503. }
  73504. };
  73505. return TitleModel;
  73506. }(ComponentModel); // View
  73507. var TitleView =
  73508. /** @class */
  73509. function (_super) {
  73510. __extends(TitleView, _super);
  73511. function TitleView() {
  73512. var _this = _super !== null && _super.apply(this, arguments) || this;
  73513. _this.type = TitleView.type;
  73514. return _this;
  73515. }
  73516. TitleView.prototype.render = function (titleModel, ecModel, api) {
  73517. this.group.removeAll();
  73518. if (!titleModel.get('show')) {
  73519. return;
  73520. }
  73521. var group = this.group;
  73522. var textStyleModel = titleModel.getModel('textStyle');
  73523. var subtextStyleModel = titleModel.getModel('subtextStyle');
  73524. var textAlign = titleModel.get('textAlign');
  73525. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  73526. var textEl = new ZRText({
  73527. style: createTextStyle(textStyleModel, {
  73528. text: titleModel.get('text'),
  73529. fill: textStyleModel.getTextColor()
  73530. }, {
  73531. disableBox: true
  73532. }),
  73533. z2: 10
  73534. });
  73535. var textRect = textEl.getBoundingRect();
  73536. var subText = titleModel.get('subtext');
  73537. var subTextEl = new ZRText({
  73538. style: createTextStyle(subtextStyleModel, {
  73539. text: subText,
  73540. fill: subtextStyleModel.getTextColor(),
  73541. y: textRect.height + titleModel.get('itemGap'),
  73542. verticalAlign: 'top'
  73543. }, {
  73544. disableBox: true
  73545. }),
  73546. z2: 10
  73547. });
  73548. var link = titleModel.get('link');
  73549. var sublink = titleModel.get('sublink');
  73550. var triggerEvent = titleModel.get('triggerEvent', true);
  73551. textEl.silent = !link && !triggerEvent;
  73552. subTextEl.silent = !sublink && !triggerEvent;
  73553. if (link) {
  73554. textEl.on('click', function () {
  73555. windowOpen(link, '_' + titleModel.get('target'));
  73556. });
  73557. }
  73558. if (sublink) {
  73559. subTextEl.on('click', function () {
  73560. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  73561. });
  73562. }
  73563. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  73564. componentType: 'title',
  73565. componentIndex: titleModel.componentIndex
  73566. } : null;
  73567. group.add(textEl);
  73568. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  73569. var groupRect = group.getBoundingRect();
  73570. var layoutOption = titleModel.getBoxLayoutParams();
  73571. layoutOption.width = groupRect.width;
  73572. layoutOption.height = groupRect.height;
  73573. var layoutRect = getLayoutRect(layoutOption, {
  73574. width: api.getWidth(),
  73575. height: api.getHeight()
  73576. }, titleModel.get('padding')); // Adjust text align based on position
  73577. if (!textAlign) {
  73578. // Align left if title is on the left. center and right is same
  73579. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  73580. if (textAlign === 'middle') {
  73581. textAlign = 'center';
  73582. } // Adjust layout by text align
  73583. if (textAlign === 'right') {
  73584. layoutRect.x += layoutRect.width;
  73585. } else if (textAlign === 'center') {
  73586. layoutRect.x += layoutRect.width / 2;
  73587. }
  73588. }
  73589. if (!textVerticalAlign) {
  73590. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  73591. if (textVerticalAlign === 'center') {
  73592. textVerticalAlign = 'middle';
  73593. }
  73594. if (textVerticalAlign === 'bottom') {
  73595. layoutRect.y += layoutRect.height;
  73596. } else if (textVerticalAlign === 'middle') {
  73597. layoutRect.y += layoutRect.height / 2;
  73598. }
  73599. textVerticalAlign = textVerticalAlign || 'top';
  73600. }
  73601. group.x = layoutRect.x;
  73602. group.y = layoutRect.y;
  73603. group.markRedraw();
  73604. var alignStyle = {
  73605. align: textAlign,
  73606. verticalAlign: textVerticalAlign
  73607. };
  73608. textEl.setStyle(alignStyle);
  73609. subTextEl.setStyle(alignStyle); // Render background
  73610. // Get groupRect again because textAlign has been changed
  73611. groupRect = group.getBoundingRect();
  73612. var padding = layoutRect.margin;
  73613. var style = titleModel.getItemStyle(['color', 'opacity']);
  73614. style.fill = titleModel.get('backgroundColor');
  73615. var rect = new Rect({
  73616. shape: {
  73617. x: groupRect.x - padding[3],
  73618. y: groupRect.y - padding[0],
  73619. width: groupRect.width + padding[1] + padding[3],
  73620. height: groupRect.height + padding[0] + padding[2],
  73621. r: titleModel.get('borderRadius')
  73622. },
  73623. style: style,
  73624. subPixelOptimize: true,
  73625. silent: true
  73626. });
  73627. group.add(rect);
  73628. };
  73629. TitleView.type = 'title';
  73630. return TitleView;
  73631. }(ComponentView);
  73632. function install$C(registers) {
  73633. registers.registerComponentModel(TitleModel);
  73634. registers.registerComponentView(TitleView);
  73635. }
  73636. var TimelineModel =
  73637. /** @class */
  73638. function (_super) {
  73639. __extends(TimelineModel, _super);
  73640. function TimelineModel() {
  73641. var _this = _super !== null && _super.apply(this, arguments) || this;
  73642. _this.type = TimelineModel.type;
  73643. _this.layoutMode = 'box';
  73644. return _this;
  73645. }
  73646. /**
  73647. * @override
  73648. */
  73649. TimelineModel.prototype.init = function (option, parentModel, ecModel) {
  73650. this.mergeDefaultAndTheme(option, ecModel);
  73651. this._initData();
  73652. };
  73653. /**
  73654. * @override
  73655. */
  73656. TimelineModel.prototype.mergeOption = function (option) {
  73657. _super.prototype.mergeOption.apply(this, arguments);
  73658. this._initData();
  73659. };
  73660. TimelineModel.prototype.setCurrentIndex = function (currentIndex) {
  73661. if (currentIndex == null) {
  73662. currentIndex = this.option.currentIndex;
  73663. }
  73664. var count = this._data.count();
  73665. if (this.option.loop) {
  73666. currentIndex = (currentIndex % count + count) % count;
  73667. } else {
  73668. currentIndex >= count && (currentIndex = count - 1);
  73669. currentIndex < 0 && (currentIndex = 0);
  73670. }
  73671. this.option.currentIndex = currentIndex;
  73672. };
  73673. /**
  73674. * @return {number} currentIndex
  73675. */
  73676. TimelineModel.prototype.getCurrentIndex = function () {
  73677. return this.option.currentIndex;
  73678. };
  73679. /**
  73680. * @return {boolean}
  73681. */
  73682. TimelineModel.prototype.isIndexMax = function () {
  73683. return this.getCurrentIndex() >= this._data.count() - 1;
  73684. };
  73685. /**
  73686. * @param {boolean} state true: play, false: stop
  73687. */
  73688. TimelineModel.prototype.setPlayState = function (state) {
  73689. this.option.autoPlay = !!state;
  73690. };
  73691. /**
  73692. * @return {boolean} true: play, false: stop
  73693. */
  73694. TimelineModel.prototype.getPlayState = function () {
  73695. return !!this.option.autoPlay;
  73696. };
  73697. /**
  73698. * @private
  73699. */
  73700. TimelineModel.prototype._initData = function () {
  73701. var thisOption = this.option;
  73702. var dataArr = thisOption.data || [];
  73703. var axisType = thisOption.axisType;
  73704. var names = this._names = [];
  73705. var processedDataArr;
  73706. if (axisType === 'category') {
  73707. processedDataArr = [];
  73708. each(dataArr, function (item, index) {
  73709. var value = convertOptionIdName(getDataItemValue(item), '');
  73710. var newItem;
  73711. if (isObject(item)) {
  73712. newItem = clone(item);
  73713. newItem.value = index;
  73714. } else {
  73715. newItem = index;
  73716. }
  73717. processedDataArr.push(newItem);
  73718. names.push(value);
  73719. });
  73720. } else {
  73721. processedDataArr = dataArr;
  73722. }
  73723. var dimType = {
  73724. category: 'ordinal',
  73725. time: 'time',
  73726. value: 'number'
  73727. }[axisType] || 'number';
  73728. var data = this._data = new SeriesData([{
  73729. name: 'value',
  73730. type: dimType
  73731. }], this);
  73732. data.initData(processedDataArr, names);
  73733. };
  73734. TimelineModel.prototype.getData = function () {
  73735. return this._data;
  73736. };
  73737. /**
  73738. * @public
  73739. * @return {Array.<string>} categoreis
  73740. */
  73741. TimelineModel.prototype.getCategories = function () {
  73742. if (this.get('axisType') === 'category') {
  73743. return this._names.slice();
  73744. }
  73745. };
  73746. TimelineModel.type = 'timeline';
  73747. /**
  73748. * @protected
  73749. */
  73750. TimelineModel.defaultOption = {
  73751. // zlevel: 0, // 一级层叠
  73752. z: 4,
  73753. show: true,
  73754. axisType: 'time',
  73755. realtime: true,
  73756. left: '20%',
  73757. top: null,
  73758. right: '20%',
  73759. bottom: 0,
  73760. width: null,
  73761. height: 40,
  73762. padding: 5,
  73763. controlPosition: 'left',
  73764. autoPlay: false,
  73765. rewind: false,
  73766. loop: true,
  73767. playInterval: 2000,
  73768. currentIndex: 0,
  73769. itemStyle: {},
  73770. label: {
  73771. color: '#000'
  73772. },
  73773. data: []
  73774. };
  73775. return TimelineModel;
  73776. }(ComponentModel);
  73777. var SliderTimelineModel =
  73778. /** @class */
  73779. function (_super) {
  73780. __extends(SliderTimelineModel, _super);
  73781. function SliderTimelineModel() {
  73782. var _this = _super !== null && _super.apply(this, arguments) || this;
  73783. _this.type = SliderTimelineModel.type;
  73784. return _this;
  73785. }
  73786. SliderTimelineModel.type = 'timeline.slider';
  73787. /**
  73788. * @protected
  73789. */
  73790. SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, {
  73791. backgroundColor: 'rgba(0,0,0,0)',
  73792. borderColor: '#ccc',
  73793. borderWidth: 0,
  73794. orient: 'horizontal',
  73795. inverse: false,
  73796. tooltip: {
  73797. trigger: 'item' // data item may also have tootip attr.
  73798. },
  73799. symbol: 'circle',
  73800. symbolSize: 12,
  73801. lineStyle: {
  73802. show: true,
  73803. width: 2,
  73804. color: '#DAE1F5'
  73805. },
  73806. label: {
  73807. position: 'auto',
  73808. // When using number, label position is not
  73809. // restricted by viewRect.
  73810. // positive: right/bottom, negative: left/top
  73811. show: true,
  73812. interval: 'auto',
  73813. rotate: 0,
  73814. // formatter: null,
  73815. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73816. color: '#A4B1D7'
  73817. },
  73818. itemStyle: {
  73819. color: '#A4B1D7',
  73820. borderWidth: 1
  73821. },
  73822. checkpointStyle: {
  73823. symbol: 'circle',
  73824. symbolSize: 15,
  73825. color: '#316bf3',
  73826. borderColor: '#fff',
  73827. borderWidth: 2,
  73828. shadowBlur: 2,
  73829. shadowOffsetX: 1,
  73830. shadowOffsetY: 1,
  73831. shadowColor: 'rgba(0, 0, 0, 0.3)',
  73832. // borderColor: 'rgba(194,53,49, 0.5)',
  73833. animation: true,
  73834. animationDuration: 300,
  73835. animationEasing: 'quinticInOut'
  73836. },
  73837. controlStyle: {
  73838. show: true,
  73839. showPlayBtn: true,
  73840. showPrevBtn: true,
  73841. showNextBtn: true,
  73842. itemSize: 24,
  73843. itemGap: 12,
  73844. position: 'left',
  73845. 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',
  73846. 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',
  73847. // eslint-disable-next-line max-len
  73848. 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',
  73849. // eslint-disable-next-line max-len
  73850. 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',
  73851. prevBtnSize: 18,
  73852. nextBtnSize: 18,
  73853. color: '#A4B1D7',
  73854. borderColor: '#A4B1D7',
  73855. borderWidth: 1
  73856. },
  73857. emphasis: {
  73858. label: {
  73859. show: true,
  73860. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  73861. color: '#6f778d'
  73862. },
  73863. itemStyle: {
  73864. color: '#316BF3'
  73865. },
  73866. controlStyle: {
  73867. color: '#316BF3',
  73868. borderColor: '#316BF3',
  73869. borderWidth: 2
  73870. }
  73871. },
  73872. progress: {
  73873. lineStyle: {
  73874. color: '#316BF3'
  73875. },
  73876. itemStyle: {
  73877. color: '#316BF3'
  73878. },
  73879. label: {
  73880. color: '#6f778d'
  73881. }
  73882. },
  73883. data: []
  73884. });
  73885. return SliderTimelineModel;
  73886. }(TimelineModel);
  73887. mixin(SliderTimelineModel, DataFormatMixin.prototype);
  73888. var TimelineView =
  73889. /** @class */
  73890. function (_super) {
  73891. __extends(TimelineView, _super);
  73892. function TimelineView() {
  73893. var _this = _super !== null && _super.apply(this, arguments) || this;
  73894. _this.type = TimelineView.type;
  73895. return _this;
  73896. }
  73897. TimelineView.type = 'timeline';
  73898. return TimelineView;
  73899. }(ComponentView);
  73900. /**
  73901. * Extend axis 2d
  73902. */
  73903. var TimelineAxis =
  73904. /** @class */
  73905. function (_super) {
  73906. __extends(TimelineAxis, _super);
  73907. function TimelineAxis(dim, scale, coordExtent, axisType) {
  73908. var _this = _super.call(this, dim, scale, coordExtent) || this;
  73909. _this.type = axisType || 'value';
  73910. return _this;
  73911. }
  73912. /**
  73913. * @override
  73914. */
  73915. TimelineAxis.prototype.getLabelModel = function () {
  73916. // Force override
  73917. return this.model.getModel('label');
  73918. };
  73919. /**
  73920. * @override
  73921. */
  73922. TimelineAxis.prototype.isHorizontal = function () {
  73923. return this.model.get('orient') === 'horizontal';
  73924. };
  73925. return TimelineAxis;
  73926. }(Axis);
  73927. var PI$8 = Math.PI;
  73928. var labelDataIndexStore = makeInner();
  73929. var SliderTimelineView =
  73930. /** @class */
  73931. function (_super) {
  73932. __extends(SliderTimelineView, _super);
  73933. function SliderTimelineView() {
  73934. var _this = _super !== null && _super.apply(this, arguments) || this;
  73935. _this.type = SliderTimelineView.type;
  73936. return _this;
  73937. }
  73938. SliderTimelineView.prototype.init = function (ecModel, api) {
  73939. this.api = api;
  73940. };
  73941. /**
  73942. * @override
  73943. */
  73944. SliderTimelineView.prototype.render = function (timelineModel, ecModel, api) {
  73945. this.model = timelineModel;
  73946. this.api = api;
  73947. this.ecModel = ecModel;
  73948. this.group.removeAll();
  73949. if (timelineModel.get('show', true)) {
  73950. var layoutInfo_1 = this._layout(timelineModel, api);
  73951. var mainGroup_1 = this._createGroup('_mainGroup');
  73952. var labelGroup = this._createGroup('_labelGroup');
  73953. var axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel);
  73954. timelineModel.formatTooltip = function (dataIndex) {
  73955. var name = axis_1.scale.getLabel({
  73956. value: dataIndex
  73957. });
  73958. return createTooltipMarkup('nameValue', {
  73959. noName: true,
  73960. value: name
  73961. });
  73962. };
  73963. each(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  73964. this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel);
  73965. }, this);
  73966. this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel);
  73967. this._position(layoutInfo_1, timelineModel);
  73968. }
  73969. this._doPlayStop();
  73970. this._updateTicksStatus();
  73971. };
  73972. /**
  73973. * @override
  73974. */
  73975. SliderTimelineView.prototype.remove = function () {
  73976. this._clearTimer();
  73977. this.group.removeAll();
  73978. };
  73979. /**
  73980. * @override
  73981. */
  73982. SliderTimelineView.prototype.dispose = function () {
  73983. this._clearTimer();
  73984. };
  73985. SliderTimelineView.prototype._layout = function (timelineModel, api) {
  73986. var labelPosOpt = timelineModel.get(['label', 'position']);
  73987. var orient = timelineModel.get('orient');
  73988. var viewRect = getViewRect$5(timelineModel, api);
  73989. var parsedLabelPos; // Auto label offset.
  73990. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73991. parsedLabelPos = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  73992. } else if (isString(labelPosOpt)) {
  73993. parsedLabelPos = {
  73994. horizontal: {
  73995. top: '-',
  73996. bottom: '+'
  73997. },
  73998. vertical: {
  73999. left: '-',
  74000. right: '+'
  74001. }
  74002. }[orient][labelPosOpt];
  74003. } else {
  74004. // is number
  74005. parsedLabelPos = labelPosOpt;
  74006. }
  74007. var labelAlignMap = {
  74008. horizontal: 'center',
  74009. vertical: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'left' : 'right'
  74010. };
  74011. var labelBaselineMap = {
  74012. horizontal: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'top' : 'bottom',
  74013. vertical: 'middle'
  74014. };
  74015. var rotationMap = {
  74016. horizontal: 0,
  74017. vertical: PI$8 / 2
  74018. }; // Position
  74019. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  74020. var controlModel = timelineModel.getModel('controlStyle');
  74021. var showControl = controlModel.get('show', true);
  74022. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  74023. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  74024. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  74025. var labelRotation = timelineModel.get(['label', 'rotate']) || 0;
  74026. labelRotation = labelRotation * PI$8 / 180; // To radian.
  74027. var playPosition;
  74028. var prevBtnPosition;
  74029. var nextBtnPosition;
  74030. var controlPosition = controlModel.get('position', true);
  74031. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  74032. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  74033. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  74034. var xLeft = 0;
  74035. var xRight = mainLength; // position[0] means left, position[1] means middle.
  74036. if (controlPosition === 'left' || controlPosition === 'bottom') {
  74037. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  74038. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  74039. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74040. } else {
  74041. // 'top' 'right'
  74042. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74043. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  74044. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  74045. }
  74046. var axisExtent = [xLeft, xRight];
  74047. if (timelineModel.get('inverse')) {
  74048. axisExtent.reverse();
  74049. }
  74050. return {
  74051. viewRect: viewRect,
  74052. mainLength: mainLength,
  74053. orient: orient,
  74054. rotation: rotationMap[orient],
  74055. labelRotation: labelRotation,
  74056. labelPosOpt: parsedLabelPos,
  74057. labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient],
  74058. labelBaseline: timelineModel.get(['label', 'verticalAlign']) || timelineModel.get(['label', 'baseline']) || labelBaselineMap[orient],
  74059. // Based on mainGroup.
  74060. playPosition: playPosition,
  74061. prevBtnPosition: prevBtnPosition,
  74062. nextBtnPosition: nextBtnPosition,
  74063. axisExtent: axisExtent,
  74064. controlSize: controlSize,
  74065. controlGap: controlGap
  74066. };
  74067. };
  74068. SliderTimelineView.prototype._position = function (layoutInfo, timelineModel) {
  74069. // Position is be called finally, because bounding rect is needed for
  74070. // adapt content to fill viewRect (auto adapt offset).
  74071. // Timeline may be not all in the viewRect when 'offset' is specified
  74072. // as a number, because it is more appropriate that label aligns at
  74073. // 'offset' but not the other edge defined by viewRect.
  74074. var mainGroup = this._mainGroup;
  74075. var labelGroup = this._labelGroup;
  74076. var viewRect = layoutInfo.viewRect;
  74077. if (layoutInfo.orient === 'vertical') {
  74078. // transform to horizontal, inverse rotate by left-top point.
  74079. var m = create$1();
  74080. var rotateOriginX = viewRect.x;
  74081. var rotateOriginY = viewRect.y + viewRect.height;
  74082. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  74083. rotate(m, m, -PI$8 / 2);
  74084. translate(m, m, [rotateOriginX, rotateOriginY]);
  74085. viewRect = viewRect.clone();
  74086. viewRect.applyTransform(m);
  74087. }
  74088. var viewBound = getBound(viewRect);
  74089. var mainBound = getBound(mainGroup.getBoundingRect());
  74090. var labelBound = getBound(labelGroup.getBoundingRect());
  74091. var mainPosition = [mainGroup.x, mainGroup.y];
  74092. var labelsPosition = [labelGroup.x, labelGroup.y];
  74093. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  74094. var labelPosOpt = layoutInfo.labelPosOpt;
  74095. if (labelPosOpt == null || isString(labelPosOpt)) {
  74096. // '+' or '-'
  74097. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  74098. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  74099. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  74100. } else {
  74101. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  74102. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  74103. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  74104. }
  74105. mainGroup.setPosition(mainPosition);
  74106. labelGroup.setPosition(labelsPosition);
  74107. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  74108. setOrigin(mainGroup);
  74109. setOrigin(labelGroup);
  74110. function setOrigin(targetGroup) {
  74111. targetGroup.originX = viewBound[0][0] - targetGroup.x;
  74112. targetGroup.originY = viewBound[1][0] - targetGroup.y;
  74113. }
  74114. function getBound(rect) {
  74115. // [[xmin, xmax], [ymin, ymax]]
  74116. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  74117. }
  74118. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  74119. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  74120. }
  74121. };
  74122. SliderTimelineView.prototype._createAxis = function (layoutInfo, timelineModel) {
  74123. var data = timelineModel.getData();
  74124. var axisType = timelineModel.get('axisType');
  74125. var scale = createScaleByModel$1(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  74126. scale.getTicks = function () {
  74127. return data.mapArray(['value'], function (value) {
  74128. return {
  74129. value: value
  74130. };
  74131. });
  74132. };
  74133. var dataExtent = data.getDataExtent('value');
  74134. scale.setExtent(dataExtent[0], dataExtent[1]);
  74135. scale.calcNiceTicks();
  74136. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  74137. axis.model = timelineModel;
  74138. return axis;
  74139. };
  74140. SliderTimelineView.prototype._createGroup = function (key) {
  74141. var newGroup = this[key] = new Group();
  74142. this.group.add(newGroup);
  74143. return newGroup;
  74144. };
  74145. SliderTimelineView.prototype._renderAxisLine = function (layoutInfo, group, axis, timelineModel) {
  74146. var axisExtent = axis.getExtent();
  74147. if (!timelineModel.get(['lineStyle', 'show'])) {
  74148. return;
  74149. }
  74150. var line = new Line({
  74151. shape: {
  74152. x1: axisExtent[0],
  74153. y1: 0,
  74154. x2: axisExtent[1],
  74155. y2: 0
  74156. },
  74157. style: extend({
  74158. lineCap: 'round'
  74159. }, timelineModel.getModel('lineStyle').getLineStyle()),
  74160. silent: true,
  74161. z2: 1
  74162. });
  74163. group.add(line);
  74164. var progressLine = this._progressLine = new Line({
  74165. shape: {
  74166. x1: axisExtent[0],
  74167. x2: this._currentPointer ? this._currentPointer.x : axisExtent[0],
  74168. y1: 0,
  74169. y2: 0
  74170. },
  74171. style: defaults({
  74172. lineCap: 'round',
  74173. lineWidth: line.style.lineWidth
  74174. }, timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()),
  74175. silent: true,
  74176. z2: 1
  74177. });
  74178. group.add(progressLine);
  74179. };
  74180. SliderTimelineView.prototype._renderAxisTick = function (layoutInfo, group, axis, timelineModel) {
  74181. var _this = this;
  74182. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  74183. var ticks = axis.scale.getTicks();
  74184. this._tickSymbols = []; // The value is dataIndex, see the customized scale.
  74185. each(ticks, function (tick) {
  74186. var tickCoord = axis.dataToCoord(tick.value);
  74187. var itemModel = data.getItemModel(tick.value);
  74188. var itemStyleModel = itemModel.getModel('itemStyle');
  74189. var hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
  74190. var progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
  74191. var symbolOpt = {
  74192. x: tickCoord,
  74193. y: 0,
  74194. onclick: bind(_this._changeTimeline, _this, tick.value)
  74195. };
  74196. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  74197. el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
  74198. el.ensureState('progress').style = progressStyleModel.getItemStyle();
  74199. enableHoverEmphasis(el);
  74200. var ecData = getECData(el);
  74201. if (itemModel.get('tooltip')) {
  74202. ecData.dataIndex = tick.value;
  74203. ecData.dataModel = timelineModel;
  74204. } else {
  74205. ecData.dataIndex = ecData.dataModel = null;
  74206. }
  74207. _this._tickSymbols.push(el);
  74208. });
  74209. };
  74210. SliderTimelineView.prototype._renderAxisLabel = function (layoutInfo, group, axis, timelineModel) {
  74211. var _this = this;
  74212. var labelModel = axis.getLabelModel();
  74213. if (!labelModel.get('show')) {
  74214. return;
  74215. }
  74216. var data = timelineModel.getData();
  74217. var labels = axis.getViewLabels();
  74218. this._tickLabels = [];
  74219. each(labels, function (labelItem) {
  74220. // The tickValue is dataIndex, see the customized scale.
  74221. var dataIndex = labelItem.tickValue;
  74222. var itemModel = data.getItemModel(dataIndex);
  74223. var normalLabelModel = itemModel.getModel('label');
  74224. var hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
  74225. var progressLabelModel = itemModel.getModel(['progress', 'label']);
  74226. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  74227. var textEl = new ZRText({
  74228. x: tickCoord,
  74229. y: 0,
  74230. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  74231. onclick: bind(_this._changeTimeline, _this, dataIndex),
  74232. silent: false,
  74233. style: createTextStyle(normalLabelModel, {
  74234. text: labelItem.formattedLabel,
  74235. align: layoutInfo.labelAlign,
  74236. verticalAlign: layoutInfo.labelBaseline
  74237. })
  74238. });
  74239. textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
  74240. textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
  74241. group.add(textEl);
  74242. enableHoverEmphasis(textEl);
  74243. labelDataIndexStore(textEl).dataIndex = dataIndex;
  74244. _this._tickLabels.push(textEl);
  74245. });
  74246. };
  74247. SliderTimelineView.prototype._renderControl = function (layoutInfo, group, axis, timelineModel) {
  74248. var controlSize = layoutInfo.controlSize;
  74249. var rotation = layoutInfo.rotation;
  74250. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  74251. var hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
  74252. var playState = timelineModel.getPlayState();
  74253. var inverse = timelineModel.get('inverse', true);
  74254. makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+'));
  74255. makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-'));
  74256. makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), true);
  74257. function makeBtn(position, iconName, onclick, willRotate) {
  74258. if (!position) {
  74259. return;
  74260. }
  74261. var iconSize = parsePercent(retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize']), controlSize), controlSize);
  74262. var rect = [0, -iconSize / 2, iconSize, iconSize];
  74263. var btn = makeControlIcon(timelineModel, iconName + 'Icon', rect, {
  74264. x: position[0],
  74265. y: position[1],
  74266. originX: controlSize / 2,
  74267. originY: 0,
  74268. rotation: willRotate ? -rotation : 0,
  74269. rectHover: true,
  74270. style: itemStyle,
  74271. onclick: onclick
  74272. });
  74273. btn.ensureState('emphasis').style = hoverStyle;
  74274. group.add(btn);
  74275. enableHoverEmphasis(btn);
  74276. }
  74277. };
  74278. SliderTimelineView.prototype._renderCurrentPointer = function (layoutInfo, group, axis, timelineModel) {
  74279. var data = timelineModel.getData();
  74280. var currentIndex = timelineModel.getCurrentIndex();
  74281. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  74282. var me = this;
  74283. var callback = {
  74284. onCreate: function (pointer) {
  74285. pointer.draggable = true;
  74286. pointer.drift = bind(me._handlePointerDrag, me);
  74287. pointer.ondragend = bind(me._handlePointerDragend, me);
  74288. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
  74289. },
  74290. onUpdate: function (pointer) {
  74291. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
  74292. }
  74293. }; // Reuse when exists, for animation and drag.
  74294. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  74295. };
  74296. SliderTimelineView.prototype._handlePlayClick = function (nextState) {
  74297. this._clearTimer();
  74298. this.api.dispatchAction({
  74299. type: 'timelinePlayChange',
  74300. playState: nextState,
  74301. from: this.uid
  74302. });
  74303. };
  74304. SliderTimelineView.prototype._handlePointerDrag = function (dx, dy, e) {
  74305. this._clearTimer();
  74306. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  74307. };
  74308. SliderTimelineView.prototype._handlePointerDragend = function (e) {
  74309. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  74310. };
  74311. SliderTimelineView.prototype._pointerChangeTimeline = function (mousePos, trigger) {
  74312. var toCoord = this._toAxisCoord(mousePos)[0];
  74313. var axis = this._axis;
  74314. var axisExtent = asc(axis.getExtent().slice());
  74315. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  74316. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  74317. this._currentPointer.x = toCoord;
  74318. this._currentPointer.markRedraw();
  74319. var progressLine = this._progressLine;
  74320. if (progressLine) {
  74321. progressLine.shape.x2 = toCoord;
  74322. progressLine.dirty();
  74323. }
  74324. var targetDataIndex = this._findNearestTick(toCoord);
  74325. var timelineModel = this.model;
  74326. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  74327. this._changeTimeline(targetDataIndex);
  74328. }
  74329. };
  74330. SliderTimelineView.prototype._doPlayStop = function () {
  74331. var _this = this;
  74332. this._clearTimer();
  74333. if (this.model.getPlayState()) {
  74334. this._timer = setTimeout(function () {
  74335. // Do not cache
  74336. var timelineModel = _this.model;
  74337. _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  74338. }, this.model.get('playInterval'));
  74339. }
  74340. };
  74341. SliderTimelineView.prototype._toAxisCoord = function (vertex) {
  74342. var trans = this._mainGroup.getLocalTransform();
  74343. return applyTransform$1(vertex, trans, true);
  74344. };
  74345. SliderTimelineView.prototype._findNearestTick = function (axisCoord) {
  74346. var data = this.model.getData();
  74347. var dist = Infinity;
  74348. var targetDataIndex;
  74349. var axis = this._axis;
  74350. data.each(['value'], function (value, dataIndex) {
  74351. var coord = axis.dataToCoord(value);
  74352. var d = Math.abs(coord - axisCoord);
  74353. if (d < dist) {
  74354. dist = d;
  74355. targetDataIndex = dataIndex;
  74356. }
  74357. });
  74358. return targetDataIndex;
  74359. };
  74360. SliderTimelineView.prototype._clearTimer = function () {
  74361. if (this._timer) {
  74362. clearTimeout(this._timer);
  74363. this._timer = null;
  74364. }
  74365. };
  74366. SliderTimelineView.prototype._changeTimeline = function (nextIndex) {
  74367. var currentIndex = this.model.getCurrentIndex();
  74368. if (nextIndex === '+') {
  74369. nextIndex = currentIndex + 1;
  74370. } else if (nextIndex === '-') {
  74371. nextIndex = currentIndex - 1;
  74372. }
  74373. this.api.dispatchAction({
  74374. type: 'timelineChange',
  74375. currentIndex: nextIndex,
  74376. from: this.uid
  74377. });
  74378. };
  74379. SliderTimelineView.prototype._updateTicksStatus = function () {
  74380. var currentIndex = this.model.getCurrentIndex();
  74381. var tickSymbols = this._tickSymbols;
  74382. var tickLabels = this._tickLabels;
  74383. if (tickSymbols) {
  74384. for (var i = 0; i < tickSymbols.length; i++) {
  74385. tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex);
  74386. }
  74387. }
  74388. if (tickLabels) {
  74389. for (var i = 0; i < tickLabels.length; i++) {
  74390. tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex);
  74391. }
  74392. }
  74393. };
  74394. SliderTimelineView.type = 'timeline.slider';
  74395. return SliderTimelineView;
  74396. }(TimelineView);
  74397. function createScaleByModel$1(model, axisType) {
  74398. axisType = axisType || model.get('type');
  74399. if (axisType) {
  74400. switch (axisType) {
  74401. // Buildin scale
  74402. case 'category':
  74403. return new OrdinalScale({
  74404. ordinalMeta: model.getCategories(),
  74405. extent: [Infinity, -Infinity]
  74406. });
  74407. case 'time':
  74408. return new TimeScale({
  74409. locale: model.ecModel.getLocaleModel(),
  74410. useUTC: model.ecModel.get('useUTC')
  74411. });
  74412. default:
  74413. // default to be value
  74414. return new IntervalScale();
  74415. }
  74416. }
  74417. }
  74418. function getViewRect$5(model, api) {
  74419. return getLayoutRect(model.getBoxLayoutParams(), {
  74420. width: api.getWidth(),
  74421. height: api.getHeight()
  74422. }, model.get('padding'));
  74423. }
  74424. function makeControlIcon(timelineModel, objPath, rect, opts) {
  74425. var style = opts.style;
  74426. 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.
  74427. if (style) {
  74428. icon.setStyle(style);
  74429. }
  74430. return icon;
  74431. }
  74432. /**
  74433. * Create symbol or update symbol
  74434. * opt: basic position and event handlers
  74435. */
  74436. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  74437. var color = itemStyleModel.get('color');
  74438. if (!symbol) {
  74439. var symbolType = hostModel.get('symbol');
  74440. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  74441. symbol.setStyle('strokeNoScale', true);
  74442. group.add(symbol);
  74443. callback && callback.onCreate(symbol);
  74444. } else {
  74445. symbol.setColor(color);
  74446. group.add(symbol); // Group may be new, also need to add.
  74447. callback && callback.onUpdate(symbol);
  74448. } // Style
  74449. var itemStyle = itemStyleModel.getItemStyle(['color']);
  74450. symbol.setStyle(itemStyle); // Transform and events.
  74451. opt = merge({
  74452. rectHover: true,
  74453. z2: 100
  74454. }, opt, true);
  74455. var symbolSize = normalizeSymbolSize(hostModel.get('symbolSize'));
  74456. opt.scaleX = symbolSize[0] / 2;
  74457. opt.scaleY = symbolSize[1] / 2;
  74458. var symbolOffset = normalizeSymbolOffset(hostModel.get('symbolOffset'), symbolSize);
  74459. if (symbolOffset) {
  74460. opt.x = (opt.x || 0) + symbolOffset[0];
  74461. opt.y = (opt.y || 0) + symbolOffset[1];
  74462. }
  74463. var symbolRotate = hostModel.get('symbolRotate');
  74464. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  74465. symbol.attr(opt); // FIXME
  74466. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  74467. // getBoundingRect will return wrong result.
  74468. // (This is supposed to be resolved in zrender, but it is a little difficult to
  74469. // leverage performance and auto updateTransform)
  74470. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  74471. symbol.updateTransform();
  74472. return symbol;
  74473. }
  74474. function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) {
  74475. if (pointer.dragging) {
  74476. return;
  74477. }
  74478. var pointerModel = timelineModel.getModel('checkpointStyle');
  74479. var toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
  74480. if (noAnimation || !pointerModel.get('animation', true)) {
  74481. pointer.attr({
  74482. x: toCoord,
  74483. y: 0
  74484. });
  74485. progressLine && progressLine.attr({
  74486. shape: {
  74487. x2: toCoord
  74488. }
  74489. });
  74490. } else {
  74491. var animationCfg = {
  74492. duration: pointerModel.get('animationDuration', true),
  74493. easing: pointerModel.get('animationEasing', true)
  74494. };
  74495. pointer.stopAnimation(null, true);
  74496. pointer.animateTo({
  74497. x: toCoord,
  74498. y: 0
  74499. }, animationCfg);
  74500. progressLine && progressLine.animateTo({
  74501. shape: {
  74502. x2: toCoord
  74503. }
  74504. }, animationCfg);
  74505. }
  74506. }
  74507. function installTimelineAction(registers) {
  74508. registers.registerAction({
  74509. type: 'timelineChange',
  74510. event: 'timelineChanged',
  74511. update: 'prepareAndUpdate'
  74512. }, function (payload, ecModel, api) {
  74513. var timelineModel = ecModel.getComponent('timeline');
  74514. if (timelineModel && payload.currentIndex != null) {
  74515. timelineModel.setCurrentIndex(payload.currentIndex);
  74516. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax() && timelineModel.getPlayState()) {
  74517. timelineModel.setPlayState(false); // The timeline has played to the end, trigger event
  74518. api.dispatchAction({
  74519. type: 'timelinePlayChange',
  74520. playState: false,
  74521. from: payload.from
  74522. });
  74523. }
  74524. } // Set normalized currentIndex to payload.
  74525. ecModel.resetOption('timeline', {
  74526. replaceMerge: timelineModel.get('replaceMerge', true)
  74527. });
  74528. return defaults({
  74529. currentIndex: timelineModel.option.currentIndex
  74530. }, payload);
  74531. });
  74532. registers.registerAction({
  74533. type: 'timelinePlayChange',
  74534. event: 'timelinePlayChanged',
  74535. update: 'update'
  74536. }, function (payload, ecModel) {
  74537. var timelineModel = ecModel.getComponent('timeline');
  74538. if (timelineModel && payload.playState != null) {
  74539. timelineModel.setPlayState(payload.playState);
  74540. }
  74541. });
  74542. }
  74543. function timelinePreprocessor(option) {
  74544. var timelineOpt = option && option.timeline;
  74545. if (!isArray(timelineOpt)) {
  74546. timelineOpt = timelineOpt ? [timelineOpt] : [];
  74547. }
  74548. each(timelineOpt, function (opt) {
  74549. if (!opt) {
  74550. return;
  74551. }
  74552. compatibleEC2(opt);
  74553. });
  74554. }
  74555. function compatibleEC2(opt) {
  74556. var type = opt.type;
  74557. var ec2Types = {
  74558. 'number': 'value',
  74559. 'time': 'time'
  74560. }; // Compatible with ec2
  74561. if (ec2Types[type]) {
  74562. opt.axisType = ec2Types[type];
  74563. delete opt.type;
  74564. }
  74565. transferItem(opt);
  74566. if (has(opt, 'controlPosition')) {
  74567. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  74568. if (!has(controlStyle, 'position')) {
  74569. controlStyle.position = opt.controlPosition;
  74570. }
  74571. if (controlStyle.position === 'none' && !has(controlStyle, 'show')) {
  74572. controlStyle.show = false;
  74573. delete controlStyle.position;
  74574. }
  74575. delete opt.controlPosition;
  74576. }
  74577. each(opt.data || [], function (dataItem) {
  74578. if (isObject(dataItem) && !isArray(dataItem)) {
  74579. if (!has(dataItem, 'value') && has(dataItem, 'name')) {
  74580. // In ec2, using name as value.
  74581. dataItem.value = dataItem.name;
  74582. }
  74583. transferItem(dataItem);
  74584. }
  74585. });
  74586. }
  74587. function transferItem(opt) {
  74588. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  74589. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  74590. var label = opt.label || opt.label || {};
  74591. var labelNormal = label.normal || (label.normal = {});
  74592. var excludeLabelAttr = {
  74593. normal: 1,
  74594. emphasis: 1
  74595. };
  74596. each(label, function (value, name) {
  74597. if (!excludeLabelAttr[name] && !has(labelNormal, name)) {
  74598. labelNormal[name] = value;
  74599. }
  74600. });
  74601. if (itemStyleEmphasis.label && !has(label, 'emphasis')) {
  74602. label.emphasis = itemStyleEmphasis.label;
  74603. delete itemStyleEmphasis.label;
  74604. }
  74605. }
  74606. function has(obj, attr) {
  74607. return obj.hasOwnProperty(attr);
  74608. }
  74609. function install$D(registers) {
  74610. registers.registerComponentModel(SliderTimelineModel);
  74611. registers.registerComponentView(SliderTimelineView);
  74612. registers.registerSubTypeDefaulter('timeline', function () {
  74613. // Only slider now.
  74614. return 'slider';
  74615. });
  74616. installTimelineAction(registers);
  74617. registers.registerPreprocessor(timelinePreprocessor);
  74618. }
  74619. function checkMarkerInSeries(seriesOpts, markerType) {
  74620. if (!seriesOpts) {
  74621. return false;
  74622. }
  74623. var seriesOptArr = isArray(seriesOpts) ? seriesOpts : [seriesOpts];
  74624. for (var idx = 0; idx < seriesOptArr.length; idx++) {
  74625. if (seriesOptArr[idx] && seriesOptArr[idx][markerType]) {
  74626. return true;
  74627. }
  74628. }
  74629. return false;
  74630. }
  74631. function fillLabel(opt) {
  74632. defaultEmphasis(opt, 'label', ['show']);
  74633. } // { [componentType]: MarkerModel }
  74634. var inner$g = makeInner();
  74635. var MarkerModel =
  74636. /** @class */
  74637. function (_super) {
  74638. __extends(MarkerModel, _super);
  74639. function MarkerModel() {
  74640. var _this = _super !== null && _super.apply(this, arguments) || this;
  74641. _this.type = MarkerModel.type;
  74642. /**
  74643. * If marker model is created by self from series
  74644. */
  74645. _this.createdBySelf = false;
  74646. return _this;
  74647. }
  74648. /**
  74649. * @overrite
  74650. */
  74651. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  74652. if ("development" !== 'production') {
  74653. if (this.type === 'marker') {
  74654. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  74655. }
  74656. }
  74657. this.mergeDefaultAndTheme(option, ecModel);
  74658. this._mergeOption(option, ecModel, false, true);
  74659. };
  74660. MarkerModel.prototype.isAnimationEnabled = function () {
  74661. if (env.node) {
  74662. return false;
  74663. }
  74664. var hostSeries = this.__hostSeries;
  74665. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  74666. };
  74667. /**
  74668. * @overrite
  74669. */
  74670. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  74671. this._mergeOption(newOpt, ecModel, false, false);
  74672. };
  74673. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  74674. var componentType = this.mainType;
  74675. if (!createdBySelf) {
  74676. ecModel.eachSeries(function (seriesModel) {
  74677. // mainType can be markPoint, markLine, markArea
  74678. var markerOpt = seriesModel.get(this.mainType, true);
  74679. var markerModel = inner$g(seriesModel)[componentType];
  74680. if (!markerOpt || !markerOpt.data) {
  74681. inner$g(seriesModel)[componentType] = null;
  74682. return;
  74683. }
  74684. if (!markerModel) {
  74685. if (isInit) {
  74686. // Default label emphasis `position` and `show`
  74687. fillLabel(markerOpt);
  74688. }
  74689. each(markerOpt.data, function (item) {
  74690. // FIXME Overwrite fillLabel method ?
  74691. if (item instanceof Array) {
  74692. fillLabel(item[0]);
  74693. fillLabel(item[1]);
  74694. } else {
  74695. fillLabel(item);
  74696. }
  74697. });
  74698. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  74699. // markerOpt, this, ecModel
  74700. // );
  74701. extend(markerModel, {
  74702. mainType: this.mainType,
  74703. // Use the same series index and name
  74704. seriesIndex: seriesModel.seriesIndex,
  74705. name: seriesModel.name,
  74706. createdBySelf: true
  74707. });
  74708. markerModel.__hostSeries = seriesModel;
  74709. } else {
  74710. markerModel._mergeOption(markerOpt, ecModel, true);
  74711. }
  74712. inner$g(seriesModel)[componentType] = markerModel;
  74713. }, this);
  74714. }
  74715. };
  74716. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  74717. var data = this.getData();
  74718. var value = this.getRawValue(dataIndex);
  74719. var itemName = data.getName(dataIndex);
  74720. return createTooltipMarkup('section', {
  74721. header: this.name,
  74722. blocks: [createTooltipMarkup('nameValue', {
  74723. name: itemName,
  74724. value: value,
  74725. noName: !itemName,
  74726. noValue: value == null
  74727. })]
  74728. });
  74729. };
  74730. MarkerModel.prototype.getData = function () {
  74731. return this._data;
  74732. };
  74733. MarkerModel.prototype.setData = function (data) {
  74734. this._data = data;
  74735. };
  74736. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  74737. componentType) {
  74738. return inner$g(seriesModel)[componentType];
  74739. };
  74740. MarkerModel.type = 'marker';
  74741. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  74742. return MarkerModel;
  74743. }(ComponentModel);
  74744. mixin(MarkerModel, DataFormatMixin.prototype);
  74745. var MarkPointModel =
  74746. /** @class */
  74747. function (_super) {
  74748. __extends(MarkPointModel, _super);
  74749. function MarkPointModel() {
  74750. var _this = _super !== null && _super.apply(this, arguments) || this;
  74751. _this.type = MarkPointModel.type;
  74752. return _this;
  74753. }
  74754. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  74755. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  74756. };
  74757. MarkPointModel.type = 'markPoint';
  74758. MarkPointModel.defaultOption = {
  74759. // zlevel: 0,
  74760. z: 5,
  74761. symbol: 'pin',
  74762. symbolSize: 50,
  74763. // symbolRotate: 0,
  74764. // symbolOffset: [0, 0]
  74765. tooltip: {
  74766. trigger: 'item'
  74767. },
  74768. label: {
  74769. show: true,
  74770. position: 'inside'
  74771. },
  74772. itemStyle: {
  74773. borderWidth: 2
  74774. },
  74775. emphasis: {
  74776. label: {
  74777. show: true
  74778. }
  74779. }
  74780. };
  74781. return MarkPointModel;
  74782. }(MarkerModel);
  74783. function hasXOrY(item) {
  74784. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  74785. }
  74786. function hasXAndY(item) {
  74787. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  74788. }
  74789. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  74790. var coordArr = [];
  74791. var stacked = isDimensionStacked(data, targetDataDim
  74792. /* , otherDataDim */
  74793. );
  74794. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  74795. var value = numCalculate(data, calcDataDim, markerType);
  74796. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  74797. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  74798. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  74799. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  74800. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  74801. precision = Math.min(precision, 20);
  74802. if (precision >= 0) {
  74803. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  74804. }
  74805. return [coordArr, coordArrValue];
  74806. } // TODO Specified percent
  74807. var markerTypeCalculator = {
  74808. min: curry(markerTypeCalculatorWithExtent, 'min'),
  74809. max: curry(markerTypeCalculatorWithExtent, 'max'),
  74810. average: curry(markerTypeCalculatorWithExtent, 'average'),
  74811. median: curry(markerTypeCalculatorWithExtent, 'median')
  74812. };
  74813. /**
  74814. * Transform markPoint data item to format used in List by do the following
  74815. * 1. Calculate statistic like `max`, `min`, `average`
  74816. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  74817. */
  74818. function dataTransform(seriesModel, item) {
  74819. if (!item) {
  74820. return;
  74821. }
  74822. var data = seriesModel.getData();
  74823. var coordSys = seriesModel.coordinateSystem;
  74824. var dims = coordSys && coordSys.dimensions; // 1. If not specify the position with pixel directly
  74825. // 2. If `coord` is not a data array. Which uses `xAxis`,
  74826. // `yAxis` to specify the coord on each dimension
  74827. // parseFloat first because item.x and item.y can be percent string like '20%'
  74828. if (!hasXAndY(item) && !isArray(item.coord) && isArray(dims)) {
  74829. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  74830. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  74831. item = clone(item);
  74832. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  74833. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  74834. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  74835. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  74836. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  74837. // let item use the value without stack.
  74838. item.value = coordInfo[1];
  74839. } else {
  74840. // FIXME Only has one of xAxis and yAxis.
  74841. item.coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis];
  74842. }
  74843. } // x y is provided
  74844. if (item.coord == null || !isArray(dims)) {
  74845. item.coord = [];
  74846. } else {
  74847. // Each coord support max, min, average
  74848. var coord = item.coord;
  74849. for (var i = 0; i < 2; i++) {
  74850. if (markerTypeCalculator[coord[i]]) {
  74851. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  74852. }
  74853. }
  74854. }
  74855. return item;
  74856. }
  74857. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  74858. var ret = {};
  74859. if (item.valueIndex != null || item.valueDim != null) {
  74860. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  74861. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  74862. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  74863. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74864. } else {
  74865. ret.baseAxis = seriesModel.getBaseAxis();
  74866. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  74867. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  74868. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  74869. }
  74870. return ret;
  74871. }
  74872. function dataDimToCoordDim(seriesModel, dataDim) {
  74873. var dimItem = seriesModel.getData().getDimensionInfo(dataDim);
  74874. return dimItem && dimItem.coordDim;
  74875. }
  74876. /**
  74877. * Filter data which is out of coordinateSystem range
  74878. * [dataFilter description]
  74879. */
  74880. function dataFilter$1( // Currently only polar and cartesian has containData.
  74881. coordSys, item) {
  74882. // Always return true if there is no coordSys
  74883. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  74884. }
  74885. function zoneFilter( // Currently only polar and cartesian has containData.
  74886. coordSys, item1, item2) {
  74887. // Always return true if there is no coordSys
  74888. return coordSys && coordSys.containZone && item1.coord && item2.coord && !hasXOrY(item1) && !hasXOrY(item2) ? coordSys.containZone(item1.coord, item2.coord) : true;
  74889. }
  74890. function createMarkerDimValueGetter(inCoordSys, dims) {
  74891. return inCoordSys ? function (item, dimName, dataIndex, dimIndex) {
  74892. var rawVal = dimIndex < 2 // x, y, radius, angle
  74893. ? item.coord && item.coord[dimIndex] : item.value;
  74894. return parseDataValue(rawVal, dims[dimIndex]);
  74895. } : function (item, dimName, dataIndex, dimIndex) {
  74896. return parseDataValue(item.value, dims[dimIndex]);
  74897. };
  74898. }
  74899. function numCalculate(data, valueDataDim, type) {
  74900. if (type === 'average') {
  74901. var sum_1 = 0;
  74902. var count_1 = 0;
  74903. data.each(valueDataDim, function (val, idx) {
  74904. if (!isNaN(val)) {
  74905. sum_1 += val;
  74906. count_1++;
  74907. }
  74908. });
  74909. return sum_1 / count_1;
  74910. } else if (type === 'median') {
  74911. return data.getMedian(valueDataDim);
  74912. } else {
  74913. // max & min
  74914. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  74915. }
  74916. }
  74917. var inner$h = makeInner();
  74918. var MarkerView =
  74919. /** @class */
  74920. function (_super) {
  74921. __extends(MarkerView, _super);
  74922. function MarkerView() {
  74923. var _this = _super !== null && _super.apply(this, arguments) || this;
  74924. _this.type = MarkerView.type;
  74925. return _this;
  74926. }
  74927. MarkerView.prototype.init = function () {
  74928. this.markerGroupMap = createHashMap();
  74929. };
  74930. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  74931. var _this = this;
  74932. var markerGroupMap = this.markerGroupMap;
  74933. markerGroupMap.each(function (item) {
  74934. inner$h(item).keep = false;
  74935. });
  74936. ecModel.eachSeries(function (seriesModel) {
  74937. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74938. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  74939. });
  74940. markerGroupMap.each(function (item) {
  74941. !inner$h(item).keep && _this.group.remove(item.group);
  74942. });
  74943. };
  74944. MarkerView.prototype.markKeep = function (drawGroup) {
  74945. inner$h(drawGroup).keep = true;
  74946. };
  74947. MarkerView.prototype.toggleBlurSeries = function (seriesModelList, isBlur) {
  74948. var _this = this;
  74949. each(seriesModelList, function (seriesModel) {
  74950. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  74951. if (markerModel) {
  74952. var data = markerModel.getData();
  74953. data.eachItemGraphicEl(function (el) {
  74954. if (el) {
  74955. isBlur ? enterBlur(el) : leaveBlur(el);
  74956. }
  74957. });
  74958. }
  74959. });
  74960. };
  74961. MarkerView.type = 'marker';
  74962. return MarkerView;
  74963. }(ComponentView);
  74964. function updateMarkerLayout(mpData, seriesModel, api) {
  74965. var coordSys = seriesModel.coordinateSystem;
  74966. mpData.each(function (idx) {
  74967. var itemModel = mpData.getItemModel(idx);
  74968. var point;
  74969. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  74970. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  74971. if (!isNaN(xPx) && !isNaN(yPx)) {
  74972. point = [xPx, yPx];
  74973. } // Chart like bar may have there own marker positioning logic
  74974. else if (seriesModel.getMarkerPosition) {
  74975. // Use the getMarkerPosition
  74976. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  74977. } else if (coordSys) {
  74978. var x = mpData.get(coordSys.dimensions[0], idx);
  74979. var y = mpData.get(coordSys.dimensions[1], idx);
  74980. point = coordSys.dataToPoint([x, y]);
  74981. } // Use x, y if has any
  74982. if (!isNaN(xPx)) {
  74983. point[0] = xPx;
  74984. }
  74985. if (!isNaN(yPx)) {
  74986. point[1] = yPx;
  74987. }
  74988. mpData.setItemLayout(idx, point);
  74989. });
  74990. }
  74991. var MarkPointView =
  74992. /** @class */
  74993. function (_super) {
  74994. __extends(MarkPointView, _super);
  74995. function MarkPointView() {
  74996. var _this = _super !== null && _super.apply(this, arguments) || this;
  74997. _this.type = MarkPointView.type;
  74998. return _this;
  74999. }
  75000. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  75001. ecModel.eachSeries(function (seriesModel) {
  75002. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  75003. if (mpModel) {
  75004. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  75005. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75006. }
  75007. }, this);
  75008. };
  75009. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  75010. var coordSys = seriesModel.coordinateSystem;
  75011. var seriesId = seriesModel.id;
  75012. var seriesData = seriesModel.getData();
  75013. var symbolDrawMap = this.markerGroupMap;
  75014. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  75015. var mpData = createData(coordSys, seriesModel, mpModel); // FIXME
  75016. mpModel.setData(mpData);
  75017. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  75018. mpData.each(function (idx) {
  75019. var itemModel = mpData.getItemModel(idx);
  75020. var symbol = itemModel.getShallow('symbol');
  75021. var symbolSize = itemModel.getShallow('symbolSize');
  75022. var symbolRotate = itemModel.getShallow('symbolRotate');
  75023. var symbolOffset = itemModel.getShallow('symbolOffset');
  75024. var symbolKeepAspect = itemModel.getShallow('symbolKeepAspect'); // TODO: refactor needed: single data item should not support callback function
  75025. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate) || isFunction(symbolOffset)) {
  75026. var rawIdx = mpModel.getRawValue(idx);
  75027. var dataParams = mpModel.getDataParams(idx);
  75028. if (isFunction(symbol)) {
  75029. symbol = symbol(rawIdx, dataParams);
  75030. }
  75031. if (isFunction(symbolSize)) {
  75032. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  75033. symbolSize = symbolSize(rawIdx, dataParams);
  75034. }
  75035. if (isFunction(symbolRotate)) {
  75036. symbolRotate = symbolRotate(rawIdx, dataParams);
  75037. }
  75038. if (isFunction(symbolOffset)) {
  75039. symbolOffset = symbolOffset(rawIdx, dataParams);
  75040. }
  75041. }
  75042. var style = itemModel.getModel('itemStyle').getItemStyle();
  75043. var color = getVisualFromData(seriesData, 'color');
  75044. if (!style.fill) {
  75045. style.fill = color;
  75046. }
  75047. mpData.setItemVisual(idx, {
  75048. symbol: symbol,
  75049. symbolSize: symbolSize,
  75050. symbolRotate: symbolRotate,
  75051. symbolOffset: symbolOffset,
  75052. symbolKeepAspect: symbolKeepAspect,
  75053. style: style
  75054. });
  75055. }); // TODO Text are wrong
  75056. symbolDraw.updateData(mpData);
  75057. this.group.add(symbolDraw.group); // Set host model for tooltip
  75058. // FIXME
  75059. mpData.eachItemGraphicEl(function (el) {
  75060. el.traverse(function (child) {
  75061. getECData(child).dataModel = mpModel;
  75062. });
  75063. });
  75064. this.markKeep(symbolDraw);
  75065. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  75066. };
  75067. MarkPointView.type = 'markPoint';
  75068. return MarkPointView;
  75069. }(MarkerView);
  75070. function createData(coordSys, seriesModel, mpModel) {
  75071. var coordDimsInfos;
  75072. if (coordSys) {
  75073. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75074. 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
  75075. return extend(extend({}, info), {
  75076. name: coordDim,
  75077. // DON'T use ordinalMeta to parse and collect ordinal.
  75078. ordinalMeta: null
  75079. });
  75080. });
  75081. } else {
  75082. coordDimsInfos = [{
  75083. name: 'value',
  75084. type: 'float'
  75085. }];
  75086. }
  75087. var mpData = new SeriesData(coordDimsInfos, mpModel);
  75088. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  75089. if (coordSys) {
  75090. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  75091. }
  75092. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  75093. mpData.initData(dataOpt, null, dimValueGetter);
  75094. return mpData;
  75095. }
  75096. function install$E(registers) {
  75097. registers.registerComponentModel(MarkPointModel);
  75098. registers.registerComponentView(MarkPointView);
  75099. registers.registerPreprocessor(function (opt) {
  75100. if (checkMarkerInSeries(opt.series, 'markPoint')) {
  75101. // Make sure markPoint component is enabled
  75102. opt.markPoint = opt.markPoint || {};
  75103. }
  75104. });
  75105. }
  75106. var MarkLineModel =
  75107. /** @class */
  75108. function (_super) {
  75109. __extends(MarkLineModel, _super);
  75110. function MarkLineModel() {
  75111. var _this = _super !== null && _super.apply(this, arguments) || this;
  75112. _this.type = MarkLineModel.type;
  75113. return _this;
  75114. }
  75115. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  75116. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  75117. };
  75118. MarkLineModel.type = 'markLine';
  75119. MarkLineModel.defaultOption = {
  75120. // zlevel: 0,
  75121. z: 5,
  75122. symbol: ['circle', 'arrow'],
  75123. symbolSize: [8, 16],
  75124. // symbolRotate: 0,
  75125. symbolOffset: 0,
  75126. precision: 2,
  75127. tooltip: {
  75128. trigger: 'item'
  75129. },
  75130. label: {
  75131. show: true,
  75132. position: 'end',
  75133. distance: 5
  75134. },
  75135. lineStyle: {
  75136. type: 'dashed'
  75137. },
  75138. emphasis: {
  75139. label: {
  75140. show: true
  75141. },
  75142. lineStyle: {
  75143. width: 3
  75144. }
  75145. },
  75146. animationEasing: 'linear'
  75147. };
  75148. return MarkLineModel;
  75149. }(MarkerModel);
  75150. var inner$i = makeInner();
  75151. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  75152. var data = seriesModel.getData();
  75153. var itemArray;
  75154. if (!isArray(item)) {
  75155. // Special type markLine like 'min', 'max', 'average', 'median'
  75156. var mlType = item.type;
  75157. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  75158. // data: [{
  75159. // yAxis: 10
  75160. // }]
  75161. || item.xAxis != null || item.yAxis != null) {
  75162. var valueAxis = void 0;
  75163. var value = void 0;
  75164. if (item.yAxis != null || item.xAxis != null) {
  75165. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  75166. value = retrieve(item.yAxis, item.xAxis);
  75167. } else {
  75168. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  75169. valueAxis = axisInfo.valueAxis;
  75170. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  75171. value = numCalculate(data, valueDataDim, mlType);
  75172. }
  75173. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  75174. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  75175. var mlFrom = clone(item);
  75176. var mlTo = {
  75177. coord: []
  75178. };
  75179. mlFrom.type = null;
  75180. mlFrom.coord = [];
  75181. mlFrom.coord[baseIndex] = -Infinity;
  75182. mlTo.coord[baseIndex] = Infinity;
  75183. var precision = mlModel.get('precision');
  75184. if (precision >= 0 && isNumber(value)) {
  75185. value = +value.toFixed(Math.min(precision, 20));
  75186. }
  75187. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  75188. itemArray = [mlFrom, mlTo, {
  75189. type: mlType,
  75190. valueIndex: item.valueIndex,
  75191. // Force to use the value of calculated value.
  75192. value: value
  75193. }];
  75194. } else {
  75195. // Invalid data
  75196. if ("development" !== 'production') {
  75197. logError('Invalid markLine data.');
  75198. }
  75199. itemArray = [];
  75200. }
  75201. } else {
  75202. itemArray = item;
  75203. }
  75204. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  75205. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  75206. merge(normalizedItem[2], normalizedItem[0]);
  75207. merge(normalizedItem[2], normalizedItem[1]);
  75208. return normalizedItem;
  75209. };
  75210. function isInfinity(val) {
  75211. return !isNaN(val) && !isFinite(val);
  75212. } // If a markLine has one dim
  75213. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75214. var otherDimIndex = 1 - dimIndex;
  75215. var dimName = coordSys.dimensions[dimIndex];
  75216. return isInfinity(fromCoord[otherDimIndex]) && isInfinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  75217. }
  75218. function markLineFilter(coordSys, item) {
  75219. if (coordSys.type === 'cartesian2d') {
  75220. var fromCoord = item[0].coord;
  75221. var toCoord = item[1].coord; // In case
  75222. // {
  75223. // markLine: {
  75224. // data: [{ yAxis: 2 }]
  75225. // }
  75226. // }
  75227. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  75228. return true;
  75229. }
  75230. }
  75231. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  75232. }
  75233. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  75234. var coordSys = seriesModel.coordinateSystem;
  75235. var itemModel = data.getItemModel(idx);
  75236. var point;
  75237. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  75238. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  75239. if (!isNaN(xPx) && !isNaN(yPx)) {
  75240. point = [xPx, yPx];
  75241. } else {
  75242. // Chart like bar may have there own marker positioning logic
  75243. if (seriesModel.getMarkerPosition) {
  75244. // Use the getMarkerPosition
  75245. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  75246. } else {
  75247. var dims = coordSys.dimensions;
  75248. var x = data.get(dims[0], idx);
  75249. var y = data.get(dims[1], idx);
  75250. point = coordSys.dataToPoint([x, y]);
  75251. } // Expand line to the edge of grid if value on one axis is Inifnity
  75252. // In case
  75253. // markLine: {
  75254. // data: [{
  75255. // yAxis: 2
  75256. // // or
  75257. // type: 'average'
  75258. // }]
  75259. // }
  75260. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75261. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75262. var xAxis = coordSys.getAxis('x');
  75263. var yAxis = coordSys.getAxis('y');
  75264. var dims = coordSys.dimensions;
  75265. if (isInfinity(data.get(dims[0], idx))) {
  75266. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  75267. } else if (isInfinity(data.get(dims[1], idx))) {
  75268. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  75269. }
  75270. } // Use x, y if has any
  75271. if (!isNaN(xPx)) {
  75272. point[0] = xPx;
  75273. }
  75274. if (!isNaN(yPx)) {
  75275. point[1] = yPx;
  75276. }
  75277. }
  75278. data.setItemLayout(idx, point);
  75279. }
  75280. var MarkLineView =
  75281. /** @class */
  75282. function (_super) {
  75283. __extends(MarkLineView, _super);
  75284. function MarkLineView() {
  75285. var _this = _super !== null && _super.apply(this, arguments) || this;
  75286. _this.type = MarkLineView.type;
  75287. return _this;
  75288. }
  75289. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  75290. ecModel.eachSeries(function (seriesModel) {
  75291. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  75292. if (mlModel) {
  75293. var mlData_1 = mlModel.getData();
  75294. var fromData_1 = inner$i(mlModel).from;
  75295. var toData_1 = inner$i(mlModel).to; // Update visual and layout of from symbol and to symbol
  75296. fromData_1.each(function (idx) {
  75297. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  75298. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  75299. }); // Update layout of line
  75300. mlData_1.each(function (idx) {
  75301. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  75302. });
  75303. this.markerGroupMap.get(seriesModel.id).updateLayout();
  75304. }
  75305. }, this);
  75306. };
  75307. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  75308. var coordSys = seriesModel.coordinateSystem;
  75309. var seriesId = seriesModel.id;
  75310. var seriesData = seriesModel.getData();
  75311. var lineDrawMap = this.markerGroupMap;
  75312. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  75313. this.group.add(lineDraw.group);
  75314. var mlData = createList$1(coordSys, seriesModel, mlModel);
  75315. var fromData = mlData.from;
  75316. var toData = mlData.to;
  75317. var lineData = mlData.line;
  75318. inner$i(mlModel).from = fromData;
  75319. inner$i(mlModel).to = toData; // Line data for tooltip and formatter
  75320. mlModel.setData(lineData); // TODO
  75321. // Functionally, `symbolSize` & `symbolOffset` can also be 2D array now.
  75322. // But the related logic and type definition are not finished yet.
  75323. // Finish it if required
  75324. var symbolType = mlModel.get('symbol');
  75325. var symbolSize = mlModel.get('symbolSize');
  75326. var symbolRotate = mlModel.get('symbolRotate');
  75327. var symbolOffset = mlModel.get('symbolOffset'); // TODO: support callback function like markPoint
  75328. if (!isArray(symbolType)) {
  75329. symbolType = [symbolType, symbolType];
  75330. }
  75331. if (!isArray(symbolSize)) {
  75332. symbolSize = [symbolSize, symbolSize];
  75333. }
  75334. if (!isArray(symbolRotate)) {
  75335. symbolRotate = [symbolRotate, symbolRotate];
  75336. }
  75337. if (!isArray(symbolOffset)) {
  75338. symbolOffset = [symbolOffset, symbolOffset];
  75339. } // Update visual and layout of from symbol and to symbol
  75340. mlData.from.each(function (idx) {
  75341. updateDataVisualAndLayout(fromData, idx, true);
  75342. updateDataVisualAndLayout(toData, idx, false);
  75343. }); // Update visual and layout of line
  75344. lineData.each(function (idx) {
  75345. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  75346. // color: lineColor || fromData.getItemVisual(idx, 'color')
  75347. // });
  75348. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  75349. if (lineStyle.stroke == null) {
  75350. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  75351. }
  75352. lineData.setItemVisual(idx, {
  75353. fromSymbolKeepAspect: fromData.getItemVisual(idx, 'symbolKeepAspect'),
  75354. fromSymbolOffset: fromData.getItemVisual(idx, 'symbolOffset'),
  75355. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  75356. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  75357. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  75358. toSymbolKeepAspect: toData.getItemVisual(idx, 'symbolKeepAspect'),
  75359. toSymbolOffset: toData.getItemVisual(idx, 'symbolOffset'),
  75360. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  75361. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  75362. toSymbol: toData.getItemVisual(idx, 'symbol'),
  75363. style: lineStyle
  75364. });
  75365. });
  75366. lineDraw.updateData(lineData); // Set host model for tooltip
  75367. // FIXME
  75368. mlData.line.eachItemGraphicEl(function (el) {
  75369. getECData(el).dataModel = mlModel;
  75370. el.traverse(function (child) {
  75371. getECData(child).dataModel = mlModel;
  75372. });
  75373. });
  75374. function updateDataVisualAndLayout(data, idx, isFrom) {
  75375. var itemModel = data.getItemModel(idx);
  75376. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  75377. var style = itemModel.getModel('itemStyle').getItemStyle();
  75378. if (style.fill == null) {
  75379. style.fill = getVisualFromData(seriesData, 'color');
  75380. }
  75381. data.setItemVisual(idx, {
  75382. symbolKeepAspect: itemModel.get('symbolKeepAspect'),
  75383. // `0` should be considered as a valid value, so use `retrieve2` instead of `||`
  75384. symbolOffset: retrieve2(itemModel.get('symbolOffset', true), symbolOffset[isFrom ? 0 : 1]),
  75385. symbolRotate: retrieve2(itemModel.get('symbolRotate', true), symbolRotate[isFrom ? 0 : 1]),
  75386. // TODO: when 2d array is supported, it should ignore parent
  75387. symbolSize: retrieve2(itemModel.get('symbolSize'), symbolSize[isFrom ? 0 : 1]),
  75388. symbol: retrieve2(itemModel.get('symbol', true), symbolType[isFrom ? 0 : 1]),
  75389. style: style
  75390. });
  75391. }
  75392. this.markKeep(lineDraw);
  75393. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  75394. };
  75395. MarkLineView.type = 'markLine';
  75396. return MarkLineView;
  75397. }(MarkerView);
  75398. function createList$1(coordSys, seriesModel, mlModel) {
  75399. var coordDimsInfos;
  75400. if (coordSys) {
  75401. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  75402. 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
  75403. return extend(extend({}, info), {
  75404. name: coordDim,
  75405. // DON'T use ordinalMeta to parse and collect ordinal.
  75406. ordinalMeta: null
  75407. });
  75408. });
  75409. } else {
  75410. coordDimsInfos = [{
  75411. name: 'value',
  75412. type: 'float'
  75413. }];
  75414. }
  75415. var fromData = new SeriesData(coordDimsInfos, mlModel);
  75416. var toData = new SeriesData(coordDimsInfos, mlModel); // No dimensions
  75417. var lineData = new SeriesData([], mlModel);
  75418. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  75419. if (coordSys) {
  75420. optData = filter(optData, curry(markLineFilter, coordSys));
  75421. }
  75422. var dimValueGetter = createMarkerDimValueGetter(!!coordSys, coordDimsInfos);
  75423. fromData.initData(map(optData, function (item) {
  75424. return item[0];
  75425. }), null, dimValueGetter);
  75426. toData.initData(map(optData, function (item) {
  75427. return item[1];
  75428. }), null, dimValueGetter);
  75429. lineData.initData(map(optData, function (item) {
  75430. return item[2];
  75431. }));
  75432. lineData.hasItemOption = true;
  75433. return {
  75434. from: fromData,
  75435. to: toData,
  75436. line: lineData
  75437. };
  75438. }
  75439. function install$F(registers) {
  75440. registers.registerComponentModel(MarkLineModel);
  75441. registers.registerComponentView(MarkLineView);
  75442. registers.registerPreprocessor(function (opt) {
  75443. if (checkMarkerInSeries(opt.series, 'markLine')) {
  75444. // Make sure markLine component is enabled
  75445. opt.markLine = opt.markLine || {};
  75446. }
  75447. });
  75448. }
  75449. var MarkAreaModel =
  75450. /** @class */
  75451. function (_super) {
  75452. __extends(MarkAreaModel, _super);
  75453. function MarkAreaModel() {
  75454. var _this = _super !== null && _super.apply(this, arguments) || this;
  75455. _this.type = MarkAreaModel.type;
  75456. return _this;
  75457. }
  75458. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  75459. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  75460. };
  75461. MarkAreaModel.type = 'markArea';
  75462. MarkAreaModel.defaultOption = {
  75463. // zlevel: 0,
  75464. // PENDING
  75465. z: 1,
  75466. tooltip: {
  75467. trigger: 'item'
  75468. },
  75469. // markArea should fixed on the coordinate system
  75470. animation: false,
  75471. label: {
  75472. show: true,
  75473. position: 'top'
  75474. },
  75475. itemStyle: {
  75476. // color and borderColor default to use color from series
  75477. // color: 'auto'
  75478. // borderColor: 'auto'
  75479. borderWidth: 0
  75480. },
  75481. emphasis: {
  75482. label: {
  75483. show: true,
  75484. position: 'top'
  75485. }
  75486. }
  75487. };
  75488. return MarkAreaModel;
  75489. }(MarkerModel);
  75490. var inner$j = makeInner();
  75491. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  75492. // item may be null
  75493. var item0 = item[0];
  75494. var item1 = item[1];
  75495. if (!item0 || !item1) {
  75496. return;
  75497. }
  75498. var lt = dataTransform(seriesModel, item0);
  75499. var rb = dataTransform(seriesModel, item1); // FIXME make sure lt is less than rb
  75500. var ltCoord = lt.coord;
  75501. var rbCoord = rb.coord;
  75502. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  75503. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  75504. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  75505. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  75506. var result = mergeAll([{}, lt, rb]);
  75507. result.coord = [lt.coord, rb.coord];
  75508. result.x0 = lt.x;
  75509. result.y0 = lt.y;
  75510. result.x1 = rb.x;
  75511. result.y1 = rb.y;
  75512. return result;
  75513. };
  75514. function isInfinity$1(val) {
  75515. return !isNaN(val) && !isFinite(val);
  75516. } // If a markArea has one dim
  75517. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  75518. var otherDimIndex = 1 - dimIndex;
  75519. return isInfinity$1(fromCoord[otherDimIndex]) && isInfinity$1(toCoord[otherDimIndex]);
  75520. }
  75521. function markAreaFilter(coordSys, item) {
  75522. var fromCoord = item.coord[0];
  75523. var toCoord = item.coord[1];
  75524. var item0 = {
  75525. coord: fromCoord,
  75526. x: item.x0,
  75527. y: item.y0
  75528. };
  75529. var item1 = {
  75530. coord: toCoord,
  75531. x: item.x1,
  75532. y: item.y1
  75533. };
  75534. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75535. // In case
  75536. // {
  75537. // markArea: {
  75538. // data: [{ yAxis: 2 }]
  75539. // }
  75540. // }
  75541. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  75542. return true;
  75543. } // Directly returning true may also do the work,
  75544. // because markArea will not be shown automatically
  75545. // when it's not included in coordinate system.
  75546. // But filtering ahead can avoid keeping rendering markArea
  75547. // when there are too many of them.
  75548. return zoneFilter(coordSys, item0, item1);
  75549. }
  75550. return dataFilter$1(coordSys, item0) || dataFilter$1(coordSys, item1);
  75551. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  75552. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  75553. var coordSys = seriesModel.coordinateSystem;
  75554. var itemModel = data.getItemModel(idx);
  75555. var point;
  75556. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  75557. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  75558. if (!isNaN(xPx) && !isNaN(yPx)) {
  75559. point = [xPx, yPx];
  75560. } else {
  75561. // Chart like bar may have there own marker positioning logic
  75562. if (seriesModel.getMarkerPosition) {
  75563. // Consider the case that user input the right-bottom point first
  75564. // Pick the larger x and y as 'x1' and 'y1'
  75565. var pointValue0 = data.getValues(['x0', 'y0'], idx);
  75566. var pointValue1 = data.getValues(['x1', 'y1'], idx);
  75567. var clampPointValue0 = coordSys.clampData(pointValue0);
  75568. var clampPointValue1 = coordSys.clampData(pointValue1);
  75569. var pointValue = [];
  75570. if (dims[0] === 'x0') {
  75571. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue1[0] : pointValue0[0];
  75572. } else {
  75573. pointValue[0] = clampPointValue0[0] > clampPointValue1[0] ? pointValue0[0] : pointValue1[0];
  75574. }
  75575. if (dims[1] === 'y0') {
  75576. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue1[1] : pointValue0[1];
  75577. } else {
  75578. pointValue[1] = clampPointValue0[1] > clampPointValue1[1] ? pointValue0[1] : pointValue1[1];
  75579. } // Use the getMarkerPosition
  75580. point = seriesModel.getMarkerPosition(pointValue, dims, true);
  75581. } else {
  75582. var x = data.get(dims[0], idx);
  75583. var y = data.get(dims[1], idx);
  75584. var pt = [x, y];
  75585. coordSys.clampData && coordSys.clampData(pt, pt);
  75586. point = coordSys.dataToPoint(pt, true);
  75587. }
  75588. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  75589. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  75590. var xAxis = coordSys.getAxis('x');
  75591. var yAxis = coordSys.getAxis('y');
  75592. var x = data.get(dims[0], idx);
  75593. var y = data.get(dims[1], idx);
  75594. if (isInfinity$1(x)) {
  75595. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  75596. } else if (isInfinity$1(y)) {
  75597. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  75598. }
  75599. } // Use x, y if has any
  75600. if (!isNaN(xPx)) {
  75601. point[0] = xPx;
  75602. }
  75603. if (!isNaN(yPx)) {
  75604. point[1] = yPx;
  75605. }
  75606. }
  75607. return point;
  75608. }
  75609. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  75610. var MarkAreaView =
  75611. /** @class */
  75612. function (_super) {
  75613. __extends(MarkAreaView, _super);
  75614. function MarkAreaView() {
  75615. var _this = _super !== null && _super.apply(this, arguments) || this;
  75616. _this.type = MarkAreaView.type;
  75617. return _this;
  75618. }
  75619. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  75620. ecModel.eachSeries(function (seriesModel) {
  75621. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  75622. if (maModel) {
  75623. var areaData_1 = maModel.getData();
  75624. areaData_1.each(function (idx) {
  75625. var points = map(dimPermutations, function (dim) {
  75626. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  75627. }); // Layout
  75628. areaData_1.setItemLayout(idx, points);
  75629. var el = areaData_1.getItemGraphicEl(idx);
  75630. el.setShape('points', points);
  75631. });
  75632. }
  75633. }, this);
  75634. };
  75635. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  75636. var coordSys = seriesModel.coordinateSystem;
  75637. var seriesId = seriesModel.id;
  75638. var seriesData = seriesModel.getData();
  75639. var areaGroupMap = this.markerGroupMap;
  75640. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  75641. group: new Group()
  75642. });
  75643. this.group.add(polygonGroup.group);
  75644. this.markKeep(polygonGroup);
  75645. var areaData = createList$2(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  75646. maModel.setData(areaData); // Update visual and layout of line
  75647. areaData.each(function (idx) {
  75648. // Layout
  75649. var points = map(dimPermutations, function (dim) {
  75650. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  75651. });
  75652. var xAxisScale = coordSys.getAxis('x').scale;
  75653. var yAxisScale = coordSys.getAxis('y').scale;
  75654. var xAxisExtent = xAxisScale.getExtent();
  75655. var yAxisExtent = yAxisScale.getExtent();
  75656. var xPointExtent = [xAxisScale.parse(areaData.get('x0', idx)), xAxisScale.parse(areaData.get('x1', idx))];
  75657. var yPointExtent = [yAxisScale.parse(areaData.get('y0', idx)), yAxisScale.parse(areaData.get('y1', idx))];
  75658. asc(xPointExtent);
  75659. asc(yPointExtent);
  75660. 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
  75661. // in layout so that label will not be displayed. See #12591
  75662. var allClipped = !overlapped;
  75663. areaData.setItemLayout(idx, {
  75664. points: points,
  75665. allClipped: allClipped
  75666. });
  75667. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  75668. var color$1 = getVisualFromData(seriesData, 'color');
  75669. if (!style.fill) {
  75670. style.fill = color$1;
  75671. if (isString(style.fill)) {
  75672. style.fill = modifyAlpha(style.fill, 0.4);
  75673. }
  75674. }
  75675. if (!style.stroke) {
  75676. style.stroke = color$1;
  75677. } // Visual
  75678. areaData.setItemVisual(idx, 'style', style);
  75679. });
  75680. areaData.diff(inner$j(polygonGroup).data).add(function (idx) {
  75681. var layout = areaData.getItemLayout(idx);
  75682. if (!layout.allClipped) {
  75683. var polygon = new Polygon({
  75684. shape: {
  75685. points: layout.points
  75686. }
  75687. });
  75688. areaData.setItemGraphicEl(idx, polygon);
  75689. polygonGroup.group.add(polygon);
  75690. }
  75691. }).update(function (newIdx, oldIdx) {
  75692. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(oldIdx);
  75693. var layout = areaData.getItemLayout(newIdx);
  75694. if (!layout.allClipped) {
  75695. if (polygon) {
  75696. updateProps(polygon, {
  75697. shape: {
  75698. points: layout.points
  75699. }
  75700. }, maModel, newIdx);
  75701. } else {
  75702. polygon = new Polygon({
  75703. shape: {
  75704. points: layout.points
  75705. }
  75706. });
  75707. }
  75708. areaData.setItemGraphicEl(newIdx, polygon);
  75709. polygonGroup.group.add(polygon);
  75710. } else if (polygon) {
  75711. polygonGroup.group.remove(polygon);
  75712. }
  75713. }).remove(function (idx) {
  75714. var polygon = inner$j(polygonGroup).data.getItemGraphicEl(idx);
  75715. polygonGroup.group.remove(polygon);
  75716. }).execute();
  75717. areaData.eachItemGraphicEl(function (polygon, idx) {
  75718. var itemModel = areaData.getItemModel(idx);
  75719. var style = areaData.getItemVisual(idx, 'style');
  75720. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  75721. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  75722. labelFetcher: maModel,
  75723. labelDataIndex: idx,
  75724. defaultText: areaData.getName(idx) || '',
  75725. inheritColor: isString(style.fill) ? modifyAlpha(style.fill, 1) : '#000'
  75726. });
  75727. setStatesStylesFromModel(polygon, itemModel);
  75728. toggleHoverEmphasis(polygon, null, null, itemModel.get(['emphasis', 'disabled']));
  75729. getECData(polygon).dataModel = maModel;
  75730. });
  75731. inner$j(polygonGroup).data = areaData;
  75732. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  75733. };
  75734. MarkAreaView.type = 'markArea';
  75735. return MarkAreaView;
  75736. }(MarkerView);
  75737. function createList$2(coordSys, seriesModel, maModel) {
  75738. var areaData;
  75739. var dataDims;
  75740. var dims = ['x0', 'y0', 'x1', 'y1'];
  75741. if (coordSys) {
  75742. var coordDimsInfos_1 = map(coordSys && coordSys.dimensions, function (coordDim) {
  75743. var data = seriesModel.getData();
  75744. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  75745. return extend(extend({}, info), {
  75746. name: coordDim,
  75747. // DON'T use ordinalMeta to parse and collect ordinal.
  75748. ordinalMeta: null
  75749. });
  75750. });
  75751. dataDims = map(dims, function (dim, idx) {
  75752. return {
  75753. name: dim,
  75754. type: coordDimsInfos_1[idx % 2].type
  75755. };
  75756. });
  75757. areaData = new SeriesData(dataDims, maModel);
  75758. } else {
  75759. dataDims = [{
  75760. name: 'value',
  75761. type: 'float'
  75762. }];
  75763. areaData = new SeriesData(dataDims, maModel);
  75764. }
  75765. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  75766. if (coordSys) {
  75767. optData = filter(optData, curry(markAreaFilter, coordSys));
  75768. }
  75769. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  75770. // TODO should convert to ParsedValue?
  75771. var rawVal = item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  75772. return parseDataValue(rawVal, dataDims[dimIndex]);
  75773. } : function (item, dimName, dataIndex, dimIndex) {
  75774. return parseDataValue(item.value, dataDims[dimIndex]);
  75775. };
  75776. areaData.initData(optData, null, dimValueGetter);
  75777. areaData.hasItemOption = true;
  75778. return areaData;
  75779. }
  75780. function install$G(registers) {
  75781. registers.registerComponentModel(MarkAreaModel);
  75782. registers.registerComponentView(MarkAreaView);
  75783. registers.registerPreprocessor(function (opt) {
  75784. if (checkMarkerInSeries(opt.series, 'markArea')) {
  75785. // Make sure markArea component is enabled
  75786. opt.markArea = opt.markArea || {};
  75787. }
  75788. });
  75789. }
  75790. var getDefaultSelectorOptions = function (ecModel, type) {
  75791. if (type === 'all') {
  75792. return {
  75793. type: 'all',
  75794. title: ecModel.getLocaleModel().get(['legend', 'selector', 'all'])
  75795. };
  75796. } else if (type === 'inverse') {
  75797. return {
  75798. type: 'inverse',
  75799. title: ecModel.getLocaleModel().get(['legend', 'selector', 'inverse'])
  75800. };
  75801. }
  75802. };
  75803. var LegendModel =
  75804. /** @class */
  75805. function (_super) {
  75806. __extends(LegendModel, _super);
  75807. function LegendModel() {
  75808. var _this = _super !== null && _super.apply(this, arguments) || this;
  75809. _this.type = LegendModel.type;
  75810. _this.layoutMode = {
  75811. type: 'box',
  75812. // legend.width/height are maxWidth/maxHeight actually,
  75813. // whereas real width/height is calculated by its content.
  75814. // (Setting {left: 10, right: 10} does not make sense).
  75815. // So consider the case:
  75816. // `setOption({legend: {left: 10});`
  75817. // then `setOption({legend: {right: 10});`
  75818. // The previous `left` should be cleared by setting `ignoreSize`.
  75819. ignoreSize: true
  75820. };
  75821. return _this;
  75822. }
  75823. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  75824. this.mergeDefaultAndTheme(option, ecModel);
  75825. option.selected = option.selected || {};
  75826. this._updateSelector(option);
  75827. };
  75828. LegendModel.prototype.mergeOption = function (option, ecModel) {
  75829. _super.prototype.mergeOption.call(this, option, ecModel);
  75830. this._updateSelector(option);
  75831. };
  75832. LegendModel.prototype._updateSelector = function (option) {
  75833. var selector = option.selector;
  75834. var ecModel = this.ecModel;
  75835. if (selector === true) {
  75836. selector = option.selector = ['all', 'inverse'];
  75837. }
  75838. if (isArray(selector)) {
  75839. each(selector, function (item, index) {
  75840. isString(item) && (item = {
  75841. type: item
  75842. });
  75843. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  75844. });
  75845. }
  75846. };
  75847. LegendModel.prototype.optionUpdated = function () {
  75848. this._updateData(this.ecModel);
  75849. var legendData = this._data; // If selectedMode is single, try to select one
  75850. if (legendData[0] && this.get('selectedMode') === 'single') {
  75851. var hasSelected = false; // If has any selected in option.selected
  75852. for (var i = 0; i < legendData.length; i++) {
  75853. var name_1 = legendData[i].get('name');
  75854. if (this.isSelected(name_1)) {
  75855. // Force to unselect others
  75856. this.select(name_1);
  75857. hasSelected = true;
  75858. break;
  75859. }
  75860. } // Try select the first if selectedMode is single
  75861. !hasSelected && this.select(legendData[0].get('name'));
  75862. }
  75863. };
  75864. LegendModel.prototype._updateData = function (ecModel) {
  75865. var potentialData = [];
  75866. var availableNames = [];
  75867. ecModel.eachRawSeries(function (seriesModel) {
  75868. var seriesName = seriesModel.name;
  75869. availableNames.push(seriesName);
  75870. var isPotential;
  75871. if (seriesModel.legendVisualProvider) {
  75872. var provider = seriesModel.legendVisualProvider;
  75873. var names = provider.getAllNames();
  75874. if (!ecModel.isSeriesFiltered(seriesModel)) {
  75875. availableNames = availableNames.concat(names);
  75876. }
  75877. if (names.length) {
  75878. potentialData = potentialData.concat(names);
  75879. } else {
  75880. isPotential = true;
  75881. }
  75882. } else {
  75883. isPotential = true;
  75884. }
  75885. if (isPotential && isNameSpecified(seriesModel)) {
  75886. potentialData.push(seriesModel.name);
  75887. }
  75888. });
  75889. /**
  75890. * @type {Array.<string>}
  75891. * @private
  75892. */
  75893. this._availableNames = availableNames; // If legend.data is not specified in option, use availableNames as data,
  75894. // which is convenient for user preparing option.
  75895. var rawData = this.get('data') || potentialData;
  75896. var legendNameMap = createHashMap();
  75897. var legendData = map(rawData, function (dataItem) {
  75898. // Can be string or number
  75899. if (isString(dataItem) || isNumber(dataItem)) {
  75900. dataItem = {
  75901. name: dataItem
  75902. };
  75903. }
  75904. if (legendNameMap.get(dataItem.name)) {
  75905. // remove legend name duplicate
  75906. return null;
  75907. }
  75908. legendNameMap.set(dataItem.name, true);
  75909. return new Model(dataItem, this, this.ecModel);
  75910. }, this);
  75911. /**
  75912. * @type {Array.<module:echarts/model/Model>}
  75913. * @private
  75914. */
  75915. this._data = filter(legendData, function (item) {
  75916. return !!item;
  75917. });
  75918. };
  75919. LegendModel.prototype.getData = function () {
  75920. return this._data;
  75921. };
  75922. LegendModel.prototype.select = function (name) {
  75923. var selected = this.option.selected;
  75924. var selectedMode = this.get('selectedMode');
  75925. if (selectedMode === 'single') {
  75926. var data = this._data;
  75927. each(data, function (dataItem) {
  75928. selected[dataItem.get('name')] = false;
  75929. });
  75930. }
  75931. selected[name] = true;
  75932. };
  75933. LegendModel.prototype.unSelect = function (name) {
  75934. if (this.get('selectedMode') !== 'single') {
  75935. this.option.selected[name] = false;
  75936. }
  75937. };
  75938. LegendModel.prototype.toggleSelected = function (name) {
  75939. var selected = this.option.selected; // Default is true
  75940. if (!selected.hasOwnProperty(name)) {
  75941. selected[name] = true;
  75942. }
  75943. this[selected[name] ? 'unSelect' : 'select'](name);
  75944. };
  75945. LegendModel.prototype.allSelect = function () {
  75946. var data = this._data;
  75947. var selected = this.option.selected;
  75948. each(data, function (dataItem) {
  75949. selected[dataItem.get('name', true)] = true;
  75950. });
  75951. };
  75952. LegendModel.prototype.inverseSelect = function () {
  75953. var data = this._data;
  75954. var selected = this.option.selected;
  75955. each(data, function (dataItem) {
  75956. var name = dataItem.get('name', true); // Initially, default value is true
  75957. if (!selected.hasOwnProperty(name)) {
  75958. selected[name] = true;
  75959. }
  75960. selected[name] = !selected[name];
  75961. });
  75962. };
  75963. LegendModel.prototype.isSelected = function (name) {
  75964. var selected = this.option.selected;
  75965. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  75966. };
  75967. LegendModel.prototype.getOrient = function () {
  75968. return this.get('orient') === 'vertical' ? {
  75969. index: 1,
  75970. name: 'vertical'
  75971. } : {
  75972. index: 0,
  75973. name: 'horizontal'
  75974. };
  75975. };
  75976. LegendModel.type = 'legend.plain';
  75977. LegendModel.dependencies = ['series'];
  75978. LegendModel.defaultOption = {
  75979. // zlevel: 0,
  75980. z: 4,
  75981. show: true,
  75982. orient: 'horizontal',
  75983. left: 'center',
  75984. // right: 'center',
  75985. top: 0,
  75986. // bottom: null,
  75987. align: 'auto',
  75988. backgroundColor: 'rgba(0,0,0,0)',
  75989. borderColor: '#ccc',
  75990. borderRadius: 0,
  75991. borderWidth: 0,
  75992. padding: 5,
  75993. itemGap: 10,
  75994. itemWidth: 25,
  75995. itemHeight: 14,
  75996. symbolRotate: 'inherit',
  75997. symbolKeepAspect: true,
  75998. inactiveColor: '#ccc',
  75999. inactiveBorderColor: '#ccc',
  76000. inactiveBorderWidth: 'auto',
  76001. itemStyle: {
  76002. color: 'inherit',
  76003. opacity: 'inherit',
  76004. borderColor: 'inherit',
  76005. borderWidth: 'auto',
  76006. borderCap: 'inherit',
  76007. borderJoin: 'inherit',
  76008. borderDashOffset: 'inherit',
  76009. borderMiterLimit: 'inherit'
  76010. },
  76011. lineStyle: {
  76012. width: 'auto',
  76013. color: 'inherit',
  76014. inactiveColor: '#ccc',
  76015. inactiveWidth: 2,
  76016. opacity: 'inherit',
  76017. type: 'inherit',
  76018. cap: 'inherit',
  76019. join: 'inherit',
  76020. dashOffset: 'inherit',
  76021. miterLimit: 'inherit'
  76022. },
  76023. textStyle: {
  76024. color: '#333'
  76025. },
  76026. selectedMode: true,
  76027. selector: false,
  76028. selectorLabel: {
  76029. show: true,
  76030. borderRadius: 10,
  76031. padding: [3, 5, 3, 5],
  76032. fontSize: 12,
  76033. fontFamily: 'sans-serif',
  76034. color: '#666',
  76035. borderWidth: 1,
  76036. borderColor: '#666'
  76037. },
  76038. emphasis: {
  76039. selectorLabel: {
  76040. show: true,
  76041. color: '#eee',
  76042. backgroundColor: '#666'
  76043. }
  76044. },
  76045. selectorPosition: 'auto',
  76046. selectorItemGap: 7,
  76047. selectorButtonGap: 10,
  76048. tooltip: {
  76049. show: false
  76050. }
  76051. };
  76052. return LegendModel;
  76053. }(ComponentModel);
  76054. var curry$1 = curry;
  76055. var each$c = each;
  76056. var Group$2 = Group;
  76057. var LegendView =
  76058. /** @class */
  76059. function (_super) {
  76060. __extends(LegendView, _super);
  76061. function LegendView() {
  76062. var _this = _super !== null && _super.apply(this, arguments) || this;
  76063. _this.type = LegendView.type;
  76064. _this.newlineDisabled = false;
  76065. return _this;
  76066. }
  76067. LegendView.prototype.init = function () {
  76068. this.group.add(this._contentGroup = new Group$2());
  76069. this.group.add(this._selectorGroup = new Group$2());
  76070. this._isFirstRender = true;
  76071. };
  76072. /**
  76073. * @protected
  76074. */
  76075. LegendView.prototype.getContentGroup = function () {
  76076. return this._contentGroup;
  76077. };
  76078. /**
  76079. * @protected
  76080. */
  76081. LegendView.prototype.getSelectorGroup = function () {
  76082. return this._selectorGroup;
  76083. };
  76084. /**
  76085. * @override
  76086. */
  76087. LegendView.prototype.render = function (legendModel, ecModel, api) {
  76088. var isFirstRender = this._isFirstRender;
  76089. this._isFirstRender = false;
  76090. this.resetInner();
  76091. if (!legendModel.get('show', true)) {
  76092. return;
  76093. }
  76094. var itemAlign = legendModel.get('align');
  76095. var orient = legendModel.get('orient');
  76096. if (!itemAlign || itemAlign === 'auto') {
  76097. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  76098. } // selector has been normalized to an array in model
  76099. var selector = legendModel.get('selector', true);
  76100. var selectorPosition = legendModel.get('selectorPosition', true);
  76101. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  76102. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  76103. }
  76104. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  76105. var positionInfo = legendModel.getBoxLayoutParams();
  76106. var viewportSize = {
  76107. width: api.getWidth(),
  76108. height: api.getHeight()
  76109. };
  76110. var padding = legendModel.get('padding');
  76111. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  76112. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  76113. var layoutRect = getLayoutRect(defaults({
  76114. width: mainRect.width,
  76115. height: mainRect.height
  76116. }, positionInfo), viewportSize, padding);
  76117. this.group.x = layoutRect.x - mainRect.x;
  76118. this.group.y = layoutRect.y - mainRect.y;
  76119. this.group.markRedraw(); // Render background after group is layout.
  76120. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  76121. };
  76122. LegendView.prototype.resetInner = function () {
  76123. this.getContentGroup().removeAll();
  76124. this._backgroundEl && this.group.remove(this._backgroundEl);
  76125. this.getSelectorGroup().removeAll();
  76126. };
  76127. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76128. var contentGroup = this.getContentGroup();
  76129. var legendDrawnMap = createHashMap();
  76130. var selectMode = legendModel.get('selectedMode');
  76131. var excludeSeriesId = [];
  76132. ecModel.eachRawSeries(function (seriesModel) {
  76133. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  76134. });
  76135. each$c(legendModel.getData(), function (legendItemModel, dataIndex) {
  76136. var name = legendItemModel.get('name'); // Use empty string or \n as a newline string
  76137. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  76138. var g = new Group$2(); // @ts-ignore
  76139. g.newline = true;
  76140. contentGroup.add(g);
  76141. return;
  76142. } // Representitive series.
  76143. var seriesModel = ecModel.getSeriesByName(name)[0];
  76144. if (legendDrawnMap.get(name)) {
  76145. // Have been drawn
  76146. return;
  76147. } // Legend to control series.
  76148. if (seriesModel) {
  76149. var data = seriesModel.getData();
  76150. var lineVisualStyle = data.getVisual('legendLineStyle') || {};
  76151. var legendIcon = data.getVisual('legendIcon');
  76152. /**
  76153. * `data.getVisual('style')` may be the color from the register
  76154. * in series. For example, for line series,
  76155. */
  76156. var style = data.getVisual('style');
  76157. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, style, legendIcon, selectMode, api);
  76158. 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));
  76159. legendDrawnMap.set(name, true);
  76160. } else {
  76161. // Legend to control data. In pie and funnel.
  76162. ecModel.eachRawSeries(function (seriesModel) {
  76163. // In case multiple series has same data name
  76164. if (legendDrawnMap.get(name)) {
  76165. return;
  76166. }
  76167. if (seriesModel.legendVisualProvider) {
  76168. var provider = seriesModel.legendVisualProvider;
  76169. if (!provider.containName(name)) {
  76170. return;
  76171. }
  76172. var idx = provider.indexOfName(name);
  76173. var style = provider.getItemVisual(idx, 'style');
  76174. var legendIcon = provider.getItemVisual(idx, 'legendIcon');
  76175. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  76176. // Do not show nothing.
  76177. if (colorArr && colorArr[3] === 0) {
  76178. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  76179. style = extend(extend({}, style), {
  76180. fill: stringify(colorArr, 'rgba')
  76181. });
  76182. }
  76183. var itemGroup = this._createItem(seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, {}, style, legendIcon, selectMode, api); // FIXME: consider different series has items with the same name.
  76184. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  76185. // more than one pie series.
  76186. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  76187. legendDrawnMap.set(name, true);
  76188. }
  76189. }, this);
  76190. }
  76191. if ("development" !== 'production') {
  76192. if (!legendDrawnMap.get(name)) {
  76193. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  76194. }
  76195. }
  76196. }, this);
  76197. if (selector) {
  76198. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  76199. }
  76200. };
  76201. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  76202. var selectorGroup = this.getSelectorGroup();
  76203. each$c(selector, function createSelectorButton(selectorItem) {
  76204. var type = selectorItem.type;
  76205. var labelText = new ZRText({
  76206. style: {
  76207. x: 0,
  76208. y: 0,
  76209. align: 'center',
  76210. verticalAlign: 'middle'
  76211. },
  76212. onclick: function () {
  76213. api.dispatchAction({
  76214. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  76215. });
  76216. }
  76217. });
  76218. selectorGroup.add(labelText);
  76219. var labelModel = legendModel.getModel('selectorLabel');
  76220. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  76221. setLabelStyle(labelText, {
  76222. normal: labelModel,
  76223. emphasis: emphasisLabelModel
  76224. }, {
  76225. defaultText: selectorItem.title
  76226. });
  76227. enableHoverEmphasis(labelText);
  76228. });
  76229. };
  76230. LegendView.prototype._createItem = function (seriesModel, name, dataIndex, legendItemModel, legendModel, itemAlign, lineVisualStyle, itemVisualStyle, legendIcon, selectMode, api) {
  76231. var drawType = seriesModel.visualDrawType;
  76232. var itemWidth = legendModel.get('itemWidth');
  76233. var itemHeight = legendModel.get('itemHeight');
  76234. var isSelected = legendModel.isSelected(name);
  76235. var iconRotate = legendItemModel.get('symbolRotate');
  76236. var symbolKeepAspect = legendItemModel.get('symbolKeepAspect');
  76237. var legendIconType = legendItemModel.get('icon');
  76238. legendIcon = legendIconType || legendIcon || 'roundRect';
  76239. var style = getLegendStyle(legendIcon, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api);
  76240. var itemGroup = new Group$2();
  76241. var textStyleModel = legendItemModel.getModel('textStyle');
  76242. if (isFunction(seriesModel.getLegendIcon) && (!legendIconType || legendIconType === 'inherit')) {
  76243. // Series has specific way to define legend icon
  76244. itemGroup.add(seriesModel.getLegendIcon({
  76245. itemWidth: itemWidth,
  76246. itemHeight: itemHeight,
  76247. icon: legendIcon,
  76248. iconRotate: iconRotate,
  76249. itemStyle: style.itemStyle,
  76250. lineStyle: style.lineStyle,
  76251. symbolKeepAspect: symbolKeepAspect
  76252. }));
  76253. } else {
  76254. // Use default legend icon policy for most series
  76255. var rotate = legendIconType === 'inherit' && seriesModel.getData().getVisual('symbol') ? iconRotate === 'inherit' ? seriesModel.getData().getVisual('symbolRotate') : iconRotate : 0; // No rotation for no icon
  76256. itemGroup.add(getDefaultLegendIcon({
  76257. itemWidth: itemWidth,
  76258. itemHeight: itemHeight,
  76259. icon: legendIcon,
  76260. iconRotate: rotate,
  76261. itemStyle: style.itemStyle,
  76262. lineStyle: style.lineStyle,
  76263. symbolKeepAspect: symbolKeepAspect
  76264. }));
  76265. }
  76266. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  76267. var textAlign = itemAlign;
  76268. var formatter = legendModel.get('formatter');
  76269. var content = name;
  76270. if (isString(formatter) && formatter) {
  76271. content = formatter.replace('{name}', name != null ? name : '');
  76272. } else if (isFunction(formatter)) {
  76273. content = formatter(name);
  76274. }
  76275. var textColor = isSelected ? textStyleModel.getTextColor() : legendItemModel.get('inactiveColor');
  76276. itemGroup.add(new ZRText({
  76277. style: createTextStyle(textStyleModel, {
  76278. text: content,
  76279. x: textX,
  76280. y: itemHeight / 2,
  76281. fill: textColor,
  76282. align: textAlign,
  76283. verticalAlign: 'middle'
  76284. }, {
  76285. inheritColor: textColor
  76286. })
  76287. })); // Add a invisible rect to increase the area of mouse hover
  76288. var hitRect = new Rect({
  76289. shape: itemGroup.getBoundingRect(),
  76290. invisible: true
  76291. });
  76292. var tooltipModel = legendItemModel.getModel('tooltip');
  76293. if (tooltipModel.get('show')) {
  76294. setTooltipConfig({
  76295. el: hitRect,
  76296. componentModel: legendModel,
  76297. itemName: name,
  76298. itemTooltipOption: tooltipModel.option
  76299. });
  76300. }
  76301. itemGroup.add(hitRect);
  76302. itemGroup.eachChild(function (child) {
  76303. child.silent = true;
  76304. });
  76305. hitRect.silent = !selectMode;
  76306. this.getContentGroup().add(itemGroup);
  76307. enableHoverEmphasis(itemGroup); // @ts-ignore
  76308. itemGroup.__legendDataIndex = dataIndex;
  76309. return itemGroup;
  76310. };
  76311. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76312. var contentGroup = this.getContentGroup();
  76313. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  76314. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  76315. var contentRect = contentGroup.getBoundingRect();
  76316. var contentPos = [-contentRect.x, -contentRect.y];
  76317. selectorGroup.markRedraw();
  76318. contentGroup.markRedraw();
  76319. if (selector) {
  76320. // Place buttons in selectorGroup
  76321. box( // Buttons in selectorGroup always layout horizontally
  76322. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76323. var selectorRect = selectorGroup.getBoundingRect();
  76324. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76325. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76326. var orientIdx = legendModel.getOrient().index;
  76327. var wh = orientIdx === 0 ? 'width' : 'height';
  76328. var hw = orientIdx === 0 ? 'height' : 'width';
  76329. var yx = orientIdx === 0 ? 'y' : 'x';
  76330. if (selectorPosition === 'end') {
  76331. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  76332. } else {
  76333. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  76334. } // Always align selector to content as 'middle'
  76335. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  76336. selectorGroup.x = selectorPos[0];
  76337. selectorGroup.y = selectorPos[1];
  76338. contentGroup.x = contentPos[0];
  76339. contentGroup.y = contentPos[1];
  76340. var mainRect = {
  76341. x: 0,
  76342. y: 0
  76343. };
  76344. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  76345. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  76346. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  76347. return mainRect;
  76348. } else {
  76349. contentGroup.x = contentPos[0];
  76350. contentGroup.y = contentPos[1];
  76351. return this.group.getBoundingRect();
  76352. }
  76353. };
  76354. /**
  76355. * @protected
  76356. */
  76357. LegendView.prototype.remove = function () {
  76358. this.getContentGroup().removeAll();
  76359. this._isFirstRender = true;
  76360. };
  76361. LegendView.type = 'legend.plain';
  76362. return LegendView;
  76363. }(ComponentView);
  76364. function getLegendStyle(iconType, legendItemModel, lineVisualStyle, itemVisualStyle, drawType, isSelected, api) {
  76365. /**
  76366. * Use series style if is inherit;
  76367. * elsewise, use legend style
  76368. */
  76369. function handleCommonProps(style, visualStyle) {
  76370. // If lineStyle.width is 'auto', it is set to be 2 if series has border
  76371. if (style.lineWidth === 'auto') {
  76372. style.lineWidth = visualStyle.lineWidth > 0 ? 2 : 0;
  76373. }
  76374. each$c(style, function (propVal, propName) {
  76375. style[propName] === 'inherit' && (style[propName] = visualStyle[propName]);
  76376. });
  76377. } // itemStyle
  76378. var itemStyleModel = legendItemModel.getModel('itemStyle');
  76379. var itemStyle = itemStyleModel.getItemStyle();
  76380. var iconBrushType = iconType.lastIndexOf('empty', 0) === 0 ? 'fill' : 'stroke';
  76381. var decalStyle = itemStyleModel.getShallow('decal');
  76382. itemStyle.decal = !decalStyle || decalStyle === 'inherit' ? itemVisualStyle.decal : createOrUpdatePatternFromDecal(decalStyle, api);
  76383. if (itemStyle.fill === 'inherit') {
  76384. /**
  76385. * Series with visualDrawType as 'stroke' should have
  76386. * series stroke as legend fill
  76387. */
  76388. itemStyle.fill = itemVisualStyle[drawType];
  76389. }
  76390. if (itemStyle.stroke === 'inherit') {
  76391. /**
  76392. * icon type with "emptyXXX" should use fill color
  76393. * in visual style
  76394. */
  76395. itemStyle.stroke = itemVisualStyle[iconBrushType];
  76396. }
  76397. if (itemStyle.opacity === 'inherit') {
  76398. /**
  76399. * Use lineStyle.opacity if drawType is stroke
  76400. */
  76401. itemStyle.opacity = (drawType === 'fill' ? itemVisualStyle : lineVisualStyle).opacity;
  76402. }
  76403. handleCommonProps(itemStyle, itemVisualStyle); // lineStyle
  76404. var legendLineModel = legendItemModel.getModel('lineStyle');
  76405. var lineStyle = legendLineModel.getLineStyle();
  76406. handleCommonProps(lineStyle, lineVisualStyle); // Fix auto color to real color
  76407. itemStyle.fill === 'auto' && (itemStyle.fill = itemVisualStyle.fill);
  76408. itemStyle.stroke === 'auto' && (itemStyle.stroke = itemVisualStyle.fill);
  76409. lineStyle.stroke === 'auto' && (lineStyle.stroke = itemVisualStyle.fill);
  76410. if (!isSelected) {
  76411. var borderWidth = legendItemModel.get('inactiveBorderWidth');
  76412. /**
  76413. * Since stroke is set to be inactiveBorderColor, it may occur that
  76414. * there is no border in series but border in legend, so we need to
  76415. * use border only when series has border if is set to be auto
  76416. */
  76417. var visualHasBorder = itemStyle[iconBrushType];
  76418. itemStyle.lineWidth = borderWidth === 'auto' ? itemVisualStyle.lineWidth > 0 && visualHasBorder ? 2 : 0 : itemStyle.lineWidth;
  76419. itemStyle.fill = legendItemModel.get('inactiveColor');
  76420. itemStyle.stroke = legendItemModel.get('inactiveBorderColor');
  76421. lineStyle.stroke = legendLineModel.get('inactiveColor');
  76422. lineStyle.lineWidth = legendLineModel.get('inactiveWidth');
  76423. }
  76424. return {
  76425. itemStyle: itemStyle,
  76426. lineStyle: lineStyle
  76427. };
  76428. }
  76429. function getDefaultLegendIcon(opt) {
  76430. var symboType = opt.icon || 'roundRect';
  76431. var icon = createSymbol(symboType, 0, 0, opt.itemWidth, opt.itemHeight, opt.itemStyle.fill, opt.symbolKeepAspect);
  76432. icon.setStyle(opt.itemStyle);
  76433. icon.rotation = (opt.iconRotate || 0) * Math.PI / 180;
  76434. icon.setOrigin([opt.itemWidth / 2, opt.itemHeight / 2]);
  76435. if (symboType.indexOf('empty') > -1) {
  76436. icon.style.stroke = icon.style.fill;
  76437. icon.style.fill = '#fff';
  76438. icon.style.lineWidth = 2;
  76439. }
  76440. return icon;
  76441. }
  76442. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  76443. // downplay before unselect
  76444. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  76445. api.dispatchAction({
  76446. type: 'legendToggleSelect',
  76447. name: seriesName != null ? seriesName : dataName
  76448. }); // highlight after select
  76449. // TODO highlight immediately may cause animation loss.
  76450. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  76451. }
  76452. function isUseHoverLayer(api) {
  76453. var list = api.getZr().storage.getDisplayList();
  76454. var emphasisState;
  76455. var i = 0;
  76456. var len = list.length;
  76457. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  76458. i++;
  76459. }
  76460. return emphasisState && emphasisState.hoverLayer;
  76461. }
  76462. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  76463. // If element hover will move to a hoverLayer.
  76464. if (!isUseHoverLayer(api)) {
  76465. api.dispatchAction({
  76466. type: 'highlight',
  76467. seriesName: seriesName,
  76468. name: dataName,
  76469. excludeSeriesId: excludeSeriesId
  76470. });
  76471. }
  76472. }
  76473. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  76474. // If element hover will move to a hoverLayer.
  76475. if (!isUseHoverLayer(api)) {
  76476. api.dispatchAction({
  76477. type: 'downplay',
  76478. seriesName: seriesName,
  76479. name: dataName,
  76480. excludeSeriesId: excludeSeriesId
  76481. });
  76482. }
  76483. }
  76484. /*
  76485. * Licensed to the Apache Software Foundation (ASF) under one
  76486. * or more contributor license agreements. See the NOTICE file
  76487. * distributed with this work for additional information
  76488. * regarding copyright ownership. The ASF licenses this file
  76489. * to you under the Apache License, Version 2.0 (the
  76490. * "License"); you may not use this file except in compliance
  76491. * with the License. You may obtain a copy of the License at
  76492. *
  76493. * http://www.apache.org/licenses/LICENSE-2.0
  76494. *
  76495. * Unless required by applicable law or agreed to in writing,
  76496. * software distributed under the License is distributed on an
  76497. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76498. * KIND, either express or implied. See the License for the
  76499. * specific language governing permissions and limitations
  76500. * under the License.
  76501. */
  76502. /**
  76503. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76504. */
  76505. /*
  76506. * Licensed to the Apache Software Foundation (ASF) under one
  76507. * or more contributor license agreements. See the NOTICE file
  76508. * distributed with this work for additional information
  76509. * regarding copyright ownership. The ASF licenses this file
  76510. * to you under the Apache License, Version 2.0 (the
  76511. * "License"); you may not use this file except in compliance
  76512. * with the License. You may obtain a copy of the License at
  76513. *
  76514. * http://www.apache.org/licenses/LICENSE-2.0
  76515. *
  76516. * Unless required by applicable law or agreed to in writing,
  76517. * software distributed under the License is distributed on an
  76518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76519. * KIND, either express or implied. See the License for the
  76520. * specific language governing permissions and limitations
  76521. * under the License.
  76522. */
  76523. function legendFilter(ecModel) {
  76524. var legendModels = ecModel.findComponents({
  76525. mainType: 'legend'
  76526. });
  76527. if (legendModels && legendModels.length) {
  76528. ecModel.filterSeries(function (series) {
  76529. // If in any legend component the status is not selected.
  76530. // Because in legend series is assumed selected when it is not in the legend data.
  76531. for (var i = 0; i < legendModels.length; i++) {
  76532. if (!legendModels[i].isSelected(series.name)) {
  76533. return false;
  76534. }
  76535. }
  76536. return true;
  76537. });
  76538. }
  76539. }
  76540. function legendSelectActionHandler(methodName, payload, ecModel) {
  76541. var selectedMap = {};
  76542. var isToggleSelect = methodName === 'toggleSelected';
  76543. var isSelected; // Update all legend components
  76544. ecModel.eachComponent('legend', function (legendModel) {
  76545. if (isToggleSelect && isSelected != null) {
  76546. // Force other legend has same selected status
  76547. // Or the first is toggled to true and other are toggled to false
  76548. // In the case one legend has some item unSelected in option. And if other legend
  76549. // doesn't has the item, they will assume it is selected.
  76550. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  76551. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  76552. legendModel[methodName]();
  76553. } else {
  76554. legendModel[methodName](payload.name);
  76555. isSelected = legendModel.isSelected(payload.name);
  76556. }
  76557. var legendData = legendModel.getData();
  76558. each(legendData, function (model) {
  76559. var name = model.get('name'); // Wrap element
  76560. if (name === '\n' || name === '') {
  76561. return;
  76562. }
  76563. var isItemSelected = legendModel.isSelected(name);
  76564. if (selectedMap.hasOwnProperty(name)) {
  76565. // Unselected if any legend is unselected
  76566. selectedMap[name] = selectedMap[name] && isItemSelected;
  76567. } else {
  76568. selectedMap[name] = isItemSelected;
  76569. }
  76570. });
  76571. }); // Return the event explicitly
  76572. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  76573. selected: selectedMap
  76574. } : {
  76575. name: payload.name,
  76576. selected: selectedMap
  76577. };
  76578. }
  76579. function installLegendAction(registers) {
  76580. /**
  76581. * @event legendToggleSelect
  76582. * @type {Object}
  76583. * @property {string} type 'legendToggleSelect'
  76584. * @property {string} [from]
  76585. * @property {string} name Series name or data item name
  76586. */
  76587. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  76588. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  76589. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  76590. /**
  76591. * @event legendSelect
  76592. * @type {Object}
  76593. * @property {string} type 'legendSelect'
  76594. * @property {string} name Series name or data item name
  76595. */
  76596. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  76597. /**
  76598. * @event legendUnSelect
  76599. * @type {Object}
  76600. * @property {string} type 'legendUnSelect'
  76601. * @property {string} name Series name or data item name
  76602. */
  76603. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  76604. }
  76605. function install$H(registers) {
  76606. registers.registerComponentModel(LegendModel);
  76607. registers.registerComponentView(LegendView);
  76608. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  76609. registers.registerSubTypeDefaulter('legend', function () {
  76610. return 'plain';
  76611. });
  76612. installLegendAction(registers);
  76613. }
  76614. var ScrollableLegendModel =
  76615. /** @class */
  76616. function (_super) {
  76617. __extends(ScrollableLegendModel, _super);
  76618. function ScrollableLegendModel() {
  76619. var _this = _super !== null && _super.apply(this, arguments) || this;
  76620. _this.type = ScrollableLegendModel.type;
  76621. return _this;
  76622. }
  76623. /**
  76624. * @param {number} scrollDataIndex
  76625. */
  76626. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  76627. this.option.scrollDataIndex = scrollDataIndex;
  76628. };
  76629. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  76630. var inputPositionParams = getLayoutParams(option);
  76631. _super.prototype.init.call(this, option, parentModel, ecModel);
  76632. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  76633. };
  76634. /**
  76635. * @override
  76636. */
  76637. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  76638. _super.prototype.mergeOption.call(this, option, ecModel);
  76639. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  76640. };
  76641. ScrollableLegendModel.type = 'legend.scroll';
  76642. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  76643. scrollDataIndex: 0,
  76644. pageButtonItemGap: 5,
  76645. pageButtonGap: null,
  76646. pageButtonPosition: 'end',
  76647. pageFormatter: '{current}/{total}',
  76648. pageIcons: {
  76649. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  76650. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  76651. },
  76652. pageIconColor: '#2f4554',
  76653. pageIconInactiveColor: '#aaa',
  76654. pageIconSize: 15,
  76655. pageTextStyle: {
  76656. color: '#333'
  76657. },
  76658. animationDurationUpdate: 800
  76659. });
  76660. return ScrollableLegendModel;
  76661. }(LegendModel);
  76662. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  76663. var orient = legendModel.getOrient();
  76664. var ignoreSize = [1, 1];
  76665. ignoreSize[orient.index] = 0;
  76666. mergeLayoutParam(target, raw, {
  76667. type: 'box',
  76668. ignoreSize: !!ignoreSize
  76669. });
  76670. }
  76671. var Group$3 = Group;
  76672. var WH$1 = ['width', 'height'];
  76673. var XY$1 = ['x', 'y'];
  76674. var ScrollableLegendView =
  76675. /** @class */
  76676. function (_super) {
  76677. __extends(ScrollableLegendView, _super);
  76678. function ScrollableLegendView() {
  76679. var _this = _super !== null && _super.apply(this, arguments) || this;
  76680. _this.type = ScrollableLegendView.type;
  76681. _this.newlineDisabled = true;
  76682. _this._currentIndex = 0;
  76683. return _this;
  76684. }
  76685. ScrollableLegendView.prototype.init = function () {
  76686. _super.prototype.init.call(this);
  76687. this.group.add(this._containerGroup = new Group$3());
  76688. this._containerGroup.add(this.getContentGroup());
  76689. this.group.add(this._controllerGroup = new Group$3());
  76690. };
  76691. /**
  76692. * @override
  76693. */
  76694. ScrollableLegendView.prototype.resetInner = function () {
  76695. _super.prototype.resetInner.call(this);
  76696. this._controllerGroup.removeAll();
  76697. this._containerGroup.removeClipPath();
  76698. this._containerGroup.__rectSize = null;
  76699. };
  76700. /**
  76701. * @override
  76702. */
  76703. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  76704. var self = this; // Render content items.
  76705. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  76706. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  76707. // e.g., '3/12345' should not overlap with the control arrow button.
  76708. var pageIconSize = legendModel.get('pageIconSize', true);
  76709. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  76710. createPageButton('pagePrev', 0);
  76711. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  76712. controllerGroup.add(new ZRText({
  76713. name: 'pageText',
  76714. style: {
  76715. // Placeholder to calculate a proper layout.
  76716. text: 'xx/xx',
  76717. fill: pageTextStyleModel.getTextColor(),
  76718. font: pageTextStyleModel.getFont(),
  76719. verticalAlign: 'middle',
  76720. align: 'center'
  76721. },
  76722. silent: true
  76723. }));
  76724. createPageButton('pageNext', 1);
  76725. function createPageButton(name, iconIdx) {
  76726. var pageDataIndexName = name + 'DataIndex';
  76727. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  76728. // Buttons will be created in each render, so we do not need
  76729. // to worry about avoiding using legendModel kept in scope.
  76730. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  76731. }, {
  76732. x: -pageIconSizeArr[0] / 2,
  76733. y: -pageIconSizeArr[1] / 2,
  76734. width: pageIconSizeArr[0],
  76735. height: pageIconSizeArr[1]
  76736. });
  76737. icon.name = name;
  76738. controllerGroup.add(icon);
  76739. }
  76740. };
  76741. /**
  76742. * @override
  76743. */
  76744. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  76745. var selectorGroup = this.getSelectorGroup();
  76746. var orientIdx = legendModel.getOrient().index;
  76747. var wh = WH$1[orientIdx];
  76748. var xy = XY$1[orientIdx];
  76749. var hw = WH$1[1 - orientIdx];
  76750. var yx = XY$1[1 - orientIdx];
  76751. selector && box( // Buttons in selectorGroup always layout horizontally
  76752. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  76753. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  76754. var selectorRect = selectorGroup.getBoundingRect();
  76755. var selectorPos = [-selectorRect.x, -selectorRect.y];
  76756. var processMaxSize = clone(maxSize);
  76757. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  76758. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  76759. if (selector) {
  76760. if (selectorPosition === 'end') {
  76761. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  76762. } else {
  76763. var offset = selectorRect[wh] + selectorButtonGap;
  76764. selectorPos[orientIdx] -= offset;
  76765. mainRect[xy] -= offset;
  76766. }
  76767. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  76768. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  76769. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  76770. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  76771. selectorGroup.x = selectorPos[0];
  76772. selectorGroup.y = selectorPos[1];
  76773. selectorGroup.markRedraw();
  76774. }
  76775. return mainRect;
  76776. };
  76777. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  76778. var contentGroup = this.getContentGroup();
  76779. var containerGroup = this._containerGroup;
  76780. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  76781. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  76782. box( // Buttons in controller are layout always horizontally.
  76783. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  76784. var contentRect = contentGroup.getBoundingRect();
  76785. var controllerRect = controllerGroup.getBoundingRect();
  76786. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  76787. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  76788. // If first rendering, `contentGroup.position` is [0, 0], which
  76789. // does not make sense and may cause unexepcted animation if adopted.
  76790. if (!isFirstRender) {
  76791. contentPos[orientIdx] = contentGroup[xy];
  76792. } // Layout container group based on 0.
  76793. var containerPos = [0, 0];
  76794. var controllerPos = [-controllerRect.x, -controllerRect.y];
  76795. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  76796. if (showController) {
  76797. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  76798. if (pageButtonPosition === 'end') {
  76799. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  76800. } // controller is on the left / top.
  76801. else {
  76802. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  76803. }
  76804. } // Always align controller to content as 'middle'.
  76805. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  76806. contentGroup.setPosition(contentPos);
  76807. containerGroup.setPosition(containerPos);
  76808. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  76809. // mainRect should not be calculated by `this.group.getBoundingRect()`
  76810. // for sake of the overflow.
  76811. var mainRect = {
  76812. x: 0,
  76813. y: 0
  76814. }; // Consider content may be overflow (should be clipped).
  76815. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  76816. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  76817. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  76818. containerGroup.__rectSize = maxSize[wh];
  76819. if (showController) {
  76820. var clipShape = {
  76821. x: 0,
  76822. y: 0
  76823. };
  76824. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  76825. clipShape[hw] = mainRect[hw];
  76826. containerGroup.setClipPath(new Rect({
  76827. shape: clipShape
  76828. })); // Consider content may be larger than container, container rect
  76829. // can not be obtained from `containerGroup.getBoundingRect()`.
  76830. containerGroup.__rectSize = clipShape[wh];
  76831. } else {
  76832. // Do not remove or ignore controller. Keep them set as placeholders.
  76833. controllerGroup.eachChild(function (child) {
  76834. child.attr({
  76835. invisible: true,
  76836. silent: true
  76837. });
  76838. });
  76839. } // Content translate animation.
  76840. var pageInfo = this._getPageInfo(legendModel);
  76841. pageInfo.pageIndex != null && updateProps(contentGroup, {
  76842. x: pageInfo.contentPosition[0],
  76843. y: pageInfo.contentPosition[1]
  76844. }, // When switch from "show controller" to "not show controller", view should be
  76845. // updated immediately without animation, otherwise causes weird effect.
  76846. showController ? legendModel : null);
  76847. this._updatePageInfoView(legendModel, pageInfo);
  76848. return mainRect;
  76849. };
  76850. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  76851. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  76852. scrollDataIndex != null && api.dispatchAction({
  76853. type: 'legendScroll',
  76854. scrollDataIndex: scrollDataIndex,
  76855. legendId: legendModel.id
  76856. });
  76857. };
  76858. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  76859. var controllerGroup = this._controllerGroup;
  76860. each(['pagePrev', 'pageNext'], function (name) {
  76861. var key = name + 'DataIndex';
  76862. var canJump = pageInfo[key] != null;
  76863. var icon = controllerGroup.childOfName(name);
  76864. if (icon) {
  76865. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  76866. icon.cursor = canJump ? 'pointer' : 'default';
  76867. }
  76868. });
  76869. var pageText = controllerGroup.childOfName('pageText');
  76870. var pageFormatter = legendModel.get('pageFormatter');
  76871. var pageIndex = pageInfo.pageIndex;
  76872. var current = pageIndex != null ? pageIndex + 1 : 0;
  76873. var total = pageInfo.pageCount;
  76874. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  76875. current: current,
  76876. total: total
  76877. }));
  76878. };
  76879. /**
  76880. * contentPosition: Array.<number>, null when data item not found.
  76881. * pageIndex: number, null when data item not found.
  76882. * pageCount: number, always be a number, can be 0.
  76883. * pagePrevDataIndex: number, null when no previous page.
  76884. * pageNextDataIndex: number, null when no next page.
  76885. * }
  76886. */
  76887. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  76888. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  76889. var contentGroup = this.getContentGroup();
  76890. var containerRectSize = this._containerGroup.__rectSize;
  76891. var orientIdx = legendModel.getOrient().index;
  76892. var wh = WH$1[orientIdx];
  76893. var xy = XY$1[orientIdx];
  76894. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  76895. var children = contentGroup.children();
  76896. var targetItem = children[targetItemIndex];
  76897. var itemCount = children.length;
  76898. var pCount = !itemCount ? 0 : 1;
  76899. var result = {
  76900. contentPosition: [contentGroup.x, contentGroup.y],
  76901. pageCount: pCount,
  76902. pageIndex: pCount - 1,
  76903. pagePrevDataIndex: null,
  76904. pageNextDataIndex: null
  76905. };
  76906. if (!targetItem) {
  76907. return result;
  76908. }
  76909. var targetItemInfo = getItemInfo(targetItem);
  76910. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  76911. // (1) Always align based on the left/top most item.
  76912. // (2) It is user-friendly that the last item shown in the
  76913. // current window is shown at the begining of next window.
  76914. // Otherwise if half of the last item is cut by the window,
  76915. // it will have no chance to display entirely.
  76916. // (3) Consider that item size probably be different, we
  76917. // have calculate pageIndex by size rather than item index,
  76918. // and we can not get page index directly by division.
  76919. // (4) The window is to narrow to contain more than
  76920. // one item, we should make sure that the page can be fliped.
  76921. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  76922. currItemInfo = getItemInfo(children[i]);
  76923. if ( // Half of the last item is out of the window.
  76924. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  76925. // can be started at the current item or the last item.
  76926. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  76927. if (winEndItemInfo.i > winStartItemInfo.i) {
  76928. winStartItemInfo = winEndItemInfo;
  76929. } else {
  76930. // e.g., when page size is smaller than item size.
  76931. winStartItemInfo = currItemInfo;
  76932. }
  76933. if (winStartItemInfo) {
  76934. if (result.pageNextDataIndex == null) {
  76935. result.pageNextDataIndex = winStartItemInfo.i;
  76936. }
  76937. ++result.pageCount;
  76938. }
  76939. }
  76940. winEndItemInfo = currItemInfo;
  76941. }
  76942. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  76943. currItemInfo = getItemInfo(children[i]);
  76944. if ( // If the the end item does not intersect with the window started
  76945. // from the current item, a page can be settled.
  76946. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  76947. winStartItemInfo.i < winEndItemInfo.i) {
  76948. winEndItemInfo = winStartItemInfo;
  76949. if (result.pagePrevDataIndex == null) {
  76950. result.pagePrevDataIndex = winStartItemInfo.i;
  76951. }
  76952. ++result.pageCount;
  76953. ++result.pageIndex;
  76954. }
  76955. winStartItemInfo = currItemInfo;
  76956. }
  76957. return result;
  76958. function getItemInfo(el) {
  76959. if (el) {
  76960. var itemRect = el.getBoundingRect();
  76961. var start = itemRect[xy] + el[xy];
  76962. return {
  76963. s: start,
  76964. e: start + itemRect[wh],
  76965. i: el.__legendDataIndex
  76966. };
  76967. }
  76968. }
  76969. function intersect(itemInfo, winStart) {
  76970. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  76971. }
  76972. };
  76973. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  76974. if (!this._showController) {
  76975. return 0;
  76976. }
  76977. var index;
  76978. var contentGroup = this.getContentGroup();
  76979. var defaultIndex;
  76980. contentGroup.eachChild(function (child, idx) {
  76981. var legendDataIdx = child.__legendDataIndex; // FIXME
  76982. // If the given targetDataIndex (from model) is illegal,
  76983. // we use defaultIndex. But the index on the legend model and
  76984. // action payload is still illegal. That case will not be
  76985. // changed until some scenario requires.
  76986. if (defaultIndex == null && legendDataIdx != null) {
  76987. defaultIndex = idx;
  76988. }
  76989. if (legendDataIdx === targetDataIndex) {
  76990. index = idx;
  76991. }
  76992. });
  76993. return index != null ? index : defaultIndex;
  76994. };
  76995. ScrollableLegendView.type = 'legend.scroll';
  76996. return ScrollableLegendView;
  76997. }(LegendView);
  76998. /*
  76999. * Licensed to the Apache Software Foundation (ASF) under one
  77000. * or more contributor license agreements. See the NOTICE file
  77001. * distributed with this work for additional information
  77002. * regarding copyright ownership. The ASF licenses this file
  77003. * to you under the Apache License, Version 2.0 (the
  77004. * "License"); you may not use this file except in compliance
  77005. * with the License. You may obtain a copy of the License at
  77006. *
  77007. * http://www.apache.org/licenses/LICENSE-2.0
  77008. *
  77009. * Unless required by applicable law or agreed to in writing,
  77010. * software distributed under the License is distributed on an
  77011. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77012. * KIND, either express or implied. See the License for the
  77013. * specific language governing permissions and limitations
  77014. * under the License.
  77015. */
  77016. /**
  77017. * AUTO-GENERATED FILE. DO NOT MODIFY.
  77018. */
  77019. /*
  77020. * Licensed to the Apache Software Foundation (ASF) under one
  77021. * or more contributor license agreements. See the NOTICE file
  77022. * distributed with this work for additional information
  77023. * regarding copyright ownership. The ASF licenses this file
  77024. * to you under the Apache License, Version 2.0 (the
  77025. * "License"); you may not use this file except in compliance
  77026. * with the License. You may obtain a copy of the License at
  77027. *
  77028. * http://www.apache.org/licenses/LICENSE-2.0
  77029. *
  77030. * Unless required by applicable law or agreed to in writing,
  77031. * software distributed under the License is distributed on an
  77032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77033. * KIND, either express or implied. See the License for the
  77034. * specific language governing permissions and limitations
  77035. * under the License.
  77036. */
  77037. function installScrollableLegendAction(registers) {
  77038. /**
  77039. * @event legendScroll
  77040. * @type {Object}
  77041. * @property {string} type 'legendScroll'
  77042. * @property {string} scrollDataIndex
  77043. */
  77044. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  77045. var scrollDataIndex = payload.scrollDataIndex;
  77046. scrollDataIndex != null && ecModel.eachComponent({
  77047. mainType: 'legend',
  77048. subType: 'scroll',
  77049. query: payload
  77050. }, function (legendModel) {
  77051. legendModel.setScrollDataIndex(scrollDataIndex);
  77052. });
  77053. });
  77054. }
  77055. function install$I(registers) {
  77056. use(install$H);
  77057. registers.registerComponentModel(ScrollableLegendModel);
  77058. registers.registerComponentView(ScrollableLegendView);
  77059. installScrollableLegendAction(registers);
  77060. }
  77061. function install$J(registers) {
  77062. use(install$H);
  77063. use(install$I);
  77064. }
  77065. var InsideZoomModel =
  77066. /** @class */
  77067. function (_super) {
  77068. __extends(InsideZoomModel, _super);
  77069. function InsideZoomModel() {
  77070. var _this = _super !== null && _super.apply(this, arguments) || this;
  77071. _this.type = InsideZoomModel.type;
  77072. return _this;
  77073. }
  77074. InsideZoomModel.type = 'dataZoom.inside';
  77075. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  77076. disabled: false,
  77077. zoomLock: false,
  77078. zoomOnMouseWheel: true,
  77079. moveOnMouseMove: true,
  77080. moveOnMouseWheel: false,
  77081. preventDefaultMouseMove: true
  77082. });
  77083. return InsideZoomModel;
  77084. }(DataZoomModel);
  77085. var inner$k = makeInner();
  77086. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  77087. inner$k(api).coordSysRecordMap.each(function (coordSysRecord) {
  77088. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  77089. if (dzInfo) {
  77090. dzInfo.getRange = getRange;
  77091. }
  77092. });
  77093. }
  77094. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  77095. var coordSysRecordMap = inner$k(api).coordSysRecordMap;
  77096. var coordSysKeyArr = coordSysRecordMap.keys();
  77097. for (var i = 0; i < coordSysKeyArr.length; i++) {
  77098. var coordSysKey = coordSysKeyArr[i];
  77099. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  77100. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  77101. if (dataZoomInfoMap) {
  77102. var dzUid = dataZoomModel.uid;
  77103. var dzInfo = dataZoomInfoMap.get(dzUid);
  77104. if (dzInfo) {
  77105. dataZoomInfoMap.removeKey(dzUid);
  77106. if (!dataZoomInfoMap.keys().length) {
  77107. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  77108. }
  77109. }
  77110. }
  77111. }
  77112. }
  77113. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  77114. if (coordSysRecord) {
  77115. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  77116. var controller = coordSysRecord.controller;
  77117. controller && controller.dispose();
  77118. }
  77119. }
  77120. function createCoordSysRecord(api, coordSysModel) {
  77121. // These init props will never change after record created.
  77122. var coordSysRecord = {
  77123. model: coordSysModel,
  77124. containsPoint: curry(containsPoint, coordSysModel),
  77125. dispatchAction: curry(dispatchAction$1, api),
  77126. dataZoomInfoMap: null,
  77127. controller: null
  77128. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  77129. // because coordSysRecord not completed yet.
  77130. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  77131. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  77132. controller.on(eventName, function (event) {
  77133. var batch = [];
  77134. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  77135. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  77136. // moveOnMouseWheel, ...) enabled.
  77137. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  77138. return;
  77139. }
  77140. var method = (dzInfo.getRange || {})[eventName];
  77141. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  77142. !dzInfo.model.get('disabled', true) && range && batch.push({
  77143. dataZoomId: dzInfo.model.id,
  77144. start: range[0],
  77145. end: range[1]
  77146. });
  77147. });
  77148. batch.length && coordSysRecord.dispatchAction(batch);
  77149. });
  77150. });
  77151. return coordSysRecord;
  77152. }
  77153. /**
  77154. * This action will be throttled.
  77155. */
  77156. function dispatchAction$1(api, batch) {
  77157. if (!api.isDisposed()) {
  77158. api.dispatchAction({
  77159. type: 'dataZoom',
  77160. animation: {
  77161. easing: 'cubicOut',
  77162. duration: 100
  77163. },
  77164. batch: batch
  77165. });
  77166. }
  77167. }
  77168. function containsPoint(coordSysModel, e, x, y) {
  77169. return coordSysModel.coordinateSystem.containPoint([x, y]);
  77170. }
  77171. /**
  77172. * Merge roamController settings when multiple dataZooms share one roamController.
  77173. */
  77174. function mergeControllerParams(dataZoomInfoMap) {
  77175. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  77176. // as string, it is probably revert to reserved word by compress tool. See #7411.
  77177. var prefix = 'type_';
  77178. var typePriority = {
  77179. 'type_true': 2,
  77180. 'type_move': 1,
  77181. 'type_false': 0,
  77182. 'type_undefined': -1
  77183. };
  77184. var preventDefaultMouseMove = true;
  77185. dataZoomInfoMap.each(function (dataZoomInfo) {
  77186. var dataZoomModel = dataZoomInfo.model;
  77187. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  77188. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  77189. controlType = oneType;
  77190. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  77191. // users may be confused why it does not work when multiple insideZooms exist.
  77192. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  77193. });
  77194. return {
  77195. controlType: controlType,
  77196. opt: {
  77197. // RoamController will enable all of these functionalities,
  77198. // and the final behavior is determined by its event listener
  77199. // provided by each inside zoom.
  77200. zoomOnMouseWheel: true,
  77201. moveOnMouseMove: true,
  77202. moveOnMouseWheel: true,
  77203. preventDefaultMouseMove: !!preventDefaultMouseMove
  77204. }
  77205. };
  77206. }
  77207. function installDataZoomRoamProcessor(registers) {
  77208. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  77209. var apiInner = inner$k(api);
  77210. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  77211. coordSysRecordMap.each(function (coordSysRecord) {
  77212. // `coordSysRecordMap` always exists (because it holds the `roam controller`, which should
  77213. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  77214. coordSysRecord.dataZoomInfoMap = null;
  77215. });
  77216. ecModel.eachComponent({
  77217. mainType: 'dataZoom',
  77218. subType: 'inside'
  77219. }, function (dataZoomModel) {
  77220. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  77221. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  77222. var coordSysUid = dzCoordSysInfo.model.uid;
  77223. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  77224. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  77225. dataZoomInfoMap.set(dataZoomModel.uid, {
  77226. dzReferCoordSysInfo: dzCoordSysInfo,
  77227. model: dataZoomModel,
  77228. getRange: null
  77229. });
  77230. });
  77231. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  77232. // (2) Clear coord sys if not refered by any dataZoom.
  77233. coordSysRecordMap.each(function (coordSysRecord) {
  77234. var controller = coordSysRecord.controller;
  77235. var firstDzInfo;
  77236. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  77237. if (dataZoomInfoMap) {
  77238. var firstDzKey = dataZoomInfoMap.keys()[0];
  77239. if (firstDzKey != null) {
  77240. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  77241. }
  77242. }
  77243. if (!firstDzInfo) {
  77244. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  77245. return;
  77246. }
  77247. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  77248. controller.enable(controllerParams.controlType, controllerParams.opt);
  77249. controller.setPointerChecker(coordSysRecord.containsPoint);
  77250. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  77251. });
  77252. });
  77253. }
  77254. var InsideZoomView =
  77255. /** @class */
  77256. function (_super) {
  77257. __extends(InsideZoomView, _super);
  77258. function InsideZoomView() {
  77259. var _this = _super !== null && _super.apply(this, arguments) || this;
  77260. _this.type = 'dataZoom.inside';
  77261. return _this;
  77262. }
  77263. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  77264. _super.prototype.render.apply(this, arguments);
  77265. if (dataZoomModel.noTarget()) {
  77266. this._clear();
  77267. return;
  77268. } // Hence the `throttle` util ensures to preserve command order,
  77269. // here simply updating range all the time will not cause missing
  77270. // any of the the roam change.
  77271. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  77272. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  77273. pan: bind(getRangeHandlers.pan, this),
  77274. zoom: bind(getRangeHandlers.zoom, this),
  77275. scrollMove: bind(getRangeHandlers.scrollMove, this)
  77276. });
  77277. };
  77278. InsideZoomView.prototype.dispose = function () {
  77279. this._clear();
  77280. _super.prototype.dispose.apply(this, arguments);
  77281. };
  77282. InsideZoomView.prototype._clear = function () {
  77283. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  77284. this.range = null;
  77285. };
  77286. InsideZoomView.type = 'dataZoom.inside';
  77287. return InsideZoomView;
  77288. }(DataZoomView);
  77289. var getRangeHandlers = {
  77290. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  77291. var lastRange = this.range;
  77292. var range = lastRange.slice(); // Calculate transform by the first axis.
  77293. var axisModel = coordSysInfo.axisModels[0];
  77294. if (!axisModel) {
  77295. return;
  77296. }
  77297. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  77298. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  77299. var scale = Math.max(1 / e.scale, 0);
  77300. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  77301. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  77302. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77303. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  77304. this.range = range;
  77305. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77306. return range;
  77307. }
  77308. },
  77309. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77310. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  77311. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  77312. }),
  77313. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  77314. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  77315. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  77316. })
  77317. };
  77318. function makeMover(getPercentDelta) {
  77319. return function (coordSysInfo, coordSysMainType, controller, e) {
  77320. var lastRange = this.range;
  77321. var range = lastRange.slice(); // Calculate transform by the first axis.
  77322. var axisModel = coordSysInfo.axisModels[0];
  77323. if (!axisModel) {
  77324. return;
  77325. }
  77326. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  77327. sliderMove(percentDelta, range, [0, 100], 'all');
  77328. this.range = range;
  77329. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  77330. return range;
  77331. }
  77332. };
  77333. }
  77334. var getDirectionInfo = {
  77335. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77336. var axis = axisModel.axis;
  77337. var ret = {};
  77338. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77339. oldPoint = oldPoint || [0, 0];
  77340. if (axis.dim === 'x') {
  77341. ret.pixel = newPoint[0] - oldPoint[0];
  77342. ret.pixelLength = rect.width;
  77343. ret.pixelStart = rect.x;
  77344. ret.signal = axis.inverse ? 1 : -1;
  77345. } else {
  77346. // axis.dim === 'y'
  77347. ret.pixel = newPoint[1] - oldPoint[1];
  77348. ret.pixelLength = rect.height;
  77349. ret.pixelStart = rect.y;
  77350. ret.signal = axis.inverse ? -1 : 1;
  77351. }
  77352. return ret;
  77353. },
  77354. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77355. var axis = axisModel.axis;
  77356. var ret = {};
  77357. var polar = coordSysInfo.model.coordinateSystem;
  77358. var radiusExtent = polar.getRadiusAxis().getExtent();
  77359. var angleExtent = polar.getAngleAxis().getExtent();
  77360. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  77361. newPoint = polar.pointToCoord(newPoint);
  77362. if (axisModel.mainType === 'radiusAxis') {
  77363. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  77364. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  77365. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  77366. ret.pixelStart = radiusExtent[0];
  77367. ret.signal = axis.inverse ? 1 : -1;
  77368. } else {
  77369. // 'angleAxis'
  77370. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  77371. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  77372. ret.pixelLength = angleExtent[1] - angleExtent[0];
  77373. ret.pixelStart = angleExtent[0];
  77374. ret.signal = axis.inverse ? -1 : 1;
  77375. }
  77376. return ret;
  77377. },
  77378. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  77379. var axis = axisModel.axis;
  77380. var rect = coordSysInfo.model.coordinateSystem.getRect();
  77381. var ret = {};
  77382. oldPoint = oldPoint || [0, 0];
  77383. if (axis.orient === 'horizontal') {
  77384. ret.pixel = newPoint[0] - oldPoint[0];
  77385. ret.pixelLength = rect.width;
  77386. ret.pixelStart = rect.x;
  77387. ret.signal = axis.inverse ? 1 : -1;
  77388. } else {
  77389. // 'vertical'
  77390. ret.pixel = newPoint[1] - oldPoint[1];
  77391. ret.pixelLength = rect.height;
  77392. ret.pixelStart = rect.y;
  77393. ret.signal = axis.inverse ? -1 : 1;
  77394. }
  77395. return ret;
  77396. }
  77397. };
  77398. function install$K(registers) {
  77399. installCommon(registers);
  77400. registers.registerComponentModel(InsideZoomModel);
  77401. registers.registerComponentView(InsideZoomView);
  77402. installDataZoomRoamProcessor(registers);
  77403. }
  77404. var SliderZoomModel =
  77405. /** @class */
  77406. function (_super) {
  77407. __extends(SliderZoomModel, _super);
  77408. function SliderZoomModel() {
  77409. var _this = _super !== null && _super.apply(this, arguments) || this;
  77410. _this.type = SliderZoomModel.type;
  77411. return _this;
  77412. }
  77413. SliderZoomModel.type = 'dataZoom.slider';
  77414. SliderZoomModel.layoutMode = 'box';
  77415. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  77416. show: true,
  77417. // deault value can only be drived in view stage.
  77418. right: 'ph',
  77419. top: 'ph',
  77420. width: 'ph',
  77421. height: 'ph',
  77422. left: null,
  77423. bottom: null,
  77424. borderColor: '#d2dbee',
  77425. borderRadius: 3,
  77426. backgroundColor: 'rgba(47,69,84,0)',
  77427. // dataBackgroundColor: '#ddd',
  77428. dataBackground: {
  77429. lineStyle: {
  77430. color: '#d2dbee',
  77431. width: 0.5
  77432. },
  77433. areaStyle: {
  77434. color: '#d2dbee',
  77435. opacity: 0.2
  77436. }
  77437. },
  77438. selectedDataBackground: {
  77439. lineStyle: {
  77440. color: '#8fb0f7',
  77441. width: 0.5
  77442. },
  77443. areaStyle: {
  77444. color: '#8fb0f7',
  77445. opacity: 0.2
  77446. }
  77447. },
  77448. // Color of selected window.
  77449. fillerColor: 'rgba(135,175,274,0.2)',
  77450. 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',
  77451. // Percent of the slider height
  77452. handleSize: '100%',
  77453. handleStyle: {
  77454. color: '#fff',
  77455. borderColor: '#ACB8D1'
  77456. },
  77457. moveHandleSize: 7,
  77458. 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',
  77459. moveHandleStyle: {
  77460. color: '#D2DBEE',
  77461. opacity: 0.7
  77462. },
  77463. showDetail: true,
  77464. showDataShadow: 'auto',
  77465. realtime: true,
  77466. zoomLock: false,
  77467. textStyle: {
  77468. color: '#6E7079'
  77469. },
  77470. brushSelect: true,
  77471. brushStyle: {
  77472. color: 'rgba(135,175,274,0.15)'
  77473. },
  77474. emphasis: {
  77475. handleStyle: {
  77476. borderColor: '#8FB0F7'
  77477. },
  77478. moveHandleStyle: {
  77479. color: '#8FB0F7'
  77480. }
  77481. }
  77482. });
  77483. return SliderZoomModel;
  77484. }(DataZoomModel);
  77485. var Rect$2 = Rect; // Constants
  77486. var DEFAULT_LOCATION_EDGE_GAP = 7;
  77487. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  77488. var DEFAULT_FILLER_SIZE = 30;
  77489. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  77490. var HORIZONTAL = 'horizontal';
  77491. var VERTICAL = 'vertical';
  77492. var LABEL_GAP = 5;
  77493. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  77494. var REALTIME_ANIMATION_CONFIG = {
  77495. easing: 'cubicOut',
  77496. duration: 100,
  77497. delay: 0
  77498. };
  77499. var SliderZoomView =
  77500. /** @class */
  77501. function (_super) {
  77502. __extends(SliderZoomView, _super);
  77503. function SliderZoomView() {
  77504. var _this = _super !== null && _super.apply(this, arguments) || this;
  77505. _this.type = SliderZoomView.type;
  77506. _this._displayables = {};
  77507. return _this;
  77508. }
  77509. SliderZoomView.prototype.init = function (ecModel, api) {
  77510. this.api = api; // A unique handler for each dataZoom component
  77511. this._onBrush = bind(this._onBrush, this);
  77512. this._onBrushEnd = bind(this._onBrushEnd, this);
  77513. };
  77514. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  77515. _super.prototype.render.apply(this, arguments);
  77516. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  77517. this._orient = dataZoomModel.getOrient();
  77518. if (dataZoomModel.get('show') === false) {
  77519. this.group.removeAll();
  77520. return;
  77521. }
  77522. if (dataZoomModel.noTarget()) {
  77523. this._clear();
  77524. this.group.removeAll();
  77525. return;
  77526. } // Notice: this._resetInterval() should not be executed when payload.type
  77527. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  77528. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  77529. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  77530. this._buildView();
  77531. }
  77532. this._updateView();
  77533. };
  77534. SliderZoomView.prototype.dispose = function () {
  77535. this._clear();
  77536. _super.prototype.dispose.apply(this, arguments);
  77537. };
  77538. SliderZoomView.prototype._clear = function () {
  77539. clear(this, '_dispatchZoomAction');
  77540. var zr = this.api.getZr();
  77541. zr.off('mousemove', this._onBrush);
  77542. zr.off('mouseup', this._onBrushEnd);
  77543. };
  77544. SliderZoomView.prototype._buildView = function () {
  77545. var thisGroup = this.group;
  77546. thisGroup.removeAll();
  77547. this._brushing = false;
  77548. this._displayables.brushRect = null;
  77549. this._resetLocation();
  77550. this._resetInterval();
  77551. var barGroup = this._displayables.sliderGroup = new Group();
  77552. this._renderBackground();
  77553. this._renderHandle();
  77554. this._renderDataShadow();
  77555. thisGroup.add(barGroup);
  77556. this._positionGroup();
  77557. };
  77558. SliderZoomView.prototype._resetLocation = function () {
  77559. var dataZoomModel = this.dataZoomModel;
  77560. var api = this.api;
  77561. var showMoveHandle = dataZoomModel.get('brushSelect');
  77562. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  77563. // auto-adapt according to target grid.
  77564. var coordRect = this._findCoordRect();
  77565. var ecSize = {
  77566. width: api.getWidth(),
  77567. height: api.getHeight()
  77568. }; // Default align by coordinate system rect.
  77569. var positionInfo = this._orient === HORIZONTAL ? {
  77570. // Why using 'right', because right should be used in vertical,
  77571. // and it is better to be consistent for dealing with position param merge.
  77572. right: ecSize.width - coordRect.x - coordRect.width,
  77573. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  77574. width: coordRect.width,
  77575. height: DEFAULT_FILLER_SIZE
  77576. } : {
  77577. right: DEFAULT_LOCATION_EDGE_GAP,
  77578. top: coordRect.y,
  77579. width: DEFAULT_FILLER_SIZE,
  77580. height: coordRect.height
  77581. }; // Do not write back to option and replace value 'ph', because
  77582. // the 'ph' value should be recalculated when resize.
  77583. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  77584. each(['right', 'top', 'width', 'height'], function (name) {
  77585. if (layoutParams[name] === 'ph') {
  77586. layoutParams[name] = positionInfo[name];
  77587. }
  77588. });
  77589. var layoutRect = getLayoutRect(layoutParams, ecSize);
  77590. this._location = {
  77591. x: layoutRect.x,
  77592. y: layoutRect.y
  77593. };
  77594. this._size = [layoutRect.width, layoutRect.height];
  77595. this._orient === VERTICAL && this._size.reverse();
  77596. };
  77597. SliderZoomView.prototype._positionGroup = function () {
  77598. var thisGroup = this.group;
  77599. var location = this._location;
  77600. var orient = this._orient; // Just use the first axis to determine mapping.
  77601. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  77602. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  77603. var sliderGroup = this._displayables.sliderGroup;
  77604. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  77605. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  77606. scaleY: otherAxisInverse ? 1 : -1,
  77607. scaleX: 1
  77608. } : orient === HORIZONTAL && inverse ? {
  77609. scaleY: otherAxisInverse ? 1 : -1,
  77610. scaleX: -1
  77611. } : orient === VERTICAL && !inverse ? {
  77612. scaleY: otherAxisInverse ? -1 : 1,
  77613. scaleX: 1,
  77614. rotation: Math.PI / 2
  77615. } // Don't use Math.PI, considering shadow direction.
  77616. : {
  77617. scaleY: otherAxisInverse ? -1 : 1,
  77618. scaleX: -1,
  77619. rotation: Math.PI / 2
  77620. }); // Position barGroup
  77621. var rect = thisGroup.getBoundingRect([sliderGroup]);
  77622. thisGroup.x = location.x - rect.x;
  77623. thisGroup.y = location.y - rect.y;
  77624. thisGroup.markRedraw();
  77625. };
  77626. SliderZoomView.prototype._getViewExtent = function () {
  77627. return [0, this._size[0]];
  77628. };
  77629. SliderZoomView.prototype._renderBackground = function () {
  77630. var dataZoomModel = this.dataZoomModel;
  77631. var size = this._size;
  77632. var barGroup = this._displayables.sliderGroup;
  77633. var brushSelect = dataZoomModel.get('brushSelect');
  77634. barGroup.add(new Rect$2({
  77635. silent: true,
  77636. shape: {
  77637. x: 0,
  77638. y: 0,
  77639. width: size[0],
  77640. height: size[1]
  77641. },
  77642. style: {
  77643. fill: dataZoomModel.get('backgroundColor')
  77644. },
  77645. z2: -40
  77646. })); // Click panel, over shadow, below handles.
  77647. var clickPanel = new Rect$2({
  77648. shape: {
  77649. x: 0,
  77650. y: 0,
  77651. width: size[0],
  77652. height: size[1]
  77653. },
  77654. style: {
  77655. fill: 'transparent'
  77656. },
  77657. z2: 0,
  77658. onclick: bind(this._onClickPanel, this)
  77659. });
  77660. var zr = this.api.getZr();
  77661. if (brushSelect) {
  77662. clickPanel.on('mousedown', this._onBrushStart, this);
  77663. clickPanel.cursor = 'crosshair';
  77664. zr.on('mousemove', this._onBrush);
  77665. zr.on('mouseup', this._onBrushEnd);
  77666. } else {
  77667. zr.off('mousemove', this._onBrush);
  77668. zr.off('mouseup', this._onBrushEnd);
  77669. }
  77670. barGroup.add(clickPanel);
  77671. };
  77672. SliderZoomView.prototype._renderDataShadow = function () {
  77673. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  77674. this._displayables.dataShadowSegs = [];
  77675. if (!info) {
  77676. return;
  77677. }
  77678. var size = this._size;
  77679. var oldSize = this._shadowSize || [];
  77680. var seriesModel = info.series;
  77681. var data = seriesModel.getRawData();
  77682. var candlestickDim = seriesModel.getShadowDim && seriesModel.getShadowDim();
  77683. var otherDim = candlestickDim && data.getDimensionInfo(candlestickDim) ? seriesModel.getShadowDim() // @see candlestick
  77684. : info.otherDim;
  77685. if (otherDim == null) {
  77686. return;
  77687. }
  77688. var polygonPts = this._shadowPolygonPts;
  77689. var polylinePts = this._shadowPolylinePts; // Not re-render if data doesn't change.
  77690. if (data !== this._shadowData || otherDim !== this._shadowDim || size[0] !== oldSize[0] || size[1] !== oldSize[1]) {
  77691. var otherDataExtent_1 = data.getDataExtent(otherDim); // Nice extent.
  77692. var otherOffset = (otherDataExtent_1[1] - otherDataExtent_1[0]) * 0.3;
  77693. otherDataExtent_1 = [otherDataExtent_1[0] - otherOffset, otherDataExtent_1[1] + otherOffset];
  77694. var otherShadowExtent_1 = [0, size[1]];
  77695. var thisShadowExtent = [0, size[0]];
  77696. var areaPoints_1 = [[size[0], 0], [0, 0]];
  77697. var linePoints_1 = [];
  77698. var step_1 = thisShadowExtent[1] / (data.count() - 1);
  77699. var thisCoord_1 = 0; // Optimize for large data shadow
  77700. var stride_1 = Math.round(data.count() / size[0]);
  77701. var lastIsEmpty_1;
  77702. data.each([otherDim], function (value, index) {
  77703. if (stride_1 > 0 && index % stride_1) {
  77704. thisCoord_1 += step_1;
  77705. return;
  77706. } // FIXME
  77707. // Should consider axis.min/axis.max when drawing dataShadow.
  77708. // FIXME
  77709. // 应该使用统一的空判断?还是在list里进行空判断?
  77710. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  77711. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent_1, otherShadowExtent_1, true); // Attempt to draw data shadow precisely when there are empty value.
  77712. if (isEmpty && !lastIsEmpty_1 && index) {
  77713. areaPoints_1.push([areaPoints_1[areaPoints_1.length - 1][0], 0]);
  77714. linePoints_1.push([linePoints_1[linePoints_1.length - 1][0], 0]);
  77715. } else if (!isEmpty && lastIsEmpty_1) {
  77716. areaPoints_1.push([thisCoord_1, 0]);
  77717. linePoints_1.push([thisCoord_1, 0]);
  77718. }
  77719. areaPoints_1.push([thisCoord_1, otherCoord]);
  77720. linePoints_1.push([thisCoord_1, otherCoord]);
  77721. thisCoord_1 += step_1;
  77722. lastIsEmpty_1 = isEmpty;
  77723. });
  77724. polygonPts = this._shadowPolygonPts = areaPoints_1;
  77725. polylinePts = this._shadowPolylinePts = linePoints_1;
  77726. }
  77727. this._shadowData = data;
  77728. this._shadowDim = otherDim;
  77729. this._shadowSize = [size[0], size[1]];
  77730. var dataZoomModel = this.dataZoomModel;
  77731. function createDataShadowGroup(isSelectedArea) {
  77732. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  77733. var group = new Group();
  77734. var polygon = new Polygon({
  77735. shape: {
  77736. points: polygonPts
  77737. },
  77738. segmentIgnoreThreshold: 1,
  77739. style: model.getModel('areaStyle').getAreaStyle(),
  77740. silent: true,
  77741. z2: -20
  77742. });
  77743. var polyline = new Polyline({
  77744. shape: {
  77745. points: polylinePts
  77746. },
  77747. segmentIgnoreThreshold: 1,
  77748. style: model.getModel('lineStyle').getLineStyle(),
  77749. silent: true,
  77750. z2: -19
  77751. });
  77752. group.add(polygon);
  77753. group.add(polyline);
  77754. return group;
  77755. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  77756. for (var i = 0; i < 3; i++) {
  77757. var group = createDataShadowGroup(i === 1);
  77758. this._displayables.sliderGroup.add(group);
  77759. this._displayables.dataShadowSegs.push(group);
  77760. }
  77761. };
  77762. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  77763. var dataZoomModel = this.dataZoomModel;
  77764. var showDataShadow = dataZoomModel.get('showDataShadow');
  77765. if (showDataShadow === false) {
  77766. return;
  77767. } // Find a representative series.
  77768. var result;
  77769. var ecModel = this.ecModel;
  77770. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  77771. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  77772. each(seriesModels, function (seriesModel) {
  77773. if (result) {
  77774. return;
  77775. }
  77776. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  77777. return;
  77778. }
  77779. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  77780. var otherDim = getOtherDim(axisDim);
  77781. var otherAxisInverse;
  77782. var coordSys = seriesModel.coordinateSystem;
  77783. if (otherDim != null && coordSys.getOtherAxis) {
  77784. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  77785. }
  77786. otherDim = seriesModel.getData().mapDimension(otherDim);
  77787. result = {
  77788. thisAxis: thisAxis,
  77789. series: seriesModel,
  77790. thisDim: axisDim,
  77791. otherDim: otherDim,
  77792. otherAxisInverse: otherAxisInverse
  77793. };
  77794. }, this);
  77795. }, this);
  77796. return result;
  77797. };
  77798. SliderZoomView.prototype._renderHandle = function () {
  77799. var thisGroup = this.group;
  77800. var displayables = this._displayables;
  77801. var handles = displayables.handles = [null, null];
  77802. var handleLabels = displayables.handleLabels = [null, null];
  77803. var sliderGroup = this._displayables.sliderGroup;
  77804. var size = this._size;
  77805. var dataZoomModel = this.dataZoomModel;
  77806. var api = this.api;
  77807. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  77808. var brushSelect = dataZoomModel.get('brushSelect');
  77809. var filler = displayables.filler = new Rect$2({
  77810. silent: brushSelect,
  77811. style: {
  77812. fill: dataZoomModel.get('fillerColor')
  77813. },
  77814. textConfig: {
  77815. position: 'inside'
  77816. }
  77817. });
  77818. sliderGroup.add(filler); // Frame border.
  77819. sliderGroup.add(new Rect$2({
  77820. silent: true,
  77821. subPixelOptimize: true,
  77822. shape: {
  77823. x: 0,
  77824. y: 0,
  77825. width: size[0],
  77826. height: size[1],
  77827. r: borderRadius
  77828. },
  77829. style: {
  77830. // deprecated option
  77831. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  77832. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  77833. fill: 'rgba(0,0,0,0)'
  77834. }
  77835. })); // Left and right handle to resize
  77836. each([0, 1], function (handleIndex) {
  77837. var iconStr = dataZoomModel.get('handleIcon');
  77838. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  77839. // Compatitable with the old icon parsers. Which can use a path string without path://
  77840. iconStr = 'path://' + iconStr;
  77841. if ("development" !== 'production') {
  77842. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  77843. }
  77844. }
  77845. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  77846. path.attr({
  77847. cursor: getCursor(this._orient),
  77848. draggable: true,
  77849. drift: bind(this._onDragMove, this, handleIndex),
  77850. ondragend: bind(this._onDragEnd, this),
  77851. onmouseover: bind(this._showDataInfo, this, true),
  77852. onmouseout: bind(this._showDataInfo, this, false),
  77853. z2: 5
  77854. });
  77855. var bRect = path.getBoundingRect();
  77856. var handleSize = dataZoomModel.get('handleSize');
  77857. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  77858. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  77859. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  77860. path.style.strokeNoScale = true;
  77861. path.rectHover = true;
  77862. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  77863. enableHoverEmphasis(path);
  77864. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  77865. // Compatitable with previous version
  77866. if (handleColor != null) {
  77867. path.style.fill = handleColor;
  77868. }
  77869. sliderGroup.add(handles[handleIndex] = path);
  77870. var textStyleModel = dataZoomModel.getModel('textStyle');
  77871. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  77872. silent: true,
  77873. invisible: true,
  77874. style: createTextStyle(textStyleModel, {
  77875. x: 0,
  77876. y: 0,
  77877. text: '',
  77878. verticalAlign: 'middle',
  77879. align: 'center',
  77880. fill: textStyleModel.getTextColor(),
  77881. font: textStyleModel.getFont()
  77882. }),
  77883. z2: 10
  77884. }));
  77885. }, this); // Handle to move. Only visible when brushSelect is set true.
  77886. var actualMoveZone = filler;
  77887. if (brushSelect) {
  77888. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  77889. var moveHandle_1 = displayables.moveHandle = new Rect({
  77890. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  77891. silent: true,
  77892. shape: {
  77893. r: [0, 0, 2, 2],
  77894. y: size[1] - 0.5,
  77895. height: moveHandleHeight
  77896. }
  77897. });
  77898. var iconSize = moveHandleHeight * 0.8;
  77899. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  77900. moveHandleIcon.silent = true;
  77901. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  77902. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  77903. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  77904. actualMoveZone = displayables.moveZone = new Rect({
  77905. invisible: true,
  77906. shape: {
  77907. y: size[1] - moveZoneExpandSize,
  77908. height: moveHandleHeight + moveZoneExpandSize
  77909. }
  77910. });
  77911. actualMoveZone.on('mouseover', function () {
  77912. api.enterEmphasis(moveHandle_1);
  77913. }).on('mouseout', function () {
  77914. api.leaveEmphasis(moveHandle_1);
  77915. });
  77916. sliderGroup.add(moveHandle_1);
  77917. sliderGroup.add(moveHandleIcon);
  77918. sliderGroup.add(actualMoveZone);
  77919. }
  77920. actualMoveZone.attr({
  77921. draggable: true,
  77922. cursor: getCursor(this._orient),
  77923. drift: bind(this._onDragMove, this, 'all'),
  77924. ondragstart: bind(this._showDataInfo, this, true),
  77925. ondragend: bind(this._onDragEnd, this),
  77926. onmouseover: bind(this._showDataInfo, this, true),
  77927. onmouseout: bind(this._showDataInfo, this, false)
  77928. });
  77929. };
  77930. SliderZoomView.prototype._resetInterval = function () {
  77931. var range = this._range = this.dataZoomModel.getPercentRange();
  77932. var viewExtent = this._getViewExtent();
  77933. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  77934. };
  77935. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  77936. var dataZoomModel = this.dataZoomModel;
  77937. var handleEnds = this._handleEnds;
  77938. var viewExtend = this._getViewExtent();
  77939. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  77940. var percentExtent = [0, 100];
  77941. 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);
  77942. var lastRange = this._range;
  77943. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  77944. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  77945. };
  77946. SliderZoomView.prototype._updateView = function (nonRealtime) {
  77947. var displaybles = this._displayables;
  77948. var handleEnds = this._handleEnds;
  77949. var handleInterval = asc(handleEnds.slice());
  77950. var size = this._size;
  77951. each([0, 1], function (handleIndex) {
  77952. // Handles
  77953. var handle = displaybles.handles[handleIndex];
  77954. var handleHeight = this._handleHeight;
  77955. handle.attr({
  77956. scaleX: handleHeight / 2,
  77957. scaleY: handleHeight / 2,
  77958. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  77959. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  77960. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  77961. y: size[1] / 2 - handleHeight / 2
  77962. });
  77963. }, this); // Filler
  77964. displaybles.filler.setShape({
  77965. x: handleInterval[0],
  77966. y: 0,
  77967. width: handleInterval[1] - handleInterval[0],
  77968. height: size[1]
  77969. });
  77970. var viewExtent = {
  77971. x: handleInterval[0],
  77972. width: handleInterval[1] - handleInterval[0]
  77973. }; // Move handle
  77974. if (displaybles.moveHandle) {
  77975. displaybles.moveHandle.setShape(viewExtent);
  77976. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  77977. displaybles.moveZone.getBoundingRect();
  77978. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  77979. } // update clip path of shadow.
  77980. var dataShadowSegs = displaybles.dataShadowSegs;
  77981. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  77982. for (var i = 0; i < dataShadowSegs.length; i++) {
  77983. var segGroup = dataShadowSegs[i];
  77984. var clipPath = segGroup.getClipPath();
  77985. if (!clipPath) {
  77986. clipPath = new Rect();
  77987. segGroup.setClipPath(clipPath);
  77988. }
  77989. clipPath.setShape({
  77990. x: segIntervals[i],
  77991. y: 0,
  77992. width: segIntervals[i + 1] - segIntervals[i],
  77993. height: size[1]
  77994. });
  77995. }
  77996. this._updateDataInfo(nonRealtime);
  77997. };
  77998. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  77999. var dataZoomModel = this.dataZoomModel;
  78000. var displaybles = this._displayables;
  78001. var handleLabels = displaybles.handleLabels;
  78002. var orient = this._orient;
  78003. var labelTexts = ['', '']; // FIXME
  78004. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  78005. if (dataZoomModel.get('showDetail')) {
  78006. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  78007. if (axisProxy) {
  78008. var axis = axisProxy.getAxisModel().axis;
  78009. var range = this._range;
  78010. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  78011. ? axisProxy.calculateDataWindow({
  78012. start: range[0],
  78013. end: range[1]
  78014. }).valueWindow : axisProxy.getDataValueWindow();
  78015. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  78016. }
  78017. }
  78018. var orderedHandleEnds = asc(this._handleEnds.slice());
  78019. setLabel.call(this, 0);
  78020. setLabel.call(this, 1);
  78021. function setLabel(handleIndex) {
  78022. // Label
  78023. // Text should not transform by barGroup.
  78024. // Ignore handlers transform
  78025. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  78026. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  78027. var offset = this._handleWidth / 2 + LABEL_GAP;
  78028. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  78029. handleLabels[handleIndex].setStyle({
  78030. x: textPoint[0],
  78031. y: textPoint[1],
  78032. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  78033. align: orient === HORIZONTAL ? direction : 'center',
  78034. text: labelTexts[handleIndex]
  78035. });
  78036. }
  78037. };
  78038. SliderZoomView.prototype._formatLabel = function (value, axis) {
  78039. var dataZoomModel = this.dataZoomModel;
  78040. var labelFormatter = dataZoomModel.get('labelFormatter');
  78041. var labelPrecision = dataZoomModel.get('labelPrecision');
  78042. if (labelPrecision == null || labelPrecision === 'auto') {
  78043. labelPrecision = axis.getPixelPrecision();
  78044. }
  78045. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  78046. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  78047. value: Math.round(value)
  78048. }) // param of toFixed should less then 20.
  78049. : value.toFixed(Math.min(labelPrecision, 20));
  78050. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  78051. };
  78052. /**
  78053. * @param showOrHide true: show, false: hide
  78054. */
  78055. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  78056. // Always show when drgging.
  78057. showOrHide = this._dragging || showOrHide;
  78058. var displayables = this._displayables;
  78059. var handleLabels = displayables.handleLabels;
  78060. handleLabels[0].attr('invisible', !showOrHide);
  78061. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  78062. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  78063. };
  78064. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  78065. this._dragging = true; // For mobile device, prevent screen slider on the button.
  78066. stop(event.event); // Transform dx, dy to bar coordination.
  78067. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  78068. var vertex = applyTransform$1([dx, dy], barTransform, true);
  78069. var changed = this._updateInterval(handleIndex, vertex[0]);
  78070. var realtime = this.dataZoomModel.get('realtime');
  78071. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  78072. // which cause bad visual effect when progressive enabled.
  78073. changed && realtime && this._dispatchZoomAction(true);
  78074. };
  78075. SliderZoomView.prototype._onDragEnd = function () {
  78076. this._dragging = false;
  78077. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  78078. // drag end will cause the whole view rerender, which is unnecessary.
  78079. var realtime = this.dataZoomModel.get('realtime');
  78080. !realtime && this._dispatchZoomAction(false);
  78081. };
  78082. SliderZoomView.prototype._onClickPanel = function (e) {
  78083. var size = this._size;
  78084. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  78085. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  78086. return;
  78087. }
  78088. var handleEnds = this._handleEnds;
  78089. var center = (handleEnds[0] + handleEnds[1]) / 2;
  78090. var changed = this._updateInterval('all', localPoint[0] - center);
  78091. this._updateView();
  78092. changed && this._dispatchZoomAction(false);
  78093. };
  78094. SliderZoomView.prototype._onBrushStart = function (e) {
  78095. var x = e.offsetX;
  78096. var y = e.offsetY;
  78097. this._brushStart = new Point(x, y);
  78098. this._brushing = true;
  78099. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  78100. };
  78101. SliderZoomView.prototype._onBrushEnd = function (e) {
  78102. if (!this._brushing) {
  78103. return;
  78104. }
  78105. var brushRect = this._displayables.brushRect;
  78106. this._brushing = false;
  78107. if (!brushRect) {
  78108. return;
  78109. }
  78110. brushRect.attr('ignore', true);
  78111. var brushShape = brushRect.shape;
  78112. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  78113. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  78114. // Will treat it as a click
  78115. return;
  78116. }
  78117. var viewExtend = this._getViewExtent();
  78118. var percentExtent = [0, 100];
  78119. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  78120. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  78121. this._updateView();
  78122. this._dispatchZoomAction(false);
  78123. };
  78124. SliderZoomView.prototype._onBrush = function (e) {
  78125. if (this._brushing) {
  78126. // For mobile device, prevent screen slider on the button.
  78127. stop(e.event);
  78128. this._updateBrushRect(e.offsetX, e.offsetY);
  78129. }
  78130. };
  78131. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  78132. var displayables = this._displayables;
  78133. var dataZoomModel = this.dataZoomModel;
  78134. var brushRect = displayables.brushRect;
  78135. if (!brushRect) {
  78136. brushRect = displayables.brushRect = new Rect$2({
  78137. silent: true,
  78138. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  78139. });
  78140. displayables.sliderGroup.add(brushRect);
  78141. }
  78142. brushRect.attr('ignore', false);
  78143. var brushStart = this._brushStart;
  78144. var sliderGroup = this._displayables.sliderGroup;
  78145. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  78146. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  78147. var size = this._size;
  78148. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  78149. brushRect.setShape({
  78150. x: startPoint[0],
  78151. y: 0,
  78152. width: endPoint[0] - startPoint[0],
  78153. height: size[1]
  78154. });
  78155. };
  78156. /**
  78157. * This action will be throttled.
  78158. */
  78159. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  78160. var range = this._range;
  78161. this.api.dispatchAction({
  78162. type: 'dataZoom',
  78163. from: this.uid,
  78164. dataZoomId: this.dataZoomModel.id,
  78165. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  78166. start: range[0],
  78167. end: range[1]
  78168. });
  78169. };
  78170. SliderZoomView.prototype._findCoordRect = function () {
  78171. // Find the grid corresponding to the first axis referred by dataZoom.
  78172. var rect;
  78173. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  78174. if (!rect && coordSysInfoList.length) {
  78175. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  78176. rect = coordSys.getRect && coordSys.getRect();
  78177. }
  78178. if (!rect) {
  78179. var width = this.api.getWidth();
  78180. var height = this.api.getHeight();
  78181. rect = {
  78182. x: width * 0.2,
  78183. y: height * 0.2,
  78184. width: width * 0.6,
  78185. height: height * 0.6
  78186. };
  78187. }
  78188. return rect;
  78189. };
  78190. SliderZoomView.type = 'dataZoom.slider';
  78191. return SliderZoomView;
  78192. }(DataZoomView);
  78193. function getOtherDim(thisDim) {
  78194. // FIXME
  78195. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  78196. var map = {
  78197. x: 'y',
  78198. y: 'x',
  78199. radius: 'angle',
  78200. angle: 'radius'
  78201. };
  78202. return map[thisDim];
  78203. }
  78204. function getCursor(orient) {
  78205. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  78206. }
  78207. function install$L(registers) {
  78208. registers.registerComponentModel(SliderZoomModel);
  78209. registers.registerComponentView(SliderZoomView);
  78210. installCommon(registers);
  78211. }
  78212. function install$M(registers) {
  78213. use(install$K);
  78214. use(install$L); // Do not install './dataZoomSelect',
  78215. // since it only work for toolbox dataZoom.
  78216. }
  78217. var visualDefault = {
  78218. /**
  78219. * @public
  78220. */
  78221. get: function (visualType, key, isCategory) {
  78222. var value = clone((defaultOption$1[visualType] || {})[key]);
  78223. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  78224. }
  78225. };
  78226. var defaultOption$1 = {
  78227. color: {
  78228. active: ['#006edd', '#e0ffff'],
  78229. inactive: ['rgba(0,0,0,0)']
  78230. },
  78231. colorHue: {
  78232. active: [0, 360],
  78233. inactive: [0, 0]
  78234. },
  78235. colorSaturation: {
  78236. active: [0.3, 1],
  78237. inactive: [0, 0]
  78238. },
  78239. colorLightness: {
  78240. active: [0.9, 0.5],
  78241. inactive: [0, 0]
  78242. },
  78243. colorAlpha: {
  78244. active: [0.3, 1],
  78245. inactive: [0, 0]
  78246. },
  78247. opacity: {
  78248. active: [0.3, 1],
  78249. inactive: [0, 0]
  78250. },
  78251. symbol: {
  78252. active: ['circle', 'roundRect', 'diamond'],
  78253. inactive: ['none']
  78254. },
  78255. symbolSize: {
  78256. active: [10, 50],
  78257. inactive: [0, 0]
  78258. }
  78259. };
  78260. var mapVisual$1 = VisualMapping.mapVisual;
  78261. var eachVisual = VisualMapping.eachVisual;
  78262. var isArray$1 = isArray;
  78263. var each$d = each;
  78264. var asc$2 = asc;
  78265. var linearMap$1 = linearMap;
  78266. var VisualMapModel =
  78267. /** @class */
  78268. function (_super) {
  78269. __extends(VisualMapModel, _super);
  78270. function VisualMapModel() {
  78271. var _this = _super !== null && _super.apply(this, arguments) || this;
  78272. _this.type = VisualMapModel.type;
  78273. _this.stateList = ['inRange', 'outOfRange'];
  78274. _this.replacableOptionKeys = ['inRange', 'outOfRange', 'target', 'controller', 'color'];
  78275. _this.layoutMode = {
  78276. type: 'box',
  78277. ignoreSize: true
  78278. };
  78279. /**
  78280. * [lowerBound, upperBound]
  78281. */
  78282. _this.dataBound = [-Infinity, Infinity];
  78283. _this.targetVisuals = {};
  78284. _this.controllerVisuals = {};
  78285. return _this;
  78286. }
  78287. VisualMapModel.prototype.init = function (option, parentModel, ecModel) {
  78288. this.mergeDefaultAndTheme(option, ecModel);
  78289. };
  78290. /**
  78291. * @protected
  78292. */
  78293. VisualMapModel.prototype.optionUpdated = function (newOption, isInit) {
  78294. var thisOption = this.option;
  78295. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  78296. this.textStyleModel = this.getModel('textStyle');
  78297. this.resetItemSize();
  78298. this.completeVisualOption();
  78299. };
  78300. /**
  78301. * @protected
  78302. */
  78303. VisualMapModel.prototype.resetVisual = function (supplementVisualOption) {
  78304. var stateList = this.stateList;
  78305. supplementVisualOption = bind(supplementVisualOption, this);
  78306. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  78307. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  78308. };
  78309. /**
  78310. * @public
  78311. */
  78312. VisualMapModel.prototype.getItemSymbol = function () {
  78313. return null;
  78314. };
  78315. /**
  78316. * @protected
  78317. * @return {Array.<number>} An array of series indices.
  78318. */
  78319. VisualMapModel.prototype.getTargetSeriesIndices = function () {
  78320. var optionSeriesIndex = this.option.seriesIndex;
  78321. var seriesIndices = [];
  78322. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  78323. this.ecModel.eachSeries(function (seriesModel, index) {
  78324. seriesIndices.push(index);
  78325. });
  78326. } else {
  78327. seriesIndices = normalizeToArray(optionSeriesIndex);
  78328. }
  78329. return seriesIndices;
  78330. };
  78331. /**
  78332. * @public
  78333. */
  78334. VisualMapModel.prototype.eachTargetSeries = function (callback, context) {
  78335. each(this.getTargetSeriesIndices(), function (seriesIndex) {
  78336. var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex);
  78337. if (seriesModel) {
  78338. callback.call(context, seriesModel);
  78339. }
  78340. }, this);
  78341. };
  78342. /**
  78343. * @pubilc
  78344. */
  78345. VisualMapModel.prototype.isTargetSeries = function (seriesModel) {
  78346. var is = false;
  78347. this.eachTargetSeries(function (model) {
  78348. model === seriesModel && (is = true);
  78349. });
  78350. return is;
  78351. };
  78352. /**
  78353. * @example
  78354. * this.formatValueText(someVal); // format single numeric value to text.
  78355. * this.formatValueText(someVal, true); // format single category value to text.
  78356. * this.formatValueText([min, max]); // format numeric min-max to text.
  78357. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  78358. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  78359. *
  78360. * @param value Real value, or this.dataBound[0 or 1].
  78361. * @param isCategory Only available when value is number.
  78362. * @param edgeSymbols Open-close symbol when value is interval.
  78363. * @protected
  78364. */
  78365. VisualMapModel.prototype.formatValueText = function (value, isCategory, edgeSymbols) {
  78366. var option = this.option;
  78367. var precision = option.precision;
  78368. var dataBound = this.dataBound;
  78369. var formatter = option.formatter;
  78370. var isMinMax;
  78371. edgeSymbols = edgeSymbols || ['<', '>'];
  78372. if (isArray(value)) {
  78373. value = value.slice();
  78374. isMinMax = true;
  78375. }
  78376. var textValue = isCategory ? value // Value is string when isCategory
  78377. : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  78378. if (isString(formatter)) {
  78379. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  78380. } else if (isFunction(formatter)) {
  78381. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  78382. }
  78383. if (isMinMax) {
  78384. if (value[0] === dataBound[0]) {
  78385. return edgeSymbols[0] + ' ' + textValue[1];
  78386. } else if (value[1] === dataBound[1]) {
  78387. return edgeSymbols[1] + ' ' + textValue[0];
  78388. } else {
  78389. return textValue[0] + ' - ' + textValue[1];
  78390. }
  78391. } else {
  78392. // Format single value (includes category case).
  78393. return textValue;
  78394. }
  78395. function toFixed(val) {
  78396. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  78397. }
  78398. };
  78399. /**
  78400. * @protected
  78401. */
  78402. VisualMapModel.prototype.resetExtent = function () {
  78403. var thisOption = this.option; // Can not calculate data extent by data here.
  78404. // Because series and data may be modified in processing stage.
  78405. // So we do not support the feature "auto min/max".
  78406. var extent = asc$2([thisOption.min, thisOption.max]);
  78407. this._dataExtent = extent;
  78408. };
  78409. /**
  78410. * PENDING:
  78411. * delete this method if no outer usage.
  78412. *
  78413. * Return Concrete dimension. If null/undefined is returned, no dimension is used.
  78414. */
  78415. // getDataDimension(data: SeriesData) {
  78416. // const optDim = this.option.dimension;
  78417. // if (optDim != null) {
  78418. // return data.getDimension(optDim);
  78419. // }
  78420. // const dimNames = data.dimensions;
  78421. // for (let i = dimNames.length - 1; i >= 0; i--) {
  78422. // const dimName = dimNames[i];
  78423. // const dimInfo = data.getDimensionInfo(dimName);
  78424. // if (!dimInfo.isCalculationCoord) {
  78425. // return dimName;
  78426. // }
  78427. // }
  78428. // }
  78429. VisualMapModel.prototype.getDataDimensionIndex = function (data) {
  78430. var optDim = this.option.dimension;
  78431. if (optDim != null) {
  78432. return data.getDimensionIndex(optDim);
  78433. }
  78434. var dimNames = data.dimensions;
  78435. for (var i = dimNames.length - 1; i >= 0; i--) {
  78436. var dimName = dimNames[i];
  78437. var dimInfo = data.getDimensionInfo(dimName);
  78438. if (!dimInfo.isCalculationCoord) {
  78439. return dimInfo.storeDimIndex;
  78440. }
  78441. }
  78442. };
  78443. VisualMapModel.prototype.getExtent = function () {
  78444. return this._dataExtent.slice();
  78445. };
  78446. VisualMapModel.prototype.completeVisualOption = function () {
  78447. var ecModel = this.ecModel;
  78448. var thisOption = this.option;
  78449. var base = {
  78450. inRange: thisOption.inRange,
  78451. outOfRange: thisOption.outOfRange
  78452. };
  78453. var target = thisOption.target || (thisOption.target = {});
  78454. var controller = thisOption.controller || (thisOption.controller = {});
  78455. merge(target, base); // Do not override
  78456. merge(controller, base); // Do not override
  78457. var isCategory = this.isCategory();
  78458. completeSingle.call(this, target);
  78459. completeSingle.call(this, controller);
  78460. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  78461. completeController.call(this, controller);
  78462. function completeSingle(base) {
  78463. // Compatible with ec2 dataRange.color.
  78464. // The mapping order of dataRange.color is: [high value, ..., low value]
  78465. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  78466. // Notice: ec2 has no inverse.
  78467. if (isArray$1(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  78468. // So adding color only when no inRange defined.
  78469. && !base.inRange) {
  78470. base.inRange = {
  78471. color: thisOption.color.slice().reverse()
  78472. };
  78473. } // Compatible with previous logic, always give a default color, otherwise
  78474. // simple config with no inRange and outOfRange will not work.
  78475. // Originally we use visualMap.color as the default color, but setOption at
  78476. // the second time the default color will be erased. So we change to use
  78477. // constant DEFAULT_COLOR.
  78478. // If user do not want the default color, set inRange: {color: null}.
  78479. base.inRange = base.inRange || {
  78480. color: ecModel.get('gradientColor')
  78481. };
  78482. }
  78483. function completeInactive(base, stateExist, stateAbsent) {
  78484. var optExist = base[stateExist];
  78485. var optAbsent = base[stateAbsent];
  78486. if (optExist && !optAbsent) {
  78487. optAbsent = base[stateAbsent] = {};
  78488. each$d(optExist, function (visualData, visualType) {
  78489. if (!VisualMapping.isValidType(visualType)) {
  78490. return;
  78491. }
  78492. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  78493. if (defa != null) {
  78494. optAbsent[visualType] = defa; // Compatibable with ec2:
  78495. // Only inactive color to rgba(0,0,0,0) can not
  78496. // make label transparent, so use opacity also.
  78497. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  78498. optAbsent.opacity = [0, 0];
  78499. }
  78500. }
  78501. });
  78502. }
  78503. }
  78504. function completeController(controller) {
  78505. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  78506. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  78507. var inactiveColor = this.get('inactiveColor');
  78508. var itemSymbol = this.getItemSymbol();
  78509. var defaultSymbol = itemSymbol || 'roundRect';
  78510. each$d(this.stateList, function (state) {
  78511. var itemSize = this.itemSize;
  78512. var visuals = controller[state]; // Set inactive color for controller if no other color
  78513. // attr (like colorAlpha) specified.
  78514. if (!visuals) {
  78515. visuals = controller[state] = {
  78516. color: isCategory ? inactiveColor : [inactiveColor]
  78517. };
  78518. } // Consistent symbol and symbolSize if not specified.
  78519. if (visuals.symbol == null) {
  78520. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? defaultSymbol : [defaultSymbol]);
  78521. }
  78522. if (visuals.symbolSize == null) {
  78523. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  78524. } // Filter none
  78525. visuals.symbol = mapVisual$1(visuals.symbol, function (symbol) {
  78526. return symbol === 'none' ? defaultSymbol : symbol;
  78527. }); // Normalize symbolSize
  78528. var symbolSize = visuals.symbolSize;
  78529. if (symbolSize != null) {
  78530. var max_1 = -Infinity; // symbolSize can be object when categories defined.
  78531. eachVisual(symbolSize, function (value) {
  78532. value > max_1 && (max_1 = value);
  78533. });
  78534. visuals.symbolSize = mapVisual$1(symbolSize, function (value) {
  78535. return linearMap$1(value, [0, max_1], [0, itemSize[0]], true);
  78536. });
  78537. }
  78538. }, this);
  78539. }
  78540. };
  78541. VisualMapModel.prototype.resetItemSize = function () {
  78542. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  78543. };
  78544. VisualMapModel.prototype.isCategory = function () {
  78545. return !!this.option.categories;
  78546. };
  78547. /**
  78548. * @public
  78549. * @abstract
  78550. */
  78551. VisualMapModel.prototype.setSelected = function (selected) {};
  78552. VisualMapModel.prototype.getSelected = function () {
  78553. return null;
  78554. };
  78555. /**
  78556. * @public
  78557. * @abstract
  78558. */
  78559. VisualMapModel.prototype.getValueState = function (value) {
  78560. return null;
  78561. };
  78562. /**
  78563. * FIXME
  78564. * Do not publish to thirt-part-dev temporarily
  78565. * util the interface is stable. (Should it return
  78566. * a function but not visual meta?)
  78567. *
  78568. * @pubilc
  78569. * @abstract
  78570. * @param getColorVisual
  78571. * params: value, valueState
  78572. * return: color
  78573. * @return {Object} visualMeta
  78574. * should includes {stops, outerColors}
  78575. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  78576. */
  78577. VisualMapModel.prototype.getVisualMeta = function (getColorVisual) {
  78578. return null;
  78579. };
  78580. VisualMapModel.type = 'visualMap';
  78581. VisualMapModel.dependencies = ['series'];
  78582. VisualMapModel.defaultOption = {
  78583. show: true,
  78584. // zlevel: 0,
  78585. z: 4,
  78586. seriesIndex: 'all',
  78587. min: 0,
  78588. max: 200,
  78589. left: 0,
  78590. right: null,
  78591. top: null,
  78592. bottom: 0,
  78593. itemWidth: null,
  78594. itemHeight: null,
  78595. inverse: false,
  78596. orient: 'vertical',
  78597. backgroundColor: 'rgba(0,0,0,0)',
  78598. borderColor: '#ccc',
  78599. contentColor: '#5793f3',
  78600. inactiveColor: '#aaa',
  78601. borderWidth: 0,
  78602. padding: 5,
  78603. // 接受数组分别设定上右下左边距,同css
  78604. textGap: 10,
  78605. precision: 0,
  78606. textStyle: {
  78607. color: '#333' // 值域文字颜色
  78608. }
  78609. };
  78610. return VisualMapModel;
  78611. }(ComponentModel);
  78612. var DEFAULT_BAR_BOUND = [20, 140];
  78613. var ContinuousModel =
  78614. /** @class */
  78615. function (_super) {
  78616. __extends(ContinuousModel, _super);
  78617. function ContinuousModel() {
  78618. var _this = _super !== null && _super.apply(this, arguments) || this;
  78619. _this.type = ContinuousModel.type;
  78620. return _this;
  78621. }
  78622. /**
  78623. * @override
  78624. */
  78625. ContinuousModel.prototype.optionUpdated = function (newOption, isInit) {
  78626. _super.prototype.optionUpdated.apply(this, arguments);
  78627. this.resetExtent();
  78628. this.resetVisual(function (mappingOption) {
  78629. mappingOption.mappingMethod = 'linear';
  78630. mappingOption.dataExtent = this.getExtent();
  78631. });
  78632. this._resetRange();
  78633. };
  78634. /**
  78635. * @protected
  78636. * @override
  78637. */
  78638. ContinuousModel.prototype.resetItemSize = function () {
  78639. _super.prototype.resetItemSize.apply(this, arguments);
  78640. var itemSize = this.itemSize;
  78641. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  78642. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  78643. };
  78644. /**
  78645. * @private
  78646. */
  78647. ContinuousModel.prototype._resetRange = function () {
  78648. var dataExtent = this.getExtent();
  78649. var range = this.option.range;
  78650. if (!range || range.auto) {
  78651. // `range` should always be array (so we don't use other
  78652. // value like 'auto') for user-friend. (consider getOption).
  78653. dataExtent.auto = 1;
  78654. this.option.range = dataExtent;
  78655. } else if (isArray(range)) {
  78656. if (range[0] > range[1]) {
  78657. range.reverse();
  78658. }
  78659. range[0] = Math.max(range[0], dataExtent[0]);
  78660. range[1] = Math.min(range[1], dataExtent[1]);
  78661. }
  78662. };
  78663. /**
  78664. * @protected
  78665. * @override
  78666. */
  78667. ContinuousModel.prototype.completeVisualOption = function () {
  78668. _super.prototype.completeVisualOption.apply(this, arguments);
  78669. each(this.stateList, function (state) {
  78670. var symbolSize = this.option.controller[state].symbolSize;
  78671. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  78672. symbolSize[0] = symbolSize[1] / 3; // For good looking.
  78673. }
  78674. }, this);
  78675. };
  78676. /**
  78677. * @override
  78678. */
  78679. ContinuousModel.prototype.setSelected = function (selected) {
  78680. this.option.range = selected.slice();
  78681. this._resetRange();
  78682. };
  78683. /**
  78684. * @public
  78685. */
  78686. ContinuousModel.prototype.getSelected = function () {
  78687. var dataExtent = this.getExtent();
  78688. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  78689. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  78690. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  78691. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  78692. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  78693. return dataInterval;
  78694. };
  78695. /**
  78696. * @override
  78697. */
  78698. ContinuousModel.prototype.getValueState = function (value) {
  78699. var range = this.option.range;
  78700. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  78701. // range[1] is processed likewise.
  78702. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  78703. };
  78704. ContinuousModel.prototype.findTargetDataIndices = function (range) {
  78705. var result = [];
  78706. this.eachTargetSeries(function (seriesModel) {
  78707. var dataIndices = [];
  78708. var data = seriesModel.getData();
  78709. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  78710. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  78711. }, this);
  78712. result.push({
  78713. seriesId: seriesModel.id,
  78714. dataIndex: dataIndices
  78715. });
  78716. }, this);
  78717. return result;
  78718. };
  78719. /**
  78720. * @implement
  78721. */
  78722. ContinuousModel.prototype.getVisualMeta = function (getColorVisual) {
  78723. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  78724. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  78725. var stops = [];
  78726. function setStop(value, valueState) {
  78727. stops.push({
  78728. value: value,
  78729. color: getColorVisual(value, valueState)
  78730. });
  78731. } // Format to: outOfRange -- inRange -- outOfRange.
  78732. var iIdx = 0;
  78733. var oIdx = 0;
  78734. var iLen = iVals.length;
  78735. var oLen = oVals.length;
  78736. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  78737. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  78738. if (oVals[oIdx] < iVals[iIdx]) {
  78739. setStop(oVals[oIdx], 'outOfRange');
  78740. }
  78741. }
  78742. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  78743. // If range is full, value beyond min, max will be clamped.
  78744. // make a singularity
  78745. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  78746. setStop(iVals[iIdx], 'inRange');
  78747. }
  78748. for (var first = 1; oIdx < oLen; oIdx++) {
  78749. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  78750. // make a singularity
  78751. if (first) {
  78752. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  78753. first = 0;
  78754. }
  78755. setStop(oVals[oIdx], 'outOfRange');
  78756. }
  78757. }
  78758. var stopsLen = stops.length;
  78759. return {
  78760. stops: stops,
  78761. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  78762. };
  78763. };
  78764. ContinuousModel.type = 'visualMap.continuous';
  78765. ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  78766. align: 'auto',
  78767. calculable: false,
  78768. hoverLink: true,
  78769. realtime: true,
  78770. 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',
  78771. handleSize: '120%',
  78772. handleStyle: {
  78773. borderColor: '#fff',
  78774. borderWidth: 1
  78775. },
  78776. indicatorIcon: 'circle',
  78777. indicatorSize: '50%',
  78778. indicatorStyle: {
  78779. borderColor: '#fff',
  78780. borderWidth: 2,
  78781. shadowBlur: 2,
  78782. shadowOffsetX: 1,
  78783. shadowOffsetY: 1,
  78784. shadowColor: 'rgba(0,0,0,0.2)'
  78785. } // emphasis: {
  78786. // handleStyle: {
  78787. // shadowBlur: 3,
  78788. // shadowOffsetX: 1,
  78789. // shadowOffsetY: 1,
  78790. // shadowColor: 'rgba(0,0,0,0.2)'
  78791. // }
  78792. // }
  78793. });
  78794. return ContinuousModel;
  78795. }(VisualMapModel);
  78796. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  78797. if (dataExtent[0] === dataExtent[1]) {
  78798. return dataExtent.slice();
  78799. } // When using colorHue mapping, it is not linear color any more.
  78800. // Moreover, canvas gradient seems not to be accurate linear.
  78801. // FIXME
  78802. // Should be arbitrary value 100? or based on pixel size?
  78803. var count = 200;
  78804. var step = (dataExtent[1] - dataExtent[0]) / count;
  78805. var value = dataExtent[0];
  78806. var stopValues = [];
  78807. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  78808. stopValues.push(value);
  78809. value += step;
  78810. }
  78811. stopValues.push(dataExtent[1]);
  78812. return stopValues;
  78813. }
  78814. var VisualMapView =
  78815. /** @class */
  78816. function (_super) {
  78817. __extends(VisualMapView, _super);
  78818. function VisualMapView() {
  78819. var _this = _super !== null && _super.apply(this, arguments) || this;
  78820. _this.type = VisualMapView.type;
  78821. _this.autoPositionValues = {
  78822. left: 1,
  78823. right: 1,
  78824. top: 1,
  78825. bottom: 1
  78826. };
  78827. return _this;
  78828. }
  78829. VisualMapView.prototype.init = function (ecModel, api) {
  78830. this.ecModel = ecModel;
  78831. this.api = api;
  78832. };
  78833. /**
  78834. * @protected
  78835. */
  78836. VisualMapView.prototype.render = function (visualMapModel, ecModel, api, payload // TODO: TYPE
  78837. ) {
  78838. this.visualMapModel = visualMapModel;
  78839. if (visualMapModel.get('show') === false) {
  78840. this.group.removeAll();
  78841. return;
  78842. }
  78843. this.doRender(visualMapModel, ecModel, api, payload);
  78844. };
  78845. /**
  78846. * @protected
  78847. */
  78848. VisualMapView.prototype.renderBackground = function (group) {
  78849. var visualMapModel = this.visualMapModel;
  78850. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  78851. var rect = group.getBoundingRect();
  78852. group.add(new Rect({
  78853. z2: -1,
  78854. silent: true,
  78855. shape: {
  78856. x: rect.x - padding[3],
  78857. y: rect.y - padding[0],
  78858. width: rect.width + padding[3] + padding[1],
  78859. height: rect.height + padding[0] + padding[2]
  78860. },
  78861. style: {
  78862. fill: visualMapModel.get('backgroundColor'),
  78863. stroke: visualMapModel.get('borderColor'),
  78864. lineWidth: visualMapModel.get('borderWidth')
  78865. }
  78866. }));
  78867. };
  78868. /**
  78869. * @protected
  78870. * @param targetValue can be Infinity or -Infinity
  78871. * @param visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  78872. * @param opts
  78873. * @param opts.forceState Specify state, instead of using getValueState method.
  78874. * @param opts.convertOpacityToAlpha For color gradient in controller widget.
  78875. * @return {*} Visual value.
  78876. */
  78877. VisualMapView.prototype.getControllerVisual = function (targetValue, visualCluster, opts) {
  78878. opts = opts || {};
  78879. var forceState = opts.forceState;
  78880. var visualMapModel = this.visualMapModel;
  78881. var visualObj = {}; // Default values.
  78882. if (visualCluster === 'color') {
  78883. var defaultColor = visualMapModel.get('contentColor');
  78884. visualObj.color = defaultColor;
  78885. }
  78886. function getter(key) {
  78887. return visualObj[key];
  78888. }
  78889. function setter(key, value) {
  78890. visualObj[key] = value;
  78891. }
  78892. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  78893. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  78894. each(visualTypes, function (type) {
  78895. var visualMapping = mappings[type];
  78896. if (opts.convertOpacityToAlpha && type === 'opacity') {
  78897. type = 'colorAlpha';
  78898. visualMapping = mappings.__alphaForOpacity;
  78899. }
  78900. if (VisualMapping.dependsOn(type, visualCluster)) {
  78901. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  78902. }
  78903. });
  78904. return visualObj[visualCluster];
  78905. };
  78906. VisualMapView.prototype.positionGroup = function (group) {
  78907. var model = this.visualMapModel;
  78908. var api = this.api;
  78909. positionElement(group, model.getBoxLayoutParams(), {
  78910. width: api.getWidth(),
  78911. height: api.getHeight()
  78912. });
  78913. };
  78914. VisualMapView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {};
  78915. VisualMapView.type = 'visualMap';
  78916. return VisualMapView;
  78917. }(ComponentView);
  78918. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  78919. /**
  78920. * @param visualMapModel
  78921. * @param api
  78922. * @param itemSize always [short, long]
  78923. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  78924. */
  78925. function getItemAlign(visualMapModel, api, itemSize) {
  78926. var modelOption = visualMapModel.option;
  78927. var itemAlign = modelOption.align;
  78928. if (itemAlign != null && itemAlign !== 'auto') {
  78929. return itemAlign;
  78930. } // Auto decision align.
  78931. var ecSize = {
  78932. width: api.getWidth(),
  78933. height: api.getHeight()
  78934. };
  78935. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  78936. var reals = paramsSet[realIndex];
  78937. var fakeValue = [0, null, 10];
  78938. var layoutInput = {};
  78939. for (var i = 0; i < 3; i++) {
  78940. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  78941. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  78942. }
  78943. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  78944. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  78945. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  78946. }
  78947. /**
  78948. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  78949. * dataIndexInside means filtered index.
  78950. */
  78951. // TODO: TYPE more specified payload types.
  78952. function makeHighDownBatch(batch, visualMapModel) {
  78953. each(batch || [], function (batchItem) {
  78954. if (batchItem.dataIndex != null) {
  78955. batchItem.dataIndexInside = batchItem.dataIndex;
  78956. batchItem.dataIndex = null;
  78957. }
  78958. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  78959. });
  78960. return batch;
  78961. }
  78962. var linearMap$2 = linearMap;
  78963. var each$e = each;
  78964. var mathMin$a = Math.min;
  78965. var mathMax$a = Math.max; // Arbitrary value
  78966. var HOVER_LINK_SIZE = 12;
  78967. var HOVER_LINK_OUT = 6; // Notice:
  78968. // Any "interval" should be by the order of [low, high].
  78969. // "handle0" (handleIndex === 0) maps to
  78970. // low data value: this._dataInterval[0] and has low coord.
  78971. // "handle1" (handleIndex === 1) maps to
  78972. // high data value: this._dataInterval[1] and has high coord.
  78973. // The logic of transform is implemented in this._createBarGroup.
  78974. var ContinuousView =
  78975. /** @class */
  78976. function (_super) {
  78977. __extends(ContinuousView, _super);
  78978. function ContinuousView() {
  78979. var _this = _super !== null && _super.apply(this, arguments) || this;
  78980. _this.type = ContinuousView.type;
  78981. _this._shapes = {};
  78982. _this._dataInterval = [];
  78983. _this._handleEnds = [];
  78984. _this._hoverLinkDataIndices = [];
  78985. return _this;
  78986. }
  78987. ContinuousView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {
  78988. this._api = api;
  78989. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  78990. this._buildView();
  78991. }
  78992. };
  78993. ContinuousView.prototype._buildView = function () {
  78994. this.group.removeAll();
  78995. var visualMapModel = this.visualMapModel;
  78996. var thisGroup = this.group;
  78997. this._orient = visualMapModel.get('orient');
  78998. this._useHandle = visualMapModel.get('calculable');
  78999. this._resetInterval();
  79000. this._renderBar(thisGroup);
  79001. var dataRangeText = visualMapModel.get('text');
  79002. this._renderEndsText(thisGroup, dataRangeText, 0);
  79003. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  79004. this._updateView(true); // After updating view, inner shapes is built completely,
  79005. // and then background can be rendered.
  79006. this.renderBackground(thisGroup); // Real update view
  79007. this._updateView();
  79008. this._enableHoverLinkToSeries();
  79009. this._enableHoverLinkFromSeries();
  79010. this.positionGroup(thisGroup);
  79011. };
  79012. ContinuousView.prototype._renderEndsText = function (group, dataRangeText, endsIndex) {
  79013. if (!dataRangeText) {
  79014. return;
  79015. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  79016. var text = dataRangeText[1 - endsIndex];
  79017. text = text != null ? text + '' : '';
  79018. var visualMapModel = this.visualMapModel;
  79019. var textGap = visualMapModel.get('textGap');
  79020. var itemSize = visualMapModel.itemSize;
  79021. var barGroup = this._shapes.mainGroup;
  79022. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  79023. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  79024. var orient = this._orient;
  79025. var textStyleModel = this.visualMapModel.textStyleModel;
  79026. this.group.add(new ZRText({
  79027. style: createTextStyle(textStyleModel, {
  79028. x: position[0],
  79029. y: position[1],
  79030. verticalAlign: orient === 'horizontal' ? 'middle' : align,
  79031. align: orient === 'horizontal' ? align : 'center',
  79032. text: text
  79033. })
  79034. }));
  79035. };
  79036. ContinuousView.prototype._renderBar = function (targetGroup) {
  79037. var visualMapModel = this.visualMapModel;
  79038. var shapes = this._shapes;
  79039. var itemSize = visualMapModel.itemSize;
  79040. var orient = this._orient;
  79041. var useHandle = this._useHandle;
  79042. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  79043. var mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
  79044. var gradientBarGroup = new Group();
  79045. mainGroup.add(gradientBarGroup); // Bar
  79046. gradientBarGroup.add(shapes.outOfRange = createPolygon());
  79047. 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.
  79048. gradientBarGroup.setClipPath(new Rect({
  79049. shape: {
  79050. x: 0,
  79051. y: 0,
  79052. width: itemSize[0],
  79053. height: itemSize[1],
  79054. r: 3
  79055. }
  79056. }));
  79057. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  79058. var textSize = mathMax$a(textRect.width, textRect.height); // Handle
  79059. if (useHandle) {
  79060. shapes.handleThumbs = [];
  79061. shapes.handleLabels = [];
  79062. shapes.handleLabelPoints = [];
  79063. this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
  79064. this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
  79065. }
  79066. this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
  79067. targetGroup.add(mainGroup);
  79068. };
  79069. ContinuousView.prototype._createHandle = function (visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) {
  79070. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  79071. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  79072. var handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
  79073. var handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, true);
  79074. var cursor = getCursor$1(this._orient);
  79075. handleThumb.attr({
  79076. cursor: cursor,
  79077. draggable: true,
  79078. drift: onDrift,
  79079. ondragend: onDragEnd,
  79080. onmousemove: function (e) {
  79081. stop(e.event);
  79082. }
  79083. });
  79084. handleThumb.x = itemSize[0] / 2;
  79085. handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
  79086. handleThumb.setStyle({
  79087. strokeNoScale: true,
  79088. strokeFirst: true
  79089. });
  79090. handleThumb.style.lineWidth *= 2;
  79091. handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  79092. setAsHighDownDispatcher(handleThumb, true);
  79093. mainGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  79094. // transform (orient/inverse). So label is built separately but not
  79095. // use zrender/graphic/helper/RectText, and is located based on view
  79096. // group (according to handleLabelPoint) but not barGroup.
  79097. var textStyleModel = this.visualMapModel.textStyleModel;
  79098. var handleLabel = new ZRText({
  79099. cursor: cursor,
  79100. draggable: true,
  79101. drift: onDrift,
  79102. onmousemove: function (e) {
  79103. // For mobile device, prevent screen slider on the button.
  79104. stop(e.event);
  79105. },
  79106. ondragend: onDragEnd,
  79107. style: createTextStyle(textStyleModel, {
  79108. x: 0,
  79109. y: 0,
  79110. text: ''
  79111. })
  79112. });
  79113. handleLabel.ensureState('blur').style = {
  79114. opacity: 0.1
  79115. };
  79116. handleLabel.stateTransition = {
  79117. duration: 200
  79118. };
  79119. this.group.add(handleLabel);
  79120. var handleLabelPoint = [handleSize, 0];
  79121. var shapes = this._shapes;
  79122. shapes.handleThumbs[handleIndex] = handleThumb;
  79123. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  79124. shapes.handleLabels[handleIndex] = handleLabel;
  79125. };
  79126. ContinuousView.prototype._createIndicator = function (visualMapModel, mainGroup, itemSize, textSize, orient) {
  79127. var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
  79128. var indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, true);
  79129. indicator.attr({
  79130. cursor: 'move',
  79131. invisible: true,
  79132. silent: true,
  79133. x: itemSize[0] / 2
  79134. });
  79135. var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
  79136. if (indicator instanceof ZRImage) {
  79137. var pathStyle = indicator.style;
  79138. indicator.useStyle(extend({
  79139. // TODO other properties like x, y ?
  79140. image: pathStyle.image,
  79141. x: pathStyle.x,
  79142. y: pathStyle.y,
  79143. width: pathStyle.width,
  79144. height: pathStyle.height
  79145. }, indicatorStyle));
  79146. } else {
  79147. indicator.useStyle(indicatorStyle);
  79148. }
  79149. mainGroup.add(indicator);
  79150. var textStyleModel = this.visualMapModel.textStyleModel;
  79151. var indicatorLabel = new ZRText({
  79152. silent: true,
  79153. invisible: true,
  79154. style: createTextStyle(textStyleModel, {
  79155. x: 0,
  79156. y: 0,
  79157. text: ''
  79158. })
  79159. });
  79160. this.group.add(indicatorLabel);
  79161. var indicatorLabelPoint = [(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2, 0];
  79162. var shapes = this._shapes;
  79163. shapes.indicator = indicator;
  79164. shapes.indicatorLabel = indicatorLabel;
  79165. shapes.indicatorLabelPoint = indicatorLabelPoint;
  79166. this._firstShowIndicator = true;
  79167. };
  79168. ContinuousView.prototype._dragHandle = function (handleIndex, isEnd, // dx is event from ondragend if isEnd is true. It's not used
  79169. dx, dy) {
  79170. if (!this._useHandle) {
  79171. return;
  79172. }
  79173. this._dragging = !isEnd;
  79174. if (!isEnd) {
  79175. // Transform dx, dy to bar coordination.
  79176. var vertex = this._applyTransform([dx, dy], this._shapes.mainGroup, true);
  79177. this._updateInterval(handleIndex, vertex[1]);
  79178. this._hideIndicator(); // Considering realtime, update view should be executed
  79179. // before dispatch action.
  79180. this._updateView();
  79181. } // dragEnd do not dispatch action when realtime.
  79182. if (isEnd === !this.visualMapModel.get('realtime')) {
  79183. // jshint ignore:line
  79184. this.api.dispatchAction({
  79185. type: 'selectDataRange',
  79186. from: this.uid,
  79187. visualMapId: this.visualMapModel.id,
  79188. selected: this._dataInterval.slice()
  79189. });
  79190. }
  79191. if (isEnd) {
  79192. !this._hovering && this._clearHoverLinkToSeries();
  79193. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  79194. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  79195. }
  79196. };
  79197. ContinuousView.prototype._resetInterval = function () {
  79198. var visualMapModel = this.visualMapModel;
  79199. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  79200. var dataExtent = visualMapModel.getExtent();
  79201. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79202. this._handleEnds = [linearMap$2(dataInterval[0], dataExtent, sizeExtent, true), linearMap$2(dataInterval[1], dataExtent, sizeExtent, true)];
  79203. };
  79204. /**
  79205. * @private
  79206. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  79207. * @param {number} dx
  79208. * @param {number} dy
  79209. */
  79210. ContinuousView.prototype._updateInterval = function (handleIndex, delta) {
  79211. delta = delta || 0;
  79212. var visualMapModel = this.visualMapModel;
  79213. var handleEnds = this._handleEnds;
  79214. var sizeExtent = [0, visualMapModel.itemSize[1]];
  79215. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbidden
  79216. 0);
  79217. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  79218. this._dataInterval = [linearMap$2(handleEnds[0], sizeExtent, dataExtent, true), linearMap$2(handleEnds[1], sizeExtent, dataExtent, true)];
  79219. };
  79220. ContinuousView.prototype._updateView = function (forSketch) {
  79221. var visualMapModel = this.visualMapModel;
  79222. var dataExtent = visualMapModel.getExtent();
  79223. var shapes = this._shapes;
  79224. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  79225. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  79226. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  79227. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  79228. shapes.inRange.setStyle({
  79229. fill: visualInRange.barColor // opacity: visualInRange.opacity
  79230. }).setShape('points', visualInRange.barPoints);
  79231. shapes.outOfRange.setStyle({
  79232. fill: visualOutOfRange.barColor // opacity: visualOutOfRange.opacity
  79233. }).setShape('points', visualOutOfRange.barPoints);
  79234. this._updateHandle(inRangeHandleEnds, visualInRange);
  79235. };
  79236. ContinuousView.prototype._createBarVisual = function (dataInterval, dataExtent, handleEnds, forceState) {
  79237. var opts = {
  79238. forceState: forceState,
  79239. convertOpacityToAlpha: true
  79240. };
  79241. var colorStops = this._makeColorGradient(dataInterval, opts);
  79242. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  79243. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  79244. return {
  79245. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  79246. barPoints: barPoints,
  79247. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  79248. };
  79249. };
  79250. ContinuousView.prototype._makeColorGradient = function (dataInterval, opts) {
  79251. // Considering colorHue, which is not linear, so we have to sample
  79252. // to calculate gradient color stops, but not only calculate head
  79253. // and tail.
  79254. var sampleNumber = 100; // Arbitrary value.
  79255. var colorStops = [];
  79256. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  79257. colorStops.push({
  79258. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  79259. offset: 0
  79260. });
  79261. for (var i = 1; i < sampleNumber; i++) {
  79262. var currValue = dataInterval[0] + step * i;
  79263. if (currValue > dataInterval[1]) {
  79264. break;
  79265. }
  79266. colorStops.push({
  79267. color: this.getControllerVisual(currValue, 'color', opts),
  79268. offset: i / sampleNumber
  79269. });
  79270. }
  79271. colorStops.push({
  79272. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  79273. offset: 1
  79274. });
  79275. return colorStops;
  79276. };
  79277. ContinuousView.prototype._createBarPoints = function (handleEnds, symbolSizes) {
  79278. var itemSize = this.visualMapModel.itemSize;
  79279. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  79280. };
  79281. ContinuousView.prototype._createBarGroup = function (itemAlign) {
  79282. var orient = this._orient;
  79283. var inverse = this.visualMapModel.get('inverse');
  79284. return new Group(orient === 'horizontal' && !inverse ? {
  79285. scaleX: itemAlign === 'bottom' ? 1 : -1,
  79286. rotation: Math.PI / 2
  79287. } : orient === 'horizontal' && inverse ? {
  79288. scaleX: itemAlign === 'bottom' ? -1 : 1,
  79289. rotation: -Math.PI / 2
  79290. } : orient === 'vertical' && !inverse ? {
  79291. scaleX: itemAlign === 'left' ? 1 : -1,
  79292. scaleY: -1
  79293. } : {
  79294. scaleX: itemAlign === 'left' ? 1 : -1
  79295. });
  79296. };
  79297. ContinuousView.prototype._updateHandle = function (handleEnds, visualInRange) {
  79298. if (!this._useHandle) {
  79299. return;
  79300. }
  79301. var shapes = this._shapes;
  79302. var visualMapModel = this.visualMapModel;
  79303. var handleThumbs = shapes.handleThumbs;
  79304. var handleLabels = shapes.handleLabels;
  79305. var itemSize = visualMapModel.itemSize;
  79306. var dataExtent = visualMapModel.getExtent();
  79307. each$e([0, 1], function (handleIndex) {
  79308. var handleThumb = handleThumbs[handleIndex];
  79309. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  79310. handleThumb.y = handleEnds[handleIndex];
  79311. var val = linearMap$2(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
  79312. var symbolSize = this.getControllerVisual(val, 'symbolSize');
  79313. handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
  79314. handleThumb.x = itemSize[0] - symbolSize / 2; // Update handle label position.
  79315. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  79316. handleLabels[handleIndex].setStyle({
  79317. x: textPoint[0],
  79318. y: textPoint[1],
  79319. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  79320. verticalAlign: 'middle',
  79321. align: this._orient === 'vertical' ? this._applyTransform('left', shapes.mainGroup) : 'center'
  79322. });
  79323. }, this);
  79324. };
  79325. ContinuousView.prototype._showIndicator = function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  79326. var visualMapModel = this.visualMapModel;
  79327. var dataExtent = visualMapModel.getExtent();
  79328. var itemSize = visualMapModel.itemSize;
  79329. var sizeExtent = [0, itemSize[1]];
  79330. var shapes = this._shapes;
  79331. var indicator = shapes.indicator;
  79332. if (!indicator) {
  79333. return;
  79334. }
  79335. indicator.attr('invisible', false);
  79336. var opts = {
  79337. convertOpacityToAlpha: true
  79338. };
  79339. var color = this.getControllerVisual(cursorValue, 'color', opts);
  79340. var symbolSize = this.getControllerVisual(cursorValue, 'symbolSize');
  79341. var y = linearMap$2(cursorValue, dataExtent, sizeExtent, true);
  79342. var x = itemSize[0] - symbolSize / 2;
  79343. var oldIndicatorPos = {
  79344. x: indicator.x,
  79345. y: indicator.y
  79346. }; // Update handle label position.
  79347. indicator.y = y;
  79348. indicator.x = x;
  79349. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  79350. var indicatorLabel = shapes.indicatorLabel;
  79351. indicatorLabel.attr('invisible', false);
  79352. var align = this._applyTransform('left', shapes.mainGroup);
  79353. var orient = this._orient;
  79354. var isHorizontal = orient === 'horizontal';
  79355. indicatorLabel.setStyle({
  79356. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  79357. verticalAlign: isHorizontal ? align : 'middle',
  79358. align: isHorizontal ? 'center' : align
  79359. });
  79360. var indicatorNewProps = {
  79361. x: x,
  79362. y: y,
  79363. style: {
  79364. fill: color
  79365. }
  79366. };
  79367. var labelNewProps = {
  79368. style: {
  79369. x: textPoint[0],
  79370. y: textPoint[1]
  79371. }
  79372. };
  79373. if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
  79374. var animationCfg = {
  79375. duration: 100,
  79376. easing: 'cubicInOut',
  79377. additive: true
  79378. };
  79379. indicator.x = oldIndicatorPos.x;
  79380. indicator.y = oldIndicatorPos.y;
  79381. indicator.animateTo(indicatorNewProps, animationCfg);
  79382. indicatorLabel.animateTo(labelNewProps, animationCfg);
  79383. } else {
  79384. indicator.attr(indicatorNewProps);
  79385. indicatorLabel.attr(labelNewProps);
  79386. }
  79387. this._firstShowIndicator = false;
  79388. var handleLabels = this._shapes.handleLabels;
  79389. if (handleLabels) {
  79390. for (var i = 0; i < handleLabels.length; i++) {
  79391. // Fade out handle labels.
  79392. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79393. this._api.enterBlur(handleLabels[i]);
  79394. }
  79395. }
  79396. };
  79397. ContinuousView.prototype._enableHoverLinkToSeries = function () {
  79398. var self = this;
  79399. this._shapes.mainGroup.on('mousemove', function (e) {
  79400. self._hovering = true;
  79401. if (!self._dragging) {
  79402. var itemSize = self.visualMapModel.itemSize;
  79403. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.mainGroup, true, true); // For hover link show when hover handle, which might be
  79404. // below or upper than sizeExtent.
  79405. pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]);
  79406. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  79407. }
  79408. }).on('mouseout', function () {
  79409. // When mouse is out of handle, hoverLink still need
  79410. // to be displayed when realtime is set as false.
  79411. self._hovering = false;
  79412. !self._dragging && self._clearHoverLinkToSeries();
  79413. });
  79414. };
  79415. ContinuousView.prototype._enableHoverLinkFromSeries = function () {
  79416. var zr = this.api.getZr();
  79417. if (this.visualMapModel.option.hoverLink) {
  79418. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  79419. zr.on('mouseout', this._hideIndicator, this);
  79420. } else {
  79421. this._clearHoverLinkFromSeries();
  79422. }
  79423. };
  79424. ContinuousView.prototype._doHoverLinkToSeries = function (cursorPos, hoverOnBar) {
  79425. var visualMapModel = this.visualMapModel;
  79426. var itemSize = visualMapModel.itemSize;
  79427. if (!visualMapModel.option.hoverLink) {
  79428. return;
  79429. }
  79430. var sizeExtent = [0, itemSize[1]];
  79431. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  79432. cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]);
  79433. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  79434. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  79435. var cursorValue = linearMap$2(cursorPos, sizeExtent, dataExtent, true);
  79436. 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,
  79437. // where china and india has very large population.
  79438. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  79439. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  79440. // otherwise labels overlap, especially when dragging.
  79441. if (hoverOnBar) {
  79442. if (valueRange[0] === -Infinity) {
  79443. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  79444. } else if (valueRange[1] === Infinity) {
  79445. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  79446. } else {
  79447. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  79448. }
  79449. } // When realtime is set as false, handles, which are in barGroup,
  79450. // also trigger hoverLink, which help user to realize where they
  79451. // focus on when dragging. (see test/heatmap-large.html)
  79452. // When realtime is set as true, highlight will not show when hover
  79453. // handle, because the label on handle, which displays a exact value
  79454. // but not range, might mislead users.
  79455. var oldBatch = this._hoverLinkDataIndices;
  79456. var newBatch = [];
  79457. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  79458. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  79459. }
  79460. var resultBatches = compressBatches(oldBatch, newBatch);
  79461. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  79462. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  79463. };
  79464. ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function (e) {
  79465. var ecData;
  79466. findEventDispatcher(e.target, function (target) {
  79467. var currECData = getECData(target);
  79468. if (currECData.dataIndex != null) {
  79469. ecData = currECData;
  79470. return true;
  79471. }
  79472. }, true);
  79473. if (!ecData) {
  79474. return;
  79475. }
  79476. var dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
  79477. var visualMapModel = this.visualMapModel;
  79478. if (!visualMapModel.isTargetSeries(dataModel)) {
  79479. return;
  79480. }
  79481. var data = dataModel.getData(ecData.dataType);
  79482. var value = data.getStore().get(visualMapModel.getDataDimensionIndex(data), ecData.dataIndex);
  79483. if (!isNaN(value)) {
  79484. this._showIndicator(value, value);
  79485. }
  79486. };
  79487. ContinuousView.prototype._hideIndicator = function () {
  79488. var shapes = this._shapes;
  79489. shapes.indicator && shapes.indicator.attr('invisible', true);
  79490. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  79491. var handleLabels = this._shapes.handleLabels;
  79492. if (handleLabels) {
  79493. for (var i = 0; i < handleLabels.length; i++) {
  79494. // Fade out handle labels.
  79495. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  79496. this._api.leaveBlur(handleLabels[i]);
  79497. }
  79498. }
  79499. };
  79500. ContinuousView.prototype._clearHoverLinkToSeries = function () {
  79501. this._hideIndicator();
  79502. var indices = this._hoverLinkDataIndices;
  79503. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  79504. indices.length = 0;
  79505. };
  79506. ContinuousView.prototype._clearHoverLinkFromSeries = function () {
  79507. this._hideIndicator();
  79508. var zr = this.api.getZr();
  79509. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  79510. zr.off('mouseout', this._hideIndicator);
  79511. };
  79512. ContinuousView.prototype._applyTransform = function (vertex, element, inverse, global) {
  79513. var transform = getTransform(element, global ? null : this.group);
  79514. return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse);
  79515. }; // TODO: TYPE more specified payload types.
  79516. ContinuousView.prototype._dispatchHighDown = function (type, batch) {
  79517. batch && batch.length && this.api.dispatchAction({
  79518. type: type,
  79519. batch: batch
  79520. });
  79521. };
  79522. /**
  79523. * @override
  79524. */
  79525. ContinuousView.prototype.dispose = function () {
  79526. this._clearHoverLinkFromSeries();
  79527. this._clearHoverLinkToSeries();
  79528. };
  79529. /**
  79530. * @override
  79531. */
  79532. ContinuousView.prototype.remove = function () {
  79533. this._clearHoverLinkFromSeries();
  79534. this._clearHoverLinkToSeries();
  79535. };
  79536. ContinuousView.type = 'visualMap.continuous';
  79537. return ContinuousView;
  79538. }(VisualMapView);
  79539. function createPolygon(points, cursor, onDrift, onDragEnd) {
  79540. return new Polygon({
  79541. shape: {
  79542. points: points
  79543. },
  79544. draggable: !!onDrift,
  79545. cursor: cursor,
  79546. drift: onDrift,
  79547. onmousemove: function (e) {
  79548. // For mobile device, prevent screen slider on the button.
  79549. stop(e.event);
  79550. },
  79551. ondragend: onDragEnd
  79552. });
  79553. }
  79554. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  79555. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  79556. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  79557. if (hoverLinkDataSize) {
  79558. halfHoverLinkSize = linearMap$2(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  79559. }
  79560. return halfHoverLinkSize;
  79561. }
  79562. function useHoverLinkOnHandle(visualMapModel) {
  79563. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  79564. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  79565. }
  79566. function getCursor$1(orient) {
  79567. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  79568. }
  79569. /*
  79570. * Licensed to the Apache Software Foundation (ASF) under one
  79571. * or more contributor license agreements. See the NOTICE file
  79572. * distributed with this work for additional information
  79573. * regarding copyright ownership. The ASF licenses this file
  79574. * to you under the Apache License, Version 2.0 (the
  79575. * "License"); you may not use this file except in compliance
  79576. * with the License. You may obtain a copy of the License at
  79577. *
  79578. * http://www.apache.org/licenses/LICENSE-2.0
  79579. *
  79580. * Unless required by applicable law or agreed to in writing,
  79581. * software distributed under the License is distributed on an
  79582. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79583. * KIND, either express or implied. See the License for the
  79584. * specific language governing permissions and limitations
  79585. * under the License.
  79586. */
  79587. /**
  79588. * AUTO-GENERATED FILE. DO NOT MODIFY.
  79589. */
  79590. /*
  79591. * Licensed to the Apache Software Foundation (ASF) under one
  79592. * or more contributor license agreements. See the NOTICE file
  79593. * distributed with this work for additional information
  79594. * regarding copyright ownership. The ASF licenses this file
  79595. * to you under the Apache License, Version 2.0 (the
  79596. * "License"); you may not use this file except in compliance
  79597. * with the License. You may obtain a copy of the License at
  79598. *
  79599. * http://www.apache.org/licenses/LICENSE-2.0
  79600. *
  79601. * Unless required by applicable law or agreed to in writing,
  79602. * software distributed under the License is distributed on an
  79603. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  79604. * KIND, either express or implied. See the License for the
  79605. * specific language governing permissions and limitations
  79606. * under the License.
  79607. */
  79608. var visualMapActionInfo = {
  79609. type: 'selectDataRange',
  79610. event: 'dataRangeSelected',
  79611. // FIXME use updateView appears wrong
  79612. update: 'update'
  79613. };
  79614. var visualMapActionHander = function (payload, ecModel) {
  79615. ecModel.eachComponent({
  79616. mainType: 'visualMap',
  79617. query: payload
  79618. }, function (model) {
  79619. model.setSelected(payload.selected);
  79620. });
  79621. };
  79622. var visualMapEncodingHandlers = [{
  79623. createOnAllSeries: true,
  79624. reset: function (seriesModel, ecModel) {
  79625. var resetDefines = [];
  79626. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79627. var pipelineContext = seriesModel.pipelineContext;
  79628. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  79629. return;
  79630. }
  79631. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimensionIndex(seriesModel.getData())));
  79632. });
  79633. return resetDefines;
  79634. }
  79635. }, // Only support color.
  79636. {
  79637. createOnAllSeries: true,
  79638. reset: function (seriesModel, ecModel) {
  79639. var data = seriesModel.getData();
  79640. var visualMetaList = [];
  79641. ecModel.eachComponent('visualMap', function (visualMapModel) {
  79642. if (visualMapModel.isTargetSeries(seriesModel)) {
  79643. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  79644. stops: [],
  79645. outerColors: []
  79646. };
  79647. var dimIdx = visualMapModel.getDataDimensionIndex(data);
  79648. if (dimIdx >= 0) {
  79649. // visualMeta.dimension should be dimension index, but not concrete dimension.
  79650. visualMeta.dimension = dimIdx;
  79651. visualMetaList.push(visualMeta);
  79652. }
  79653. }
  79654. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  79655. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  79656. }
  79657. }]; // FIXME
  79658. // performance and export for heatmap?
  79659. // value can be Infinity or -Infinity
  79660. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  79661. var mappings = visualMapModel.targetVisuals[valueState];
  79662. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  79663. var resultVisual = {
  79664. color: getVisualFromData(seriesModel.getData(), 'color') // default color.
  79665. };
  79666. for (var i = 0, len = visualTypes.length; i < len; i++) {
  79667. var type = visualTypes[i];
  79668. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  79669. mapping && mapping.applyVisual(value, getVisual, setVisual);
  79670. }
  79671. return resultVisual.color;
  79672. function getVisual(key) {
  79673. return resultVisual[key];
  79674. }
  79675. function setVisual(key, value) {
  79676. resultVisual[key] = value;
  79677. }
  79678. }
  79679. var each$f = each;
  79680. function visualMapPreprocessor(option) {
  79681. var visualMap = option && option.visualMap;
  79682. if (!isArray(visualMap)) {
  79683. visualMap = visualMap ? [visualMap] : [];
  79684. }
  79685. each$f(visualMap, function (opt) {
  79686. if (!opt) {
  79687. return;
  79688. } // rename splitList to pieces
  79689. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  79690. opt.pieces = opt.splitList;
  79691. delete opt.splitList;
  79692. }
  79693. var pieces = opt.pieces;
  79694. if (pieces && isArray(pieces)) {
  79695. each$f(pieces, function (piece) {
  79696. if (isObject(piece)) {
  79697. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  79698. piece.min = piece.start;
  79699. }
  79700. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  79701. piece.max = piece.end;
  79702. }
  79703. }
  79704. });
  79705. }
  79706. });
  79707. }
  79708. function has$1(obj, name) {
  79709. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  79710. }
  79711. var installed$1 = false;
  79712. function installCommon$1(registers) {
  79713. if (installed$1) {
  79714. return;
  79715. }
  79716. installed$1 = true;
  79717. registers.registerSubTypeDefaulter('visualMap', function (option) {
  79718. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  79719. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  79720. });
  79721. registers.registerAction(visualMapActionInfo, visualMapActionHander);
  79722. each(visualMapEncodingHandlers, function (handler) {
  79723. registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler);
  79724. });
  79725. registers.registerPreprocessor(visualMapPreprocessor);
  79726. }
  79727. function install$N(registers) {
  79728. registers.registerComponentModel(ContinuousModel);
  79729. registers.registerComponentView(ContinuousView);
  79730. installCommon$1(registers);
  79731. }
  79732. var PiecewiseModel =
  79733. /** @class */
  79734. function (_super) {
  79735. __extends(PiecewiseModel, _super);
  79736. function PiecewiseModel() {
  79737. var _this = _super !== null && _super.apply(this, arguments) || this;
  79738. _this.type = PiecewiseModel.type;
  79739. /**
  79740. * The order is always [low, ..., high].
  79741. * [{text: string, interval: Array.<number>}, ...]
  79742. */
  79743. _this._pieceList = [];
  79744. return _this;
  79745. }
  79746. PiecewiseModel.prototype.optionUpdated = function (newOption, isInit) {
  79747. _super.prototype.optionUpdated.apply(this, arguments);
  79748. this.resetExtent();
  79749. var mode = this._mode = this._determineMode();
  79750. this._pieceList = [];
  79751. resetMethods[this._mode].call(this, this._pieceList);
  79752. this._resetSelected(newOption, isInit);
  79753. var categories = this.option.categories;
  79754. this.resetVisual(function (mappingOption, state) {
  79755. if (mode === 'categories') {
  79756. mappingOption.mappingMethod = 'category';
  79757. mappingOption.categories = clone(categories);
  79758. } else {
  79759. mappingOption.dataExtent = this.getExtent();
  79760. mappingOption.mappingMethod = 'piecewise';
  79761. mappingOption.pieceList = map(this._pieceList, function (piece) {
  79762. piece = clone(piece);
  79763. if (state !== 'inRange') {
  79764. // FIXME
  79765. // outOfRange do not support special visual in pieces.
  79766. piece.visual = null;
  79767. }
  79768. return piece;
  79769. });
  79770. }
  79771. });
  79772. };
  79773. /**
  79774. * @protected
  79775. * @override
  79776. */
  79777. PiecewiseModel.prototype.completeVisualOption = function () {
  79778. // Consider this case:
  79779. // visualMap: {
  79780. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  79781. // }
  79782. // where no inRange/outOfRange set but only pieces. So we should make
  79783. // default inRange/outOfRange for this case, otherwise visuals that only
  79784. // appear in `pieces` will not be taken into account in visual encoding.
  79785. var option = this.option;
  79786. var visualTypesInPieces = {};
  79787. var visualTypes = VisualMapping.listVisualTypes();
  79788. var isCategory = this.isCategory();
  79789. each(option.pieces, function (piece) {
  79790. each(visualTypes, function (visualType) {
  79791. if (piece.hasOwnProperty(visualType)) {
  79792. visualTypesInPieces[visualType] = 1;
  79793. }
  79794. });
  79795. });
  79796. each(visualTypesInPieces, function (v, visualType) {
  79797. var exists = false;
  79798. each(this.stateList, function (state) {
  79799. exists = exists || has(option, state, visualType) || has(option.target, state, visualType);
  79800. }, this);
  79801. !exists && each(this.stateList, function (state) {
  79802. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  79803. });
  79804. }, this);
  79805. function has(obj, state, visualType) {
  79806. return obj && obj[state] && obj[state].hasOwnProperty(visualType);
  79807. }
  79808. _super.prototype.completeVisualOption.apply(this, arguments);
  79809. };
  79810. PiecewiseModel.prototype._resetSelected = function (newOption, isInit) {
  79811. var thisOption = this.option;
  79812. var pieceList = this._pieceList; // Selected do not merge but all override.
  79813. var selected = (isInit ? thisOption : newOption).selected || {};
  79814. thisOption.selected = selected; // Consider 'not specified' means true.
  79815. each(pieceList, function (piece, index) {
  79816. var key = this.getSelectedMapKey(piece);
  79817. if (!selected.hasOwnProperty(key)) {
  79818. selected[key] = true;
  79819. }
  79820. }, this);
  79821. if (thisOption.selectedMode === 'single') {
  79822. // Ensure there is only one selected.
  79823. var hasSel_1 = false;
  79824. each(pieceList, function (piece, index) {
  79825. var key = this.getSelectedMapKey(piece);
  79826. if (selected[key]) {
  79827. hasSel_1 ? selected[key] = false : hasSel_1 = true;
  79828. }
  79829. }, this);
  79830. } // thisOption.selectedMode === 'multiple', default: all selected.
  79831. };
  79832. /**
  79833. * @public
  79834. */
  79835. PiecewiseModel.prototype.getItemSymbol = function () {
  79836. return this.get('itemSymbol');
  79837. };
  79838. /**
  79839. * @public
  79840. */
  79841. PiecewiseModel.prototype.getSelectedMapKey = function (piece) {
  79842. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  79843. };
  79844. /**
  79845. * @public
  79846. */
  79847. PiecewiseModel.prototype.getPieceList = function () {
  79848. return this._pieceList;
  79849. };
  79850. /**
  79851. * @return {string}
  79852. */
  79853. PiecewiseModel.prototype._determineMode = function () {
  79854. var option = this.option;
  79855. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  79856. };
  79857. /**
  79858. * @override
  79859. */
  79860. PiecewiseModel.prototype.setSelected = function (selected) {
  79861. this.option.selected = clone(selected);
  79862. };
  79863. /**
  79864. * @override
  79865. */
  79866. PiecewiseModel.prototype.getValueState = function (value) {
  79867. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  79868. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  79869. };
  79870. /**
  79871. * @public
  79872. * @param pieceIndex piece index in visualMapModel.getPieceList()
  79873. */
  79874. PiecewiseModel.prototype.findTargetDataIndices = function (pieceIndex) {
  79875. var result = [];
  79876. var pieceList = this._pieceList;
  79877. this.eachTargetSeries(function (seriesModel) {
  79878. var dataIndices = [];
  79879. var data = seriesModel.getData();
  79880. data.each(this.getDataDimensionIndex(data), function (value, dataIndex) {
  79881. // Should always base on model pieceList, because it is order sensitive.
  79882. var pIdx = VisualMapping.findPieceIndex(value, pieceList);
  79883. pIdx === pieceIndex && dataIndices.push(dataIndex);
  79884. }, this);
  79885. result.push({
  79886. seriesId: seriesModel.id,
  79887. dataIndex: dataIndices
  79888. });
  79889. }, this);
  79890. return result;
  79891. };
  79892. /**
  79893. * @private
  79894. * @param piece piece.value or piece.interval is required.
  79895. * @return Can be Infinity or -Infinity
  79896. */
  79897. PiecewiseModel.prototype.getRepresentValue = function (piece) {
  79898. var representValue;
  79899. if (this.isCategory()) {
  79900. representValue = piece.value;
  79901. } else {
  79902. if (piece.value != null) {
  79903. representValue = piece.value;
  79904. } else {
  79905. var pieceInterval = piece.interval || [];
  79906. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  79907. }
  79908. }
  79909. return representValue;
  79910. };
  79911. PiecewiseModel.prototype.getVisualMeta = function (getColorVisual) {
  79912. // Do not support category. (category axis is ordinal, numerical)
  79913. if (this.isCategory()) {
  79914. return;
  79915. }
  79916. var stops = [];
  79917. var outerColors = ['', ''];
  79918. var visualMapModel = this;
  79919. function setStop(interval, valueState) {
  79920. var representValue = visualMapModel.getRepresentValue({
  79921. interval: interval
  79922. }); // Not category
  79923. if (!valueState) {
  79924. valueState = visualMapModel.getValueState(representValue);
  79925. }
  79926. var color = getColorVisual(representValue, valueState);
  79927. if (interval[0] === -Infinity) {
  79928. outerColors[0] = color;
  79929. } else if (interval[1] === Infinity) {
  79930. outerColors[1] = color;
  79931. } else {
  79932. stops.push({
  79933. value: interval[0],
  79934. color: color
  79935. }, {
  79936. value: interval[1],
  79937. color: color
  79938. });
  79939. }
  79940. } // Suplement
  79941. var pieceList = this._pieceList.slice();
  79942. if (!pieceList.length) {
  79943. pieceList.push({
  79944. interval: [-Infinity, Infinity]
  79945. });
  79946. } else {
  79947. var edge = pieceList[0].interval[0];
  79948. edge !== -Infinity && pieceList.unshift({
  79949. interval: [-Infinity, edge]
  79950. });
  79951. edge = pieceList[pieceList.length - 1].interval[1];
  79952. edge !== Infinity && pieceList.push({
  79953. interval: [edge, Infinity]
  79954. });
  79955. }
  79956. var curr = -Infinity;
  79957. each(pieceList, function (piece) {
  79958. var interval = piece.interval;
  79959. if (interval) {
  79960. // Fulfill gap.
  79961. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  79962. setStop(interval.slice());
  79963. curr = interval[1];
  79964. }
  79965. }, this);
  79966. return {
  79967. stops: stops,
  79968. outerColors: outerColors
  79969. };
  79970. };
  79971. PiecewiseModel.type = 'visualMap.piecewise';
  79972. PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  79973. selected: null,
  79974. minOpen: false,
  79975. maxOpen: false,
  79976. align: 'auto',
  79977. itemWidth: 20,
  79978. itemHeight: 14,
  79979. itemSymbol: 'roundRect',
  79980. pieces: null,
  79981. categories: null,
  79982. splitNumber: 5,
  79983. selectedMode: 'multiple',
  79984. itemGap: 10,
  79985. hoverLink: true // Enable hover highlight.
  79986. });
  79987. return PiecewiseModel;
  79988. }(VisualMapModel);
  79989. /**
  79990. * Key is this._mode
  79991. * @type {Object}
  79992. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  79993. */
  79994. var resetMethods = {
  79995. splitNumber: function (outPieceList) {
  79996. var thisOption = this.option;
  79997. var precision = Math.min(thisOption.precision, 20);
  79998. var dataExtent = this.getExtent();
  79999. var splitNumber = thisOption.splitNumber;
  80000. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  80001. thisOption.splitNumber = splitNumber;
  80002. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  80003. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  80004. precision++;
  80005. }
  80006. thisOption.precision = precision;
  80007. splitStep = +splitStep.toFixed(precision);
  80008. if (thisOption.minOpen) {
  80009. outPieceList.push({
  80010. interval: [-Infinity, dataExtent[0]],
  80011. close: [0, 0]
  80012. });
  80013. }
  80014. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  80015. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  80016. outPieceList.push({
  80017. interval: [curr, max],
  80018. close: [1, 1]
  80019. });
  80020. }
  80021. if (thisOption.maxOpen) {
  80022. outPieceList.push({
  80023. interval: [dataExtent[1], Infinity],
  80024. close: [0, 0]
  80025. });
  80026. }
  80027. reformIntervals(outPieceList);
  80028. each(outPieceList, function (piece, index) {
  80029. piece.index = index;
  80030. piece.text = this.formatValueText(piece.interval);
  80031. }, this);
  80032. },
  80033. categories: function (outPieceList) {
  80034. var thisOption = this.option;
  80035. each(thisOption.categories, function (cate) {
  80036. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  80037. // 是否改一致。
  80038. outPieceList.push({
  80039. text: this.formatValueText(cate, true),
  80040. value: cate
  80041. });
  80042. }, this); // See "Order Rule".
  80043. normalizeReverse(thisOption, outPieceList);
  80044. },
  80045. pieces: function (outPieceList) {
  80046. var thisOption = this.option;
  80047. each(thisOption.pieces, function (pieceListItem, index) {
  80048. if (!isObject(pieceListItem)) {
  80049. pieceListItem = {
  80050. value: pieceListItem
  80051. };
  80052. }
  80053. var item = {
  80054. text: '',
  80055. index: index
  80056. };
  80057. if (pieceListItem.label != null) {
  80058. item.text = pieceListItem.label;
  80059. }
  80060. if (pieceListItem.hasOwnProperty('value')) {
  80061. var value = item.value = pieceListItem.value;
  80062. item.interval = [value, value];
  80063. item.close = [1, 1];
  80064. } else {
  80065. // `min` `max` is legacy option.
  80066. // `lt` `gt` `lte` `gte` is recommended.
  80067. var interval = item.interval = [];
  80068. var close_1 = item.close = [0, 0];
  80069. var closeList = [1, 0, 1];
  80070. var infinityList = [-Infinity, Infinity];
  80071. var useMinMax = [];
  80072. for (var lg = 0; lg < 2; lg++) {
  80073. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  80074. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  80075. interval[lg] = pieceListItem[names[i]];
  80076. close_1[lg] = closeList[i];
  80077. useMinMax[lg] = i === 2;
  80078. }
  80079. interval[lg] == null && (interval[lg] = infinityList[lg]);
  80080. }
  80081. useMinMax[0] && interval[1] === Infinity && (close_1[0] = 0);
  80082. useMinMax[1] && interval[0] === -Infinity && (close_1[1] = 0);
  80083. if ("development" !== 'production') {
  80084. if (interval[0] > interval[1]) {
  80085. console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.');
  80086. }
  80087. }
  80088. if (interval[0] === interval[1] && close_1[0] && close_1[1]) {
  80089. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  80090. // we use value to lift the priority when min === max
  80091. item.value = interval[0];
  80092. }
  80093. }
  80094. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  80095. outPieceList.push(item);
  80096. }, this); // See "Order Rule".
  80097. normalizeReverse(thisOption, outPieceList); // Only pieces
  80098. reformIntervals(outPieceList);
  80099. each(outPieceList, function (piece) {
  80100. var close = piece.close;
  80101. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  80102. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  80103. }, this);
  80104. }
  80105. };
  80106. function normalizeReverse(thisOption, pieceList) {
  80107. var inverse = thisOption.inverse;
  80108. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  80109. pieceList.reverse();
  80110. }
  80111. }
  80112. var PiecewiseVisualMapView =
  80113. /** @class */
  80114. function (_super) {
  80115. __extends(PiecewiseVisualMapView, _super);
  80116. function PiecewiseVisualMapView() {
  80117. var _this = _super !== null && _super.apply(this, arguments) || this;
  80118. _this.type = PiecewiseVisualMapView.type;
  80119. return _this;
  80120. }
  80121. PiecewiseVisualMapView.prototype.doRender = function () {
  80122. var thisGroup = this.group;
  80123. thisGroup.removeAll();
  80124. var visualMapModel = this.visualMapModel;
  80125. var textGap = visualMapModel.get('textGap');
  80126. var textStyleModel = visualMapModel.textStyleModel;
  80127. var textFont = textStyleModel.getFont();
  80128. var textFill = textStyleModel.getTextColor();
  80129. var itemAlign = this._getItemAlign();
  80130. var itemSize = visualMapModel.itemSize;
  80131. var viewData = this._getViewData();
  80132. var endsText = viewData.endsText;
  80133. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  80134. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  80135. each(viewData.viewPieceList, function (item) {
  80136. var piece = item.piece;
  80137. var itemGroup = new Group();
  80138. itemGroup.onclick = bind(this._onItemClick, this, piece);
  80139. this._enableHoverLink(itemGroup, item.indexInModelPieceList); // TODO Category
  80140. var representValue = visualMapModel.getRepresentValue(piece);
  80141. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  80142. if (showLabel) {
  80143. var visualState = this.visualMapModel.getValueState(representValue);
  80144. itemGroup.add(new ZRText({
  80145. style: {
  80146. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  80147. y: itemSize[1] / 2,
  80148. text: piece.text,
  80149. verticalAlign: 'middle',
  80150. align: itemAlign,
  80151. font: textFont,
  80152. fill: textFill,
  80153. opacity: visualState === 'outOfRange' ? 0.5 : 1
  80154. }
  80155. }));
  80156. }
  80157. thisGroup.add(itemGroup);
  80158. }, this);
  80159. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  80160. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  80161. this.renderBackground(thisGroup);
  80162. this.positionGroup(thisGroup);
  80163. };
  80164. PiecewiseVisualMapView.prototype._enableHoverLink = function (itemGroup, pieceIndex) {
  80165. var _this = this;
  80166. itemGroup.on('mouseover', function () {
  80167. return onHoverLink('highlight');
  80168. }).on('mouseout', function () {
  80169. return onHoverLink('downplay');
  80170. });
  80171. var onHoverLink = function (method) {
  80172. var visualMapModel = _this.visualMapModel; // TODO: TYPE More detailed action types
  80173. visualMapModel.option.hoverLink && _this.api.dispatchAction({
  80174. type: method,
  80175. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  80176. });
  80177. };
  80178. };
  80179. PiecewiseVisualMapView.prototype._getItemAlign = function () {
  80180. var visualMapModel = this.visualMapModel;
  80181. var modelOption = visualMapModel.option;
  80182. if (modelOption.orient === 'vertical') {
  80183. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  80184. } else {
  80185. // horizontal, most case left unless specifying right.
  80186. var align = modelOption.align;
  80187. if (!align || align === 'auto') {
  80188. align = 'left';
  80189. }
  80190. return align;
  80191. }
  80192. };
  80193. PiecewiseVisualMapView.prototype._renderEndsText = function (group, text, itemSize, showLabel, itemAlign) {
  80194. if (!text) {
  80195. return;
  80196. }
  80197. var itemGroup = new Group();
  80198. var textStyleModel = this.visualMapModel.textStyleModel;
  80199. itemGroup.add(new ZRText({
  80200. style: createTextStyle(textStyleModel, {
  80201. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  80202. y: itemSize[1] / 2,
  80203. verticalAlign: 'middle',
  80204. align: showLabel ? itemAlign : 'center',
  80205. text: text
  80206. })
  80207. }));
  80208. group.add(itemGroup);
  80209. };
  80210. /**
  80211. * @private
  80212. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  80213. */
  80214. PiecewiseVisualMapView.prototype._getViewData = function () {
  80215. var visualMapModel = this.visualMapModel;
  80216. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  80217. return {
  80218. piece: piece,
  80219. indexInModelPieceList: index
  80220. };
  80221. });
  80222. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  80223. var orient = visualMapModel.get('orient');
  80224. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  80225. if (orient === 'horizontal' ? inverse : !inverse) {
  80226. viewPieceList.reverse();
  80227. } // Origin order of endsText is [high, low]
  80228. else if (endsText) {
  80229. endsText = endsText.slice().reverse();
  80230. }
  80231. return {
  80232. viewPieceList: viewPieceList,
  80233. endsText: endsText
  80234. };
  80235. };
  80236. PiecewiseVisualMapView.prototype._createItemSymbol = function (group, representValue, shapeParam) {
  80237. group.add(createSymbol( // symbol will be string
  80238. this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], // color will be string
  80239. this.getControllerVisual(representValue, 'color')));
  80240. };
  80241. PiecewiseVisualMapView.prototype._onItemClick = function (piece) {
  80242. var visualMapModel = this.visualMapModel;
  80243. var option = visualMapModel.option;
  80244. var selectedMode = option.selectedMode;
  80245. if (!selectedMode) {
  80246. return;
  80247. }
  80248. var selected = clone(option.selected);
  80249. var newKey = visualMapModel.getSelectedMapKey(piece);
  80250. if (selectedMode === 'single' || selectedMode === true) {
  80251. selected[newKey] = true;
  80252. each(selected, function (o, key) {
  80253. selected[key] = key === newKey;
  80254. });
  80255. } else {
  80256. selected[newKey] = !selected[newKey];
  80257. }
  80258. this.api.dispatchAction({
  80259. type: 'selectDataRange',
  80260. from: this.uid,
  80261. visualMapId: this.visualMapModel.id,
  80262. selected: selected
  80263. });
  80264. };
  80265. PiecewiseVisualMapView.type = 'visualMap.piecewise';
  80266. return PiecewiseVisualMapView;
  80267. }(VisualMapView);
  80268. function install$O(registers) {
  80269. registers.registerComponentModel(PiecewiseModel);
  80270. registers.registerComponentView(PiecewiseVisualMapView);
  80271. installCommon$1(registers);
  80272. }
  80273. function install$P(registers) {
  80274. use(install$N);
  80275. use(install$O); // Do not install './dataZoomSelect',
  80276. // since it only work for toolbox dataZoom.
  80277. }
  80278. var DEFAULT_OPTION = {
  80279. label: {
  80280. enabled: true
  80281. },
  80282. decal: {
  80283. show: false
  80284. }
  80285. };
  80286. var inner$l = makeInner();
  80287. var decalPaletteScope = {};
  80288. function ariaVisual(ecModel, api) {
  80289. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  80290. if (!ariaModel.get('enabled')) {
  80291. return;
  80292. }
  80293. var defaultOption = clone(DEFAULT_OPTION);
  80294. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  80295. merge(ariaModel.option, defaultOption, false);
  80296. setDecal();
  80297. setLabel();
  80298. function setDecal() {
  80299. var decalModel = ariaModel.getModel('decal');
  80300. var useDecal = decalModel.get('show');
  80301. if (useDecal) {
  80302. // Each type of series use one scope.
  80303. // Pie and funnel are using different scopes.
  80304. var paletteScopeGroupByType_1 = createHashMap();
  80305. ecModel.eachSeries(function (seriesModel) {
  80306. if (seriesModel.isColorBySeries()) {
  80307. return;
  80308. }
  80309. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  80310. if (!decalScope) {
  80311. decalScope = {};
  80312. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  80313. }
  80314. inner$l(seriesModel).scope = decalScope;
  80315. });
  80316. ecModel.eachRawSeries(function (seriesModel) {
  80317. if (ecModel.isSeriesFiltered(seriesModel)) {
  80318. return;
  80319. }
  80320. if (isFunction(seriesModel.enableAriaDecal)) {
  80321. // Let series define how to use decal palette on data
  80322. seriesModel.enableAriaDecal();
  80323. return;
  80324. }
  80325. var data = seriesModel.getData();
  80326. if (!seriesModel.isColorBySeries()) {
  80327. var dataAll_1 = seriesModel.getRawData();
  80328. var idxMap_1 = {};
  80329. var decalScope_1 = inner$l(seriesModel).scope;
  80330. data.each(function (idx) {
  80331. var rawIdx = data.getRawIndex(idx);
  80332. idxMap_1[rawIdx] = idx;
  80333. });
  80334. var dataCount_1 = dataAll_1.count();
  80335. dataAll_1.each(function (rawIdx) {
  80336. var idx = idxMap_1[rawIdx];
  80337. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  80338. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  80339. var specifiedDecal = data.getItemVisual(idx, 'decal');
  80340. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  80341. });
  80342. } else {
  80343. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  80344. var specifiedDecal = data.getVisual('decal');
  80345. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  80346. }
  80347. function mergeDecal(specifiedDecal, paletteDecal) {
  80348. // Merge decal from palette to decal from itemStyle.
  80349. // User do not need to specify all of the decal props.
  80350. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  80351. resultDecal.dirty = true;
  80352. return resultDecal;
  80353. }
  80354. });
  80355. }
  80356. }
  80357. function setLabel() {
  80358. var labelLocale = ecModel.getLocaleModel().get('aria');
  80359. var labelModel = ariaModel.getModel('label');
  80360. labelModel.option = defaults(labelModel.option, labelLocale);
  80361. if (!labelModel.get('enabled')) {
  80362. return;
  80363. }
  80364. var dom = api.getZr().dom;
  80365. if (labelModel.get('description')) {
  80366. dom.setAttribute('aria-label', labelModel.get('description'));
  80367. return;
  80368. }
  80369. var seriesCnt = ecModel.getSeriesCount();
  80370. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  80371. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  80372. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  80373. var ariaLabel;
  80374. if (seriesCnt < 1) {
  80375. // No series, no aria label
  80376. return;
  80377. } else {
  80378. var title = getTitle();
  80379. if (title) {
  80380. var withTitle = labelModel.get(['general', 'withTitle']);
  80381. ariaLabel = replace(withTitle, {
  80382. title: title
  80383. });
  80384. } else {
  80385. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  80386. }
  80387. var seriesLabels_1 = [];
  80388. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  80389. ariaLabel += replace(prefix, {
  80390. seriesCount: seriesCnt
  80391. });
  80392. ecModel.eachSeries(function (seriesModel, idx) {
  80393. if (idx < displaySeriesCnt) {
  80394. var seriesLabel = void 0;
  80395. var seriesName = seriesModel.get('name');
  80396. var withName = seriesName ? 'withName' : 'withoutName';
  80397. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  80398. seriesLabel = replace(seriesLabel, {
  80399. seriesId: seriesModel.seriesIndex,
  80400. seriesName: seriesModel.get('name'),
  80401. seriesType: getSeriesTypeName(seriesModel.subType)
  80402. });
  80403. var data = seriesModel.getData();
  80404. if (data.count() > maxDataCnt) {
  80405. // Show part of data
  80406. var partialLabel = labelModel.get(['data', 'partialData']);
  80407. seriesLabel += replace(partialLabel, {
  80408. displayCnt: maxDataCnt
  80409. });
  80410. } else {
  80411. seriesLabel += labelModel.get(['data', 'allData']);
  80412. }
  80413. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  80414. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  80415. var dataLabels = [];
  80416. for (var i = 0; i < data.count(); i++) {
  80417. if (i < maxDataCnt) {
  80418. var name_1 = data.getName(i);
  80419. var value = data.getValues(i);
  80420. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  80421. dataLabels.push(replace(dataLabel, {
  80422. name: name_1,
  80423. value: value.join(middleSeparator_1)
  80424. }));
  80425. }
  80426. }
  80427. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  80428. seriesLabels_1.push(seriesLabel);
  80429. }
  80430. });
  80431. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  80432. var middleSeparator = separatorModel.get('middle');
  80433. var endSeparator = separatorModel.get('end');
  80434. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  80435. dom.setAttribute('aria-label', ariaLabel);
  80436. }
  80437. }
  80438. function replace(str, keyValues) {
  80439. if (!isString(str)) {
  80440. return str;
  80441. }
  80442. var result = str;
  80443. each(keyValues, function (value, key) {
  80444. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  80445. });
  80446. return result;
  80447. }
  80448. function getTitle() {
  80449. var title = ecModel.get('title');
  80450. if (title && title.length) {
  80451. title = title[0];
  80452. }
  80453. return title && title.text;
  80454. }
  80455. function getSeriesTypeName(type) {
  80456. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  80457. }
  80458. }
  80459. function ariaPreprocessor(option) {
  80460. if (!option || !option.aria) {
  80461. return;
  80462. }
  80463. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  80464. if (aria.show != null) {
  80465. aria.enabled = aria.show;
  80466. }
  80467. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  80468. each(['description', 'general', 'series', 'data'], function (name) {
  80469. if (aria[name] != null) {
  80470. aria.label[name] = aria[name];
  80471. }
  80472. });
  80473. }
  80474. function install$Q(registers) {
  80475. registers.registerPreprocessor(ariaPreprocessor);
  80476. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  80477. }
  80478. var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = {
  80479. value: 'eq',
  80480. // PENDING: not good for literal semantic?
  80481. '<': 'lt',
  80482. '<=': 'lte',
  80483. '>': 'gt',
  80484. '>=': 'gte',
  80485. '=': 'eq',
  80486. '!=': 'ne',
  80487. '<>': 'ne' // Might be misleading for sake of the difference between '==' and '===',
  80488. // so don't support them.
  80489. // '==': 'eq',
  80490. // '===': 'seq',
  80491. // '!==': 'sne'
  80492. // PENDING: Whether support some common alias "ge", "le", "neq"?
  80493. // ge: 'gte',
  80494. // le: 'lte',
  80495. // neq: 'ne',
  80496. }; // type RelationalExpressionOpEvaluate = (tarVal: unknown, condVal: unknown) => boolean;
  80497. var RegExpEvaluator =
  80498. /** @class */
  80499. function () {
  80500. function RegExpEvaluator(rVal) {
  80501. // Support condVal: RegExp | string
  80502. var condValue = this._condVal = isString(rVal) ? new RegExp(rVal) : isRegExp(rVal) ? rVal : null;
  80503. if (condValue == null) {
  80504. var errMsg = '';
  80505. if ("development" !== 'production') {
  80506. errMsg = makePrintable('Illegal regexp', rVal, 'in');
  80507. }
  80508. throwError(errMsg);
  80509. }
  80510. }
  80511. RegExpEvaluator.prototype.evaluate = function (lVal) {
  80512. var type = typeof lVal;
  80513. return isString(type) ? this._condVal.test(lVal) : isNumber(type) ? this._condVal.test(lVal + '') : false;
  80514. };
  80515. return RegExpEvaluator;
  80516. }();
  80517. var ConstConditionInternal =
  80518. /** @class */
  80519. function () {
  80520. function ConstConditionInternal() {}
  80521. ConstConditionInternal.prototype.evaluate = function () {
  80522. return this.value;
  80523. };
  80524. return ConstConditionInternal;
  80525. }();
  80526. var AndConditionInternal =
  80527. /** @class */
  80528. function () {
  80529. function AndConditionInternal() {}
  80530. AndConditionInternal.prototype.evaluate = function () {
  80531. var children = this.children;
  80532. for (var i = 0; i < children.length; i++) {
  80533. if (!children[i].evaluate()) {
  80534. return false;
  80535. }
  80536. }
  80537. return true;
  80538. };
  80539. return AndConditionInternal;
  80540. }();
  80541. var OrConditionInternal =
  80542. /** @class */
  80543. function () {
  80544. function OrConditionInternal() {}
  80545. OrConditionInternal.prototype.evaluate = function () {
  80546. var children = this.children;
  80547. for (var i = 0; i < children.length; i++) {
  80548. if (children[i].evaluate()) {
  80549. return true;
  80550. }
  80551. }
  80552. return false;
  80553. };
  80554. return OrConditionInternal;
  80555. }();
  80556. var NotConditionInternal =
  80557. /** @class */
  80558. function () {
  80559. function NotConditionInternal() {}
  80560. NotConditionInternal.prototype.evaluate = function () {
  80561. return !this.child.evaluate();
  80562. };
  80563. return NotConditionInternal;
  80564. }();
  80565. var RelationalConditionInternal =
  80566. /** @class */
  80567. function () {
  80568. function RelationalConditionInternal() {}
  80569. RelationalConditionInternal.prototype.evaluate = function () {
  80570. var needParse = !!this.valueParser; // Call getValue with no `this`.
  80571. var getValue = this.getValue;
  80572. var tarValRaw = getValue(this.valueGetterParam);
  80573. var tarValParsed = needParse ? this.valueParser(tarValRaw) : null; // Relational cond follow "and" logic internally.
  80574. for (var i = 0; i < this.subCondList.length; i++) {
  80575. if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) {
  80576. return false;
  80577. }
  80578. }
  80579. return true;
  80580. };
  80581. return RelationalConditionInternal;
  80582. }();
  80583. function parseOption(exprOption, getters) {
  80584. if (exprOption === true || exprOption === false) {
  80585. var cond = new ConstConditionInternal();
  80586. cond.value = exprOption;
  80587. return cond;
  80588. }
  80589. var errMsg = '';
  80590. if (!isObjectNotArray(exprOption)) {
  80591. if ("development" !== 'production') {
  80592. errMsg = makePrintable('Illegal config. Expect a plain object but actually', exprOption);
  80593. }
  80594. throwError(errMsg);
  80595. }
  80596. if (exprOption.and) {
  80597. return parseAndOrOption('and', exprOption, getters);
  80598. } else if (exprOption.or) {
  80599. return parseAndOrOption('or', exprOption, getters);
  80600. } else if (exprOption.not) {
  80601. return parseNotOption(exprOption, getters);
  80602. }
  80603. return parseRelationalOption(exprOption, getters);
  80604. }
  80605. function parseAndOrOption(op, exprOption, getters) {
  80606. var subOptionArr = exprOption[op];
  80607. var errMsg = '';
  80608. if ("development" !== 'production') {
  80609. errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption);
  80610. }
  80611. if (!isArray(subOptionArr)) {
  80612. throwError(errMsg);
  80613. }
  80614. if (!subOptionArr.length) {
  80615. throwError(errMsg);
  80616. }
  80617. var cond = op === 'and' ? new AndConditionInternal() : new OrConditionInternal();
  80618. cond.children = map(subOptionArr, function (subOption) {
  80619. return parseOption(subOption, getters);
  80620. });
  80621. if (!cond.children.length) {
  80622. throwError(errMsg);
  80623. }
  80624. return cond;
  80625. }
  80626. function parseNotOption(exprOption, getters) {
  80627. var subOption = exprOption.not;
  80628. var errMsg = '';
  80629. if ("development" !== 'production') {
  80630. errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption);
  80631. }
  80632. if (!isObjectNotArray(subOption)) {
  80633. throwError(errMsg);
  80634. }
  80635. var cond = new NotConditionInternal();
  80636. cond.child = parseOption(subOption, getters);
  80637. if (!cond.child) {
  80638. throwError(errMsg);
  80639. }
  80640. return cond;
  80641. }
  80642. function parseRelationalOption(exprOption, getters) {
  80643. var errMsg = '';
  80644. var valueGetterParam = getters.prepareGetValue(exprOption);
  80645. var subCondList = [];
  80646. var exprKeys = keys(exprOption);
  80647. var parserName = exprOption.parser;
  80648. var valueParser = parserName ? getRawValueParser(parserName) : null;
  80649. for (var i = 0; i < exprKeys.length; i++) {
  80650. var keyRaw = exprKeys[i];
  80651. if (keyRaw === 'parser' || getters.valueGetterAttrMap.get(keyRaw)) {
  80652. continue;
  80653. }
  80654. var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw;
  80655. var condValueRaw = exprOption[keyRaw];
  80656. var condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw;
  80657. var evaluator = createFilterComparator(op, condValueParsed) || op === 'reg' && new RegExpEvaluator(condValueParsed);
  80658. if (!evaluator) {
  80659. if ("development" !== 'production') {
  80660. errMsg = makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption);
  80661. }
  80662. throwError(errMsg);
  80663. }
  80664. subCondList.push(evaluator);
  80665. }
  80666. if (!subCondList.length) {
  80667. if ("development" !== 'production') {
  80668. errMsg = makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption);
  80669. } // No relational operator always disabled in case of dangers result.
  80670. throwError(errMsg);
  80671. }
  80672. var cond = new RelationalConditionInternal();
  80673. cond.valueGetterParam = valueGetterParam;
  80674. cond.valueParser = valueParser;
  80675. cond.getValue = getters.getValue;
  80676. cond.subCondList = subCondList;
  80677. return cond;
  80678. }
  80679. function isObjectNotArray(val) {
  80680. return isObject(val) && !isArrayLike(val);
  80681. }
  80682. var ConditionalExpressionParsed =
  80683. /** @class */
  80684. function () {
  80685. function ConditionalExpressionParsed(exprOption, getters) {
  80686. this._cond = parseOption(exprOption, getters);
  80687. }
  80688. ConditionalExpressionParsed.prototype.evaluate = function () {
  80689. return this._cond.evaluate();
  80690. };
  80691. return ConditionalExpressionParsed;
  80692. }();
  80693. function parseConditionalExpression(exprOption, getters) {
  80694. return new ConditionalExpressionParsed(exprOption, getters);
  80695. }
  80696. var filterTransform = {
  80697. type: 'echarts:filter',
  80698. // PENDING: enhance to filter by index rather than create new data
  80699. transform: function (params) {
  80700. // [Caveat] Fail-Fast:
  80701. // Do not return the whole dataset unless user config indicates it explicitly.
  80702. // For example, if no condition is specified by mistake, returning an empty result
  80703. // is better than returning the entire raw source for the user to find the mistake.
  80704. var upstream = params.upstream;
  80705. var rawItem;
  80706. var condition = parseConditionalExpression(params.config, {
  80707. valueGetterAttrMap: createHashMap({
  80708. dimension: true
  80709. }),
  80710. prepareGetValue: function (exprOption) {
  80711. var errMsg = '';
  80712. var dimLoose = exprOption.dimension;
  80713. if (!hasOwn(exprOption, 'dimension')) {
  80714. if ("development" !== 'production') {
  80715. errMsg = makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption);
  80716. }
  80717. throwError(errMsg);
  80718. }
  80719. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80720. if (!dimInfo) {
  80721. if ("development" !== 'production') {
  80722. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n');
  80723. }
  80724. throwError(errMsg);
  80725. }
  80726. return {
  80727. dimIdx: dimInfo.index
  80728. };
  80729. },
  80730. getValue: function (param) {
  80731. return upstream.retrieveValueFromItem(rawItem, param.dimIdx);
  80732. }
  80733. });
  80734. var resultData = [];
  80735. for (var i = 0, len = upstream.count(); i < len; i++) {
  80736. rawItem = upstream.getRawDataItem(i);
  80737. if (condition.evaluate()) {
  80738. resultData.push(rawItem);
  80739. }
  80740. }
  80741. return {
  80742. data: resultData
  80743. };
  80744. }
  80745. };
  80746. var sampleLog = '';
  80747. if ("development" !== 'production') {
  80748. sampleLog = ['Valid config is like:', '{ dimension: "age", order: "asc" }', 'or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'].join(' ');
  80749. }
  80750. var sortTransform = {
  80751. type: 'echarts:sort',
  80752. transform: function (params) {
  80753. var upstream = params.upstream;
  80754. var config = params.config;
  80755. var errMsg = ''; // Normalize
  80756. // const orderExprList: OrderExpression[] = isArray(config[0])
  80757. // ? config as OrderExpression[]
  80758. // : [config as OrderExpression];
  80759. var orderExprList = normalizeToArray(config);
  80760. if (!orderExprList.length) {
  80761. if ("development" !== 'production') {
  80762. errMsg = 'Empty `config` in sort transform.';
  80763. }
  80764. throwError(errMsg);
  80765. }
  80766. var orderDefList = [];
  80767. each(orderExprList, function (orderExpr) {
  80768. var dimLoose = orderExpr.dimension;
  80769. var order = orderExpr.order;
  80770. var parserName = orderExpr.parser;
  80771. var incomparable = orderExpr.incomparable;
  80772. if (dimLoose == null) {
  80773. if ("development" !== 'production') {
  80774. errMsg = 'Sort transform config must has "dimension" specified.' + sampleLog;
  80775. }
  80776. throwError(errMsg);
  80777. }
  80778. if (order !== 'asc' && order !== 'desc') {
  80779. if ("development" !== 'production') {
  80780. errMsg = 'Sort transform config must has "order" specified.' + sampleLog;
  80781. }
  80782. throwError(errMsg);
  80783. }
  80784. if (incomparable && incomparable !== 'min' && incomparable !== 'max') {
  80785. var errMsg_1 = '';
  80786. if ("development" !== 'production') {
  80787. errMsg_1 = 'incomparable must be "min" or "max" rather than "' + incomparable + '".';
  80788. }
  80789. throwError(errMsg_1);
  80790. }
  80791. if (order !== 'asc' && order !== 'desc') {
  80792. var errMsg_2 = '';
  80793. if ("development" !== 'production') {
  80794. errMsg_2 = 'order must be "asc" or "desc" rather than "' + order + '".';
  80795. }
  80796. throwError(errMsg_2);
  80797. }
  80798. var dimInfo = upstream.getDimensionInfo(dimLoose);
  80799. if (!dimInfo) {
  80800. if ("development" !== 'production') {
  80801. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n');
  80802. }
  80803. throwError(errMsg);
  80804. }
  80805. var parser = parserName ? getRawValueParser(parserName) : null;
  80806. if (parserName && !parser) {
  80807. if ("development" !== 'production') {
  80808. errMsg = makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n');
  80809. }
  80810. throwError(errMsg);
  80811. }
  80812. orderDefList.push({
  80813. dimIdx: dimInfo.index,
  80814. parser: parser,
  80815. comparator: new SortOrderComparator(order, incomparable)
  80816. });
  80817. }); // TODO: support it?
  80818. var sourceFormat = upstream.sourceFormat;
  80819. if (sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  80820. if ("development" !== 'production') {
  80821. errMsg = 'sourceFormat "' + sourceFormat + '" is not supported yet';
  80822. }
  80823. throwError(errMsg);
  80824. } // Other upstream format are all array.
  80825. var resultData = [];
  80826. for (var i = 0, len = upstream.count(); i < len; i++) {
  80827. resultData.push(upstream.getRawDataItem(i));
  80828. }
  80829. resultData.sort(function (item0, item1) {
  80830. for (var i = 0; i < orderDefList.length; i++) {
  80831. var orderDef = orderDefList[i];
  80832. var val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx);
  80833. var val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx);
  80834. if (orderDef.parser) {
  80835. val0 = orderDef.parser(val0);
  80836. val1 = orderDef.parser(val1);
  80837. }
  80838. var result = orderDef.comparator.evaluate(val0, val1);
  80839. if (result !== 0) {
  80840. return result;
  80841. }
  80842. }
  80843. return 0;
  80844. });
  80845. return {
  80846. data: resultData
  80847. };
  80848. }
  80849. };
  80850. function install$R(registers) {
  80851. registers.registerTransform(filterTransform);
  80852. registers.registerTransform(sortTransform);
  80853. }
  80854. var DatasetModel =
  80855. /** @class */
  80856. function (_super) {
  80857. __extends(DatasetModel, _super);
  80858. function DatasetModel() {
  80859. var _this = _super !== null && _super.apply(this, arguments) || this;
  80860. _this.type = 'dataset';
  80861. return _this;
  80862. }
  80863. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  80864. _super.prototype.init.call(this, option, parentModel, ecModel);
  80865. this._sourceManager = new SourceManager(this);
  80866. disableTransformOptionMerge(this);
  80867. };
  80868. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  80869. _super.prototype.mergeOption.call(this, newOption, ecModel);
  80870. disableTransformOptionMerge(this);
  80871. };
  80872. DatasetModel.prototype.optionUpdated = function () {
  80873. this._sourceManager.dirty();
  80874. };
  80875. DatasetModel.prototype.getSourceManager = function () {
  80876. return this._sourceManager;
  80877. };
  80878. DatasetModel.type = 'dataset';
  80879. DatasetModel.defaultOption = {
  80880. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  80881. };
  80882. return DatasetModel;
  80883. }(ComponentModel);
  80884. var DatasetView =
  80885. /** @class */
  80886. function (_super) {
  80887. __extends(DatasetView, _super);
  80888. function DatasetView() {
  80889. var _this = _super !== null && _super.apply(this, arguments) || this;
  80890. _this.type = 'dataset';
  80891. return _this;
  80892. }
  80893. DatasetView.type = 'dataset';
  80894. return DatasetView;
  80895. }(ComponentView);
  80896. function install$S(registers) {
  80897. registers.registerComponentModel(DatasetModel);
  80898. registers.registerComponentView(DatasetView);
  80899. }
  80900. var CMD$4 = PathProxy.CMD;
  80901. function aroundEqual(a, b) {
  80902. return Math.abs(a - b) < 1e-5;
  80903. }
  80904. function pathToBezierCurves(path) {
  80905. var data = path.data;
  80906. var len = path.len();
  80907. var bezierArrayGroups = [];
  80908. var currentSubpath;
  80909. var xi = 0;
  80910. var yi = 0;
  80911. var x0 = 0;
  80912. var y0 = 0;
  80913. function createNewSubpath(x, y) {
  80914. if (currentSubpath && currentSubpath.length > 2) {
  80915. bezierArrayGroups.push(currentSubpath);
  80916. }
  80917. currentSubpath = [x, y];
  80918. }
  80919. function addLine(x0, y0, x1, y1) {
  80920. if (!(aroundEqual(x0, x1) && aroundEqual(y0, y1))) {
  80921. currentSubpath.push(x0, y0, x1, y1, x1, y1);
  80922. }
  80923. }
  80924. function addArc(startAngle, endAngle, cx, cy, rx, ry) {
  80925. var delta = Math.abs(endAngle - startAngle);
  80926. var len = Math.tan(delta / 4) * 4 / 3;
  80927. var dir = endAngle < startAngle ? -1 : 1;
  80928. var c1 = Math.cos(startAngle);
  80929. var s1 = Math.sin(startAngle);
  80930. var c2 = Math.cos(endAngle);
  80931. var s2 = Math.sin(endAngle);
  80932. var x1 = c1 * rx + cx;
  80933. var y1 = s1 * ry + cy;
  80934. var x4 = c2 * rx + cx;
  80935. var y4 = s2 * ry + cy;
  80936. var hx = rx * len * dir;
  80937. var hy = ry * len * dir;
  80938. currentSubpath.push(x1 - hx * s1, y1 + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4);
  80939. }
  80940. var x1;
  80941. var y1;
  80942. var x2;
  80943. var y2;
  80944. for (var i = 0; i < len;) {
  80945. var cmd = data[i++];
  80946. var isFirst = i === 1;
  80947. if (isFirst) {
  80948. xi = data[i];
  80949. yi = data[i + 1];
  80950. x0 = xi;
  80951. y0 = yi;
  80952. if (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) {
  80953. currentSubpath = [x0, y0];
  80954. }
  80955. }
  80956. switch (cmd) {
  80957. case CMD$4.M:
  80958. xi = x0 = data[i++];
  80959. yi = y0 = data[i++];
  80960. createNewSubpath(x0, y0);
  80961. break;
  80962. case CMD$4.L:
  80963. x1 = data[i++];
  80964. y1 = data[i++];
  80965. addLine(xi, yi, x1, y1);
  80966. xi = x1;
  80967. yi = y1;
  80968. break;
  80969. case CMD$4.C:
  80970. currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]);
  80971. break;
  80972. case CMD$4.Q:
  80973. x1 = data[i++];
  80974. y1 = data[i++];
  80975. x2 = data[i++];
  80976. y2 = data[i++];
  80977. currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2);
  80978. xi = x2;
  80979. yi = y2;
  80980. break;
  80981. case CMD$4.A:
  80982. var cx = data[i++];
  80983. var cy = data[i++];
  80984. var rx = data[i++];
  80985. var ry = data[i++];
  80986. var startAngle = data[i++];
  80987. var endAngle = data[i++] + startAngle;
  80988. i += 1;
  80989. var anticlockwise = !data[i++];
  80990. x1 = Math.cos(startAngle) * rx + cx;
  80991. y1 = Math.sin(startAngle) * ry + cy;
  80992. if (isFirst) {
  80993. x0 = x1;
  80994. y0 = y1;
  80995. createNewSubpath(x0, y0);
  80996. }
  80997. else {
  80998. addLine(xi, yi, x1, y1);
  80999. }
  81000. xi = Math.cos(endAngle) * rx + cx;
  81001. yi = Math.sin(endAngle) * ry + cy;
  81002. var step = (anticlockwise ? -1 : 1) * Math.PI / 2;
  81003. for (var angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step) {
  81004. var nextAngle = anticlockwise ? Math.max(angle + step, endAngle)
  81005. : Math.min(angle + step, endAngle);
  81006. addArc(angle, nextAngle, cx, cy, rx, ry);
  81007. }
  81008. break;
  81009. case CMD$4.R:
  81010. x0 = xi = data[i++];
  81011. y0 = yi = data[i++];
  81012. x1 = x0 + data[i++];
  81013. y1 = y0 + data[i++];
  81014. createNewSubpath(x1, y0);
  81015. addLine(x1, y0, x1, y1);
  81016. addLine(x1, y1, x0, y1);
  81017. addLine(x0, y1, x0, y0);
  81018. addLine(x0, y0, x1, y0);
  81019. break;
  81020. case CMD$4.Z:
  81021. currentSubpath && addLine(xi, yi, x0, y0);
  81022. xi = x0;
  81023. yi = y0;
  81024. break;
  81025. }
  81026. }
  81027. if (currentSubpath && currentSubpath.length > 2) {
  81028. bezierArrayGroups.push(currentSubpath);
  81029. }
  81030. return bezierArrayGroups;
  81031. }
  81032. function adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, out, scale) {
  81033. if (aroundEqual(x0, x1) && aroundEqual(y0, y1) && aroundEqual(x2, x3) && aroundEqual(y2, y3)) {
  81034. out.push(x3, y3);
  81035. return;
  81036. }
  81037. var PIXEL_DISTANCE = 2 / scale;
  81038. var PIXEL_DISTANCE_SQR = PIXEL_DISTANCE * PIXEL_DISTANCE;
  81039. var dx = x3 - x0;
  81040. var dy = y3 - y0;
  81041. var d = Math.sqrt(dx * dx + dy * dy);
  81042. dx /= d;
  81043. dy /= d;
  81044. var dx1 = x1 - x0;
  81045. var dy1 = y1 - y0;
  81046. var dx2 = x2 - x3;
  81047. var dy2 = y2 - y3;
  81048. var cp1LenSqr = dx1 * dx1 + dy1 * dy1;
  81049. var cp2LenSqr = dx2 * dx2 + dy2 * dy2;
  81050. if (cp1LenSqr < PIXEL_DISTANCE_SQR && cp2LenSqr < PIXEL_DISTANCE_SQR) {
  81051. out.push(x3, y3);
  81052. return;
  81053. }
  81054. var projLen1 = dx * dx1 + dy * dy1;
  81055. var projLen2 = -dx * dx2 - dy * dy2;
  81056. var d1Sqr = cp1LenSqr - projLen1 * projLen1;
  81057. var d2Sqr = cp2LenSqr - projLen2 * projLen2;
  81058. if (d1Sqr < PIXEL_DISTANCE_SQR && projLen1 >= 0
  81059. && d2Sqr < PIXEL_DISTANCE_SQR && projLen2 >= 0) {
  81060. out.push(x3, y3);
  81061. return;
  81062. }
  81063. var tmpSegX = [];
  81064. var tmpSegY = [];
  81065. cubicSubdivide(x0, x1, x2, x3, 0.5, tmpSegX);
  81066. cubicSubdivide(y0, y1, y2, y3, 0.5, tmpSegY);
  81067. adpativeBezier(tmpSegX[0], tmpSegY[0], tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], tmpSegX[3], tmpSegY[3], out, scale);
  81068. adpativeBezier(tmpSegX[4], tmpSegY[4], tmpSegX[5], tmpSegY[5], tmpSegX[6], tmpSegY[6], tmpSegX[7], tmpSegY[7], out, scale);
  81069. }
  81070. function pathToPolygons(path, scale) {
  81071. var bezierArrayGroups = pathToBezierCurves(path);
  81072. var polygons = [];
  81073. scale = scale || 1;
  81074. for (var i = 0; i < bezierArrayGroups.length; i++) {
  81075. var beziers = bezierArrayGroups[i];
  81076. var polygon = [];
  81077. var x0 = beziers[0];
  81078. var y0 = beziers[1];
  81079. polygon.push(x0, y0);
  81080. for (var k = 2; k < beziers.length;) {
  81081. var x1 = beziers[k++];
  81082. var y1 = beziers[k++];
  81083. var x2 = beziers[k++];
  81084. var y2 = beziers[k++];
  81085. var x3 = beziers[k++];
  81086. var y3 = beziers[k++];
  81087. adpativeBezier(x0, y0, x1, y1, x2, y2, x3, y3, polygon, scale);
  81088. x0 = x3;
  81089. y0 = y3;
  81090. }
  81091. polygons.push(polygon);
  81092. }
  81093. return polygons;
  81094. }
  81095. function getDividingGrids(dimSize, rowDim, count) {
  81096. var rowSize = dimSize[rowDim];
  81097. var columnSize = dimSize[1 - rowDim];
  81098. var ratio = Math.abs(rowSize / columnSize);
  81099. var rowCount = Math.ceil(Math.sqrt(ratio * count));
  81100. var columnCount = Math.floor(count / rowCount);
  81101. if (columnCount === 0) {
  81102. columnCount = 1;
  81103. rowCount = count;
  81104. }
  81105. var grids = [];
  81106. for (var i = 0; i < rowCount; i++) {
  81107. grids.push(columnCount);
  81108. }
  81109. var currentCount = rowCount * columnCount;
  81110. var remained = count - currentCount;
  81111. if (remained > 0) {
  81112. for (var i = 0; i < remained; i++) {
  81113. grids[i % rowCount] += 1;
  81114. }
  81115. }
  81116. return grids;
  81117. }
  81118. function divideSector(sectorShape, count, outShapes) {
  81119. var r0 = sectorShape.r0;
  81120. var r = sectorShape.r;
  81121. var startAngle = sectorShape.startAngle;
  81122. var endAngle = sectorShape.endAngle;
  81123. var angle = Math.abs(endAngle - startAngle);
  81124. var arcLen = angle * r;
  81125. var deltaR = r - r0;
  81126. var isAngleRow = arcLen > Math.abs(deltaR);
  81127. var grids = getDividingGrids([arcLen, deltaR], isAngleRow ? 0 : 1, count);
  81128. var rowSize = (isAngleRow ? angle : deltaR) / grids.length;
  81129. for (var row = 0; row < grids.length; row++) {
  81130. var columnSize = (isAngleRow ? deltaR : angle) / grids[row];
  81131. for (var column = 0; column < grids[row]; column++) {
  81132. var newShape = {};
  81133. if (isAngleRow) {
  81134. newShape.startAngle = startAngle + rowSize * row;
  81135. newShape.endAngle = startAngle + rowSize * (row + 1);
  81136. newShape.r0 = r0 + columnSize * column;
  81137. newShape.r = r0 + columnSize * (column + 1);
  81138. }
  81139. else {
  81140. newShape.startAngle = startAngle + columnSize * column;
  81141. newShape.endAngle = startAngle + columnSize * (column + 1);
  81142. newShape.r0 = r0 + rowSize * row;
  81143. newShape.r = r0 + rowSize * (row + 1);
  81144. }
  81145. newShape.clockwise = sectorShape.clockwise;
  81146. newShape.cx = sectorShape.cx;
  81147. newShape.cy = sectorShape.cy;
  81148. outShapes.push(newShape);
  81149. }
  81150. }
  81151. }
  81152. function divideRect(rectShape, count, outShapes) {
  81153. var width = rectShape.width;
  81154. var height = rectShape.height;
  81155. var isHorizontalRow = width > height;
  81156. var grids = getDividingGrids([width, height], isHorizontalRow ? 0 : 1, count);
  81157. var rowSizeDim = isHorizontalRow ? 'width' : 'height';
  81158. var columnSizeDim = isHorizontalRow ? 'height' : 'width';
  81159. var rowDim = isHorizontalRow ? 'x' : 'y';
  81160. var columnDim = isHorizontalRow ? 'y' : 'x';
  81161. var rowSize = rectShape[rowSizeDim] / grids.length;
  81162. for (var row = 0; row < grids.length; row++) {
  81163. var columnSize = rectShape[columnSizeDim] / grids[row];
  81164. for (var column = 0; column < grids[row]; column++) {
  81165. var newShape = {};
  81166. newShape[rowDim] = row * rowSize;
  81167. newShape[columnDim] = column * columnSize;
  81168. newShape[rowSizeDim] = rowSize;
  81169. newShape[columnSizeDim] = columnSize;
  81170. newShape.x += rectShape.x;
  81171. newShape.y += rectShape.y;
  81172. outShapes.push(newShape);
  81173. }
  81174. }
  81175. }
  81176. function crossProduct2d$1(x1, y1, x2, y2) {
  81177. return x1 * y2 - x2 * y1;
  81178. }
  81179. function lineLineIntersect$1(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  81180. var mx = a2x - a1x;
  81181. var my = a2y - a1y;
  81182. var nx = b2x - b1x;
  81183. var ny = b2y - b1y;
  81184. var nmCrossProduct = crossProduct2d$1(nx, ny, mx, my);
  81185. if (Math.abs(nmCrossProduct) < 1e-6) {
  81186. return null;
  81187. }
  81188. var b1a1x = a1x - b1x;
  81189. var b1a1y = a1y - b1y;
  81190. var p = crossProduct2d$1(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  81191. if (p < 0 || p > 1) {
  81192. return null;
  81193. }
  81194. return new Point(p * mx + a1x, p * my + a1y);
  81195. }
  81196. function projPtOnLine(pt, lineA, lineB) {
  81197. var dir = new Point();
  81198. Point.sub(dir, lineB, lineA);
  81199. dir.normalize();
  81200. var dir2 = new Point();
  81201. Point.sub(dir2, pt, lineA);
  81202. var len = dir2.dot(dir);
  81203. return len;
  81204. }
  81205. function addToPoly(poly, pt) {
  81206. var last = poly[poly.length - 1];
  81207. if (last && last[0] === pt[0] && last[1] === pt[1]) {
  81208. return;
  81209. }
  81210. poly.push(pt);
  81211. }
  81212. function splitPolygonByLine(points, lineA, lineB) {
  81213. var len = points.length;
  81214. var intersections = [];
  81215. for (var i = 0; i < len; i++) {
  81216. var p0 = points[i];
  81217. var p1 = points[(i + 1) % len];
  81218. var intersectionPt = lineLineIntersect$1(p0[0], p0[1], p1[0], p1[1], lineA.x, lineA.y, lineB.x, lineB.y);
  81219. if (intersectionPt) {
  81220. intersections.push({
  81221. projPt: projPtOnLine(intersectionPt, lineA, lineB),
  81222. pt: intersectionPt,
  81223. idx: i
  81224. });
  81225. }
  81226. }
  81227. if (intersections.length < 2) {
  81228. return [{ points: points }, { points: points }];
  81229. }
  81230. intersections.sort(function (a, b) {
  81231. return a.projPt - b.projPt;
  81232. });
  81233. var splitPt0 = intersections[0];
  81234. var splitPt1 = intersections[intersections.length - 1];
  81235. if (splitPt1.idx < splitPt0.idx) {
  81236. var tmp = splitPt0;
  81237. splitPt0 = splitPt1;
  81238. splitPt1 = tmp;
  81239. }
  81240. var splitPt0Arr = [splitPt0.pt.x, splitPt0.pt.y];
  81241. var splitPt1Arr = [splitPt1.pt.x, splitPt1.pt.y];
  81242. var newPolyA = [splitPt0Arr];
  81243. var newPolyB = [splitPt1Arr];
  81244. for (var i = splitPt0.idx + 1; i <= splitPt1.idx; i++) {
  81245. addToPoly(newPolyA, points[i].slice());
  81246. }
  81247. addToPoly(newPolyA, splitPt1Arr);
  81248. addToPoly(newPolyA, splitPt0Arr);
  81249. for (var i = splitPt1.idx + 1; i <= splitPt0.idx + len; i++) {
  81250. addToPoly(newPolyB, points[i % len].slice());
  81251. }
  81252. addToPoly(newPolyB, splitPt0Arr);
  81253. addToPoly(newPolyB, splitPt1Arr);
  81254. return [{
  81255. points: newPolyA
  81256. }, {
  81257. points: newPolyB
  81258. }];
  81259. }
  81260. function binaryDividePolygon(polygonShape) {
  81261. var points = polygonShape.points;
  81262. var min = [];
  81263. var max = [];
  81264. fromPoints(points, min, max);
  81265. var boundingRect = new BoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  81266. var width = boundingRect.width;
  81267. var height = boundingRect.height;
  81268. var x = boundingRect.x;
  81269. var y = boundingRect.y;
  81270. var pt0 = new Point();
  81271. var pt1 = new Point();
  81272. if (width > height) {
  81273. pt0.x = pt1.x = x + width / 2;
  81274. pt0.y = y;
  81275. pt1.y = y + height;
  81276. }
  81277. else {
  81278. pt0.y = pt1.y = y + height / 2;
  81279. pt0.x = x;
  81280. pt1.x = x + width;
  81281. }
  81282. return splitPolygonByLine(points, pt0, pt1);
  81283. }
  81284. function binaryDivideRecursive(divider, shape, count, out) {
  81285. if (count === 1) {
  81286. out.push(shape);
  81287. }
  81288. else {
  81289. var mid = Math.floor(count / 2);
  81290. var sub = divider(shape);
  81291. binaryDivideRecursive(divider, sub[0], mid, out);
  81292. binaryDivideRecursive(divider, sub[1], count - mid, out);
  81293. }
  81294. return out;
  81295. }
  81296. function clone$4(path, count) {
  81297. var paths = [];
  81298. for (var i = 0; i < count; i++) {
  81299. paths.push(clonePath(path));
  81300. }
  81301. return paths;
  81302. }
  81303. function copyPathProps(source, target) {
  81304. target.setStyle(source.style);
  81305. target.z = source.z;
  81306. target.z2 = source.z2;
  81307. target.zlevel = source.zlevel;
  81308. }
  81309. function polygonConvert(points) {
  81310. var out = [];
  81311. for (var i = 0; i < points.length;) {
  81312. out.push([points[i++], points[i++]]);
  81313. }
  81314. return out;
  81315. }
  81316. function split(path, count) {
  81317. var outShapes = [];
  81318. var shape = path.shape;
  81319. var OutShapeCtor;
  81320. switch (path.type) {
  81321. case 'rect':
  81322. divideRect(shape, count, outShapes);
  81323. OutShapeCtor = Rect;
  81324. break;
  81325. case 'sector':
  81326. divideSector(shape, count, outShapes);
  81327. OutShapeCtor = Sector;
  81328. break;
  81329. case 'circle':
  81330. divideSector({
  81331. r0: 0, r: shape.r, startAngle: 0, endAngle: Math.PI * 2,
  81332. cx: shape.cx, cy: shape.cy
  81333. }, count, outShapes);
  81334. OutShapeCtor = Sector;
  81335. break;
  81336. default:
  81337. var m = path.getComputedTransform();
  81338. var scale = m ? Math.sqrt(Math.max(m[0] * m[0] + m[1] * m[1], m[2] * m[2] + m[3] * m[3])) : 1;
  81339. var polygons = map(pathToPolygons(path.getUpdatedPathProxy(), scale), function (poly) { return polygonConvert(poly); });
  81340. var polygonCount = polygons.length;
  81341. if (polygonCount === 0) {
  81342. binaryDivideRecursive(binaryDividePolygon, {
  81343. points: polygons[0]
  81344. }, count, outShapes);
  81345. }
  81346. else if (polygonCount === count) {
  81347. for (var i = 0; i < polygonCount; i++) {
  81348. outShapes.push({
  81349. points: polygons[i]
  81350. });
  81351. }
  81352. }
  81353. else {
  81354. var totalArea_1 = 0;
  81355. var items = map(polygons, function (poly) {
  81356. var min = [];
  81357. var max = [];
  81358. fromPoints(poly, min, max);
  81359. var area = (max[1] - min[1]) * (max[0] - min[0]);
  81360. totalArea_1 += area;
  81361. return { poly: poly, area: area };
  81362. });
  81363. items.sort(function (a, b) { return b.area - a.area; });
  81364. var left = count;
  81365. for (var i = 0; i < polygonCount; i++) {
  81366. var item = items[i];
  81367. if (left <= 0) {
  81368. break;
  81369. }
  81370. var selfCount = i === polygonCount - 1
  81371. ? left
  81372. : Math.ceil(item.area / totalArea_1 * count);
  81373. if (selfCount < 0) {
  81374. continue;
  81375. }
  81376. binaryDivideRecursive(binaryDividePolygon, {
  81377. points: item.poly
  81378. }, selfCount, outShapes);
  81379. left -= selfCount;
  81380. }
  81381. }
  81382. OutShapeCtor = Polygon;
  81383. break;
  81384. }
  81385. if (!OutShapeCtor) {
  81386. return clone$4(path, count);
  81387. }
  81388. var out = [];
  81389. for (var i = 0; i < outShapes.length; i++) {
  81390. var subPath = new OutShapeCtor();
  81391. subPath.setShape(outShapes[i]);
  81392. copyPathProps(path, subPath);
  81393. out.push(subPath);
  81394. }
  81395. return out;
  81396. }
  81397. function alignSubpath(subpath1, subpath2) {
  81398. var len1 = subpath1.length;
  81399. var len2 = subpath2.length;
  81400. if (len1 === len2) {
  81401. return [subpath1, subpath2];
  81402. }
  81403. var tmpSegX = [];
  81404. var tmpSegY = [];
  81405. var shorterPath = len1 < len2 ? subpath1 : subpath2;
  81406. var shorterLen = Math.min(len1, len2);
  81407. var diff = Math.abs(len2 - len1) / 6;
  81408. var shorterBezierCount = (shorterLen - 2) / 6;
  81409. var eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
  81410. var newSubpath = [shorterPath[0], shorterPath[1]];
  81411. var remained = diff;
  81412. for (var i = 2; i < shorterLen;) {
  81413. var x0 = shorterPath[i - 2];
  81414. var y0 = shorterPath[i - 1];
  81415. var x1 = shorterPath[i++];
  81416. var y1 = shorterPath[i++];
  81417. var x2 = shorterPath[i++];
  81418. var y2 = shorterPath[i++];
  81419. var x3 = shorterPath[i++];
  81420. var y3 = shorterPath[i++];
  81421. if (remained <= 0) {
  81422. newSubpath.push(x1, y1, x2, y2, x3, y3);
  81423. continue;
  81424. }
  81425. var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
  81426. for (var k = 1; k <= actualSubDivCount; k++) {
  81427. var p = k / actualSubDivCount;
  81428. cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
  81429. cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
  81430. x0 = tmpSegX[3];
  81431. y0 = tmpSegY[3];
  81432. newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
  81433. x1 = tmpSegX[5];
  81434. y1 = tmpSegY[5];
  81435. x2 = tmpSegX[6];
  81436. y2 = tmpSegY[6];
  81437. }
  81438. remained -= actualSubDivCount - 1;
  81439. }
  81440. return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
  81441. }
  81442. function createSubpath(lastSubpathSubpath, otherSubpath) {
  81443. var len = lastSubpathSubpath.length;
  81444. var lastX = lastSubpathSubpath[len - 2];
  81445. var lastY = lastSubpathSubpath[len - 1];
  81446. var newSubpath = [];
  81447. for (var i = 0; i < otherSubpath.length;) {
  81448. newSubpath[i++] = lastX;
  81449. newSubpath[i++] = lastY;
  81450. }
  81451. return newSubpath;
  81452. }
  81453. function alignBezierCurves(array1, array2) {
  81454. var _a;
  81455. var lastSubpath1;
  81456. var lastSubpath2;
  81457. var newArray1 = [];
  81458. var newArray2 = [];
  81459. for (var i = 0; i < Math.max(array1.length, array2.length); i++) {
  81460. var subpath1 = array1[i];
  81461. var subpath2 = array2[i];
  81462. var newSubpath1 = void 0;
  81463. var newSubpath2 = void 0;
  81464. if (!subpath1) {
  81465. newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
  81466. newSubpath2 = subpath2;
  81467. }
  81468. else if (!subpath2) {
  81469. newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
  81470. newSubpath1 = subpath1;
  81471. }
  81472. else {
  81473. _a = alignSubpath(subpath1, subpath2), newSubpath1 = _a[0], newSubpath2 = _a[1];
  81474. lastSubpath1 = newSubpath1;
  81475. lastSubpath2 = newSubpath2;
  81476. }
  81477. newArray1.push(newSubpath1);
  81478. newArray2.push(newSubpath2);
  81479. }
  81480. return [newArray1, newArray2];
  81481. }
  81482. function centroid$1(array) {
  81483. var signedArea = 0;
  81484. var cx = 0;
  81485. var cy = 0;
  81486. var len = array.length;
  81487. for (var i = 0, j = len - 2; i < len; j = i, i += 2) {
  81488. var x0 = array[j];
  81489. var y0 = array[j + 1];
  81490. var x1 = array[i];
  81491. var y1 = array[i + 1];
  81492. var a = x0 * y1 - x1 * y0;
  81493. signedArea += a;
  81494. cx += (x0 + x1) * a;
  81495. cy += (y0 + y1) * a;
  81496. }
  81497. if (signedArea === 0) {
  81498. return [array[0] || 0, array[1] || 0];
  81499. }
  81500. return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
  81501. }
  81502. function findBestRingOffset(fromSubBeziers, toSubBeziers, fromCp, toCp) {
  81503. var bezierCount = (fromSubBeziers.length - 2) / 6;
  81504. var bestScore = Infinity;
  81505. var bestOffset = 0;
  81506. var len = fromSubBeziers.length;
  81507. var len2 = len - 2;
  81508. for (var offset = 0; offset < bezierCount; offset++) {
  81509. var cursorOffset = offset * 6;
  81510. var score = 0;
  81511. for (var k = 0; k < len; k += 2) {
  81512. var idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
  81513. var x0 = fromSubBeziers[idx] - fromCp[0];
  81514. var y0 = fromSubBeziers[idx + 1] - fromCp[1];
  81515. var x1 = toSubBeziers[k] - toCp[0];
  81516. var y1 = toSubBeziers[k + 1] - toCp[1];
  81517. var dx = x1 - x0;
  81518. var dy = y1 - y0;
  81519. score += dx * dx + dy * dy;
  81520. }
  81521. if (score < bestScore) {
  81522. bestScore = score;
  81523. bestOffset = offset;
  81524. }
  81525. }
  81526. return bestOffset;
  81527. }
  81528. function reverse(array) {
  81529. var newArr = [];
  81530. var len = array.length;
  81531. for (var i = 0; i < len; i += 2) {
  81532. newArr[i] = array[len - i - 2];
  81533. newArr[i + 1] = array[len - i - 1];
  81534. }
  81535. return newArr;
  81536. }
  81537. function findBestMorphingRotation(fromArr, toArr, searchAngleIteration, searchAngleRange) {
  81538. var result = [];
  81539. var fromNeedsReverse;
  81540. for (var i = 0; i < fromArr.length; i++) {
  81541. var fromSubpathBezier = fromArr[i];
  81542. var toSubpathBezier = toArr[i];
  81543. var fromCp = centroid$1(fromSubpathBezier);
  81544. var toCp = centroid$1(toSubpathBezier);
  81545. if (fromNeedsReverse == null) {
  81546. fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
  81547. }
  81548. var newFromSubpathBezier = [];
  81549. var newToSubpathBezier = [];
  81550. var bestAngle = 0;
  81551. var bestScore = Infinity;
  81552. var tmpArr = [];
  81553. var len = fromSubpathBezier.length;
  81554. if (fromNeedsReverse) {
  81555. fromSubpathBezier = reverse(fromSubpathBezier);
  81556. }
  81557. var offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
  81558. var len2 = len - 2;
  81559. for (var k = 0; k < len2; k += 2) {
  81560. var idx = (offset + k) % len2 + 2;
  81561. newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
  81562. newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
  81563. }
  81564. newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
  81565. newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
  81566. if (searchAngleIteration > 0) {
  81567. var step = searchAngleRange / searchAngleIteration;
  81568. for (var angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
  81569. var sa = Math.sin(angle);
  81570. var ca = Math.cos(angle);
  81571. var score = 0;
  81572. for (var k = 0; k < fromSubpathBezier.length; k += 2) {
  81573. var x0 = newFromSubpathBezier[k];
  81574. var y0 = newFromSubpathBezier[k + 1];
  81575. var x1 = toSubpathBezier[k] - toCp[0];
  81576. var y1 = toSubpathBezier[k + 1] - toCp[1];
  81577. var newX1 = x1 * ca - y1 * sa;
  81578. var newY1 = x1 * sa + y1 * ca;
  81579. tmpArr[k] = newX1;
  81580. tmpArr[k + 1] = newY1;
  81581. var dx = newX1 - x0;
  81582. var dy = newY1 - y0;
  81583. score += dx * dx + dy * dy;
  81584. }
  81585. if (score < bestScore) {
  81586. bestScore = score;
  81587. bestAngle = angle;
  81588. for (var m = 0; m < tmpArr.length; m++) {
  81589. newToSubpathBezier[m] = tmpArr[m];
  81590. }
  81591. }
  81592. }
  81593. }
  81594. else {
  81595. for (var i_1 = 0; i_1 < len; i_1 += 2) {
  81596. newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0];
  81597. newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1];
  81598. }
  81599. }
  81600. result.push({
  81601. from: newFromSubpathBezier,
  81602. to: newToSubpathBezier,
  81603. fromCp: fromCp,
  81604. toCp: toCp,
  81605. rotation: -bestAngle
  81606. });
  81607. }
  81608. return result;
  81609. }
  81610. function isCombineMorphing(path) {
  81611. return path.__isCombineMorphing;
  81612. }
  81613. var SAVED_METHOD_PREFIX = '__mOriginal_';
  81614. function saveAndModifyMethod(obj, methodName, modifiers) {
  81615. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81616. var originalMethod = obj[savedMethodName] || obj[methodName];
  81617. if (!obj[savedMethodName]) {
  81618. obj[savedMethodName] = obj[methodName];
  81619. }
  81620. var replace = modifiers.replace;
  81621. var after = modifiers.after;
  81622. var before = modifiers.before;
  81623. obj[methodName] = function () {
  81624. var args = arguments;
  81625. var res;
  81626. before && before.apply(this, args);
  81627. if (replace) {
  81628. res = replace.apply(this, args);
  81629. }
  81630. else {
  81631. res = originalMethod.apply(this, args);
  81632. }
  81633. after && after.apply(this, args);
  81634. return res;
  81635. };
  81636. }
  81637. function restoreMethod(obj, methodName) {
  81638. var savedMethodName = SAVED_METHOD_PREFIX + methodName;
  81639. if (obj[savedMethodName]) {
  81640. obj[methodName] = obj[savedMethodName];
  81641. obj[savedMethodName] = null;
  81642. }
  81643. }
  81644. function applyTransformOnBeziers(bezierCurves, mm) {
  81645. for (var i = 0; i < bezierCurves.length; i++) {
  81646. var subBeziers = bezierCurves[i];
  81647. for (var k = 0; k < subBeziers.length;) {
  81648. var x = subBeziers[k];
  81649. var y = subBeziers[k + 1];
  81650. subBeziers[k++] = mm[0] * x + mm[2] * y + mm[4];
  81651. subBeziers[k++] = mm[1] * x + mm[3] * y + mm[5];
  81652. }
  81653. }
  81654. }
  81655. function prepareMorphPath(fromPath, toPath) {
  81656. var fromPathProxy = fromPath.getUpdatedPathProxy();
  81657. var toPathProxy = toPath.getUpdatedPathProxy();
  81658. var _a = alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)), fromBezierCurves = _a[0], toBezierCurves = _a[1];
  81659. var fromPathTransform = fromPath.getComputedTransform();
  81660. var toPathTransform = toPath.getComputedTransform();
  81661. function updateIdentityTransform() {
  81662. this.transform = null;
  81663. }
  81664. fromPathTransform && applyTransformOnBeziers(fromBezierCurves, fromPathTransform);
  81665. toPathTransform && applyTransformOnBeziers(toBezierCurves, toPathTransform);
  81666. saveAndModifyMethod(toPath, 'updateTransform', { replace: updateIdentityTransform });
  81667. toPath.transform = null;
  81668. var morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
  81669. var tmpArr = [];
  81670. saveAndModifyMethod(toPath, 'buildPath', { replace: function (path) {
  81671. var t = toPath.__morphT;
  81672. var onet = 1 - t;
  81673. var newCp = [];
  81674. for (var i = 0; i < morphingData.length; i++) {
  81675. var item = morphingData[i];
  81676. var from = item.from;
  81677. var to = item.to;
  81678. var angle = item.rotation * t;
  81679. var fromCp = item.fromCp;
  81680. var toCp = item.toCp;
  81681. var sa = Math.sin(angle);
  81682. var ca = Math.cos(angle);
  81683. lerp(newCp, fromCp, toCp, t);
  81684. for (var m = 0; m < from.length; m += 2) {
  81685. var x0_1 = from[m];
  81686. var y0_1 = from[m + 1];
  81687. var x1 = to[m];
  81688. var y1 = to[m + 1];
  81689. var x = x0_1 * onet + x1 * t;
  81690. var y = y0_1 * onet + y1 * t;
  81691. tmpArr[m] = (x * ca - y * sa) + newCp[0];
  81692. tmpArr[m + 1] = (x * sa + y * ca) + newCp[1];
  81693. }
  81694. var x0 = tmpArr[0];
  81695. var y0 = tmpArr[1];
  81696. path.moveTo(x0, y0);
  81697. for (var m = 2; m < from.length;) {
  81698. var x1 = tmpArr[m++];
  81699. var y1 = tmpArr[m++];
  81700. var x2 = tmpArr[m++];
  81701. var y2 = tmpArr[m++];
  81702. var x3 = tmpArr[m++];
  81703. var y3 = tmpArr[m++];
  81704. if (x0 === x1 && y0 === y1 && x2 === x3 && y2 === y3) {
  81705. path.lineTo(x3, y3);
  81706. }
  81707. else {
  81708. path.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  81709. }
  81710. x0 = x3;
  81711. y0 = y3;
  81712. }
  81713. }
  81714. } });
  81715. }
  81716. function morphPath(fromPath, toPath, animationOpts) {
  81717. if (!fromPath || !toPath) {
  81718. return toPath;
  81719. }
  81720. var oldDone = animationOpts.done;
  81721. var oldDuring = animationOpts.during;
  81722. prepareMorphPath(fromPath, toPath);
  81723. toPath.__morphT = 0;
  81724. function restoreToPath() {
  81725. restoreMethod(toPath, 'buildPath');
  81726. restoreMethod(toPath, 'updateTransform');
  81727. toPath.__morphT = -1;
  81728. toPath.createPathProxy();
  81729. toPath.dirtyShape();
  81730. }
  81731. toPath.animateTo({
  81732. __morphT: 1
  81733. }, defaults({
  81734. during: function (p) {
  81735. toPath.dirtyShape();
  81736. oldDuring && oldDuring(p);
  81737. },
  81738. done: function () {
  81739. restoreToPath();
  81740. oldDone && oldDone();
  81741. }
  81742. }, animationOpts));
  81743. return toPath;
  81744. }
  81745. function hilbert(x, y, minX, minY, maxX, maxY) {
  81746. var bits = 16;
  81747. x = (maxX === minX) ? 0 : Math.round(32767 * (x - minX) / (maxX - minX));
  81748. y = (maxY === minY) ? 0 : Math.round(32767 * (y - minY) / (maxY - minY));
  81749. var d = 0;
  81750. var tmp;
  81751. for (var s = (1 << bits) / 2; s > 0; s /= 2) {
  81752. var rx = 0;
  81753. var ry = 0;
  81754. if ((x & s) > 0) {
  81755. rx = 1;
  81756. }
  81757. if ((y & s) > 0) {
  81758. ry = 1;
  81759. }
  81760. d += s * s * ((3 * rx) ^ ry);
  81761. if (ry === 0) {
  81762. if (rx === 1) {
  81763. x = s - 1 - x;
  81764. y = s - 1 - y;
  81765. }
  81766. tmp = x;
  81767. x = y;
  81768. y = tmp;
  81769. }
  81770. }
  81771. return d;
  81772. }
  81773. function sortPaths(pathList) {
  81774. var xMin = Infinity;
  81775. var yMin = Infinity;
  81776. var xMax = -Infinity;
  81777. var yMax = -Infinity;
  81778. var cps = map(pathList, function (path) {
  81779. var rect = path.getBoundingRect();
  81780. var m = path.getComputedTransform();
  81781. var x = rect.x + rect.width / 2 + (m ? m[4] : 0);
  81782. var y = rect.y + rect.height / 2 + (m ? m[5] : 0);
  81783. xMin = Math.min(x, xMin);
  81784. yMin = Math.min(y, yMin);
  81785. xMax = Math.max(x, xMax);
  81786. yMax = Math.max(y, yMax);
  81787. return [x, y];
  81788. });
  81789. var items = map(cps, function (cp, idx) {
  81790. return {
  81791. cp: cp,
  81792. z: hilbert(cp[0], cp[1], xMin, yMin, xMax, yMax),
  81793. path: pathList[idx]
  81794. };
  81795. });
  81796. return items.sort(function (a, b) { return a.z - b.z; }).map(function (item) { return item.path; });
  81797. }
  81798. function defaultDividePath(param) {
  81799. return split(param.path, param.count);
  81800. }
  81801. function createEmptyReturn() {
  81802. return {
  81803. fromIndividuals: [],
  81804. toIndividuals: [],
  81805. count: 0
  81806. };
  81807. }
  81808. function combineMorph(fromList, toPath, animationOpts) {
  81809. var fromPathList = [];
  81810. function addFromPath(fromList) {
  81811. for (var i = 0; i < fromList.length; i++) {
  81812. var from = fromList[i];
  81813. if (isCombineMorphing(from)) {
  81814. addFromPath(from.childrenRef());
  81815. }
  81816. else if (from instanceof Path) {
  81817. fromPathList.push(from);
  81818. }
  81819. }
  81820. }
  81821. addFromPath(fromList);
  81822. var separateCount = fromPathList.length;
  81823. if (!separateCount) {
  81824. return createEmptyReturn();
  81825. }
  81826. var dividePath = animationOpts.dividePath || defaultDividePath;
  81827. var toSubPathList = dividePath({
  81828. path: toPath, count: separateCount
  81829. });
  81830. if (toSubPathList.length !== separateCount) {
  81831. console.error('Invalid morphing: unmatched splitted path');
  81832. return createEmptyReturn();
  81833. }
  81834. fromPathList = sortPaths(fromPathList);
  81835. toSubPathList = sortPaths(toSubPathList);
  81836. var oldDone = animationOpts.done;
  81837. var oldDuring = animationOpts.during;
  81838. var individualDelay = animationOpts.individualDelay;
  81839. var identityTransform = new Transformable();
  81840. for (var i = 0; i < separateCount; i++) {
  81841. var from = fromPathList[i];
  81842. var to = toSubPathList[i];
  81843. to.parent = toPath;
  81844. to.copyTransform(identityTransform);
  81845. if (!individualDelay) {
  81846. prepareMorphPath(from, to);
  81847. }
  81848. }
  81849. toPath.__isCombineMorphing = true;
  81850. toPath.childrenRef = function () {
  81851. return toSubPathList;
  81852. };
  81853. function addToSubPathListToZr(zr) {
  81854. for (var i = 0; i < toSubPathList.length; i++) {
  81855. toSubPathList[i].addSelfToZr(zr);
  81856. }
  81857. }
  81858. saveAndModifyMethod(toPath, 'addSelfToZr', {
  81859. after: function (zr) {
  81860. addToSubPathListToZr(zr);
  81861. }
  81862. });
  81863. saveAndModifyMethod(toPath, 'removeSelfFromZr', {
  81864. after: function (zr) {
  81865. for (var i = 0; i < toSubPathList.length; i++) {
  81866. toSubPathList[i].removeSelfFromZr(zr);
  81867. }
  81868. }
  81869. });
  81870. function restoreToPath() {
  81871. toPath.__isCombineMorphing = false;
  81872. toPath.__morphT = -1;
  81873. toPath.childrenRef = null;
  81874. restoreMethod(toPath, 'addSelfToZr');
  81875. restoreMethod(toPath, 'removeSelfFromZr');
  81876. }
  81877. var toLen = toSubPathList.length;
  81878. if (individualDelay) {
  81879. var animating_1 = toLen;
  81880. var eachDone = function () {
  81881. animating_1--;
  81882. if (animating_1 === 0) {
  81883. restoreToPath();
  81884. oldDone && oldDone();
  81885. }
  81886. };
  81887. for (var i = 0; i < toLen; i++) {
  81888. var indivdualAnimationOpts = individualDelay ? defaults({
  81889. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toSubPathList[i]),
  81890. done: eachDone
  81891. }, animationOpts) : animationOpts;
  81892. morphPath(fromPathList[i], toSubPathList[i], indivdualAnimationOpts);
  81893. }
  81894. }
  81895. else {
  81896. toPath.__morphT = 0;
  81897. toPath.animateTo({
  81898. __morphT: 1
  81899. }, defaults({
  81900. during: function (p) {
  81901. for (var i = 0; i < toLen; i++) {
  81902. var child = toSubPathList[i];
  81903. child.__morphT = toPath.__morphT;
  81904. child.dirtyShape();
  81905. }
  81906. oldDuring && oldDuring(p);
  81907. },
  81908. done: function () {
  81909. restoreToPath();
  81910. for (var i = 0; i < fromList.length; i++) {
  81911. restoreMethod(fromList[i], 'updateTransform');
  81912. }
  81913. oldDone && oldDone();
  81914. }
  81915. }, animationOpts));
  81916. }
  81917. if (toPath.__zr) {
  81918. addToSubPathListToZr(toPath.__zr);
  81919. }
  81920. return {
  81921. fromIndividuals: fromPathList,
  81922. toIndividuals: toSubPathList,
  81923. count: toLen
  81924. };
  81925. }
  81926. function separateMorph(fromPath, toPathList, animationOpts) {
  81927. var toLen = toPathList.length;
  81928. var fromPathList = [];
  81929. var dividePath = animationOpts.dividePath || defaultDividePath;
  81930. function addFromPath(fromList) {
  81931. for (var i = 0; i < fromList.length; i++) {
  81932. var from = fromList[i];
  81933. if (isCombineMorphing(from)) {
  81934. addFromPath(from.childrenRef());
  81935. }
  81936. else if (from instanceof Path) {
  81937. fromPathList.push(from);
  81938. }
  81939. }
  81940. }
  81941. if (isCombineMorphing(fromPath)) {
  81942. addFromPath(fromPath.childrenRef());
  81943. var fromLen = fromPathList.length;
  81944. if (fromLen < toLen) {
  81945. var k = 0;
  81946. for (var i = fromLen; i < toLen; i++) {
  81947. fromPathList.push(clonePath(fromPathList[k++ % fromLen]));
  81948. }
  81949. }
  81950. fromPathList.length = toLen;
  81951. }
  81952. else {
  81953. fromPathList = dividePath({ path: fromPath, count: toLen });
  81954. var fromPathTransform = fromPath.getComputedTransform();
  81955. for (var i = 0; i < fromPathList.length; i++) {
  81956. fromPathList[i].setLocalTransform(fromPathTransform);
  81957. }
  81958. if (fromPathList.length !== toLen) {
  81959. console.error('Invalid morphing: unmatched splitted path');
  81960. return createEmptyReturn();
  81961. }
  81962. }
  81963. fromPathList = sortPaths(fromPathList);
  81964. toPathList = sortPaths(toPathList);
  81965. var individualDelay = animationOpts.individualDelay;
  81966. for (var i = 0; i < toLen; i++) {
  81967. var indivdualAnimationOpts = individualDelay ? defaults({
  81968. delay: (animationOpts.delay || 0) + individualDelay(i, toLen, fromPathList[i], toPathList[i])
  81969. }, animationOpts) : animationOpts;
  81970. morphPath(fromPathList[i], toPathList[i], indivdualAnimationOpts);
  81971. }
  81972. return {
  81973. fromIndividuals: fromPathList,
  81974. toIndividuals: toPathList,
  81975. count: toPathList.length
  81976. };
  81977. }
  81978. function isMultiple(elements) {
  81979. return isArray(elements[0]);
  81980. }
  81981. function prepareMorphBatches(one, many) {
  81982. var batches = [];
  81983. var batchCount = one.length;
  81984. for (var i = 0; i < batchCount; i++) {
  81985. batches.push({
  81986. one: one[i],
  81987. many: []
  81988. });
  81989. }
  81990. for (var i = 0; i < many.length; i++) {
  81991. var len = many[i].length;
  81992. var k = void 0;
  81993. for (k = 0; k < len; k++) {
  81994. batches[k % batchCount].many.push(many[i][k]);
  81995. }
  81996. }
  81997. var off = 0; // If one has more paths than each one of many. average them.
  81998. for (var i = batchCount - 1; i >= 0; i--) {
  81999. if (!batches[i].many.length) {
  82000. var moveFrom = batches[off].many;
  82001. if (moveFrom.length <= 1) {
  82002. // Not enough
  82003. // Start from the first one.
  82004. if (off) {
  82005. off = 0;
  82006. } else {
  82007. return batches;
  82008. }
  82009. }
  82010. var len = moveFrom.length;
  82011. var mid = Math.ceil(len / 2);
  82012. batches[i].many = moveFrom.slice(mid, len);
  82013. batches[off].many = moveFrom.slice(0, mid);
  82014. off++;
  82015. }
  82016. }
  82017. return batches;
  82018. }
  82019. var pathDividers = {
  82020. clone: function (params) {
  82021. var ret = []; // Fitting the alpha
  82022. var approxOpacity = 1 - Math.pow(1 - params.path.style.opacity, 1 / params.count);
  82023. for (var i = 0; i < params.count; i++) {
  82024. var cloned = clonePath(params.path);
  82025. cloned.setStyle('opacity', approxOpacity);
  82026. ret.push(cloned);
  82027. }
  82028. return ret;
  82029. },
  82030. // Use the default divider
  82031. split: null
  82032. };
  82033. function applyMorphAnimation(from, to, divideShape, seriesModel, dataIndex, animateOtherProps) {
  82034. if (!from.length || !to.length) {
  82035. return;
  82036. }
  82037. var updateAnimationCfg = getAnimationConfig('update', seriesModel, dataIndex);
  82038. if (!(updateAnimationCfg && updateAnimationCfg.duration > 0)) {
  82039. return;
  82040. }
  82041. var animationDelay = seriesModel.getModel('universalTransition').get('delay');
  82042. var animationCfg = Object.assign({
  82043. // Need to setToFinal so the further calculation based on the style can be correct.
  82044. // Like emphasis color.
  82045. setToFinal: true
  82046. }, updateAnimationCfg);
  82047. var many;
  82048. var one;
  82049. if (isMultiple(from)) {
  82050. // manyToOne
  82051. many = from;
  82052. one = to;
  82053. }
  82054. if (isMultiple(to)) {
  82055. // oneToMany
  82056. many = to;
  82057. one = from;
  82058. }
  82059. function morphOneBatch(batch, fromIsMany, animateIndex, animateCount, forceManyOne) {
  82060. var batchMany = batch.many;
  82061. var batchOne = batch.one;
  82062. if (batchMany.length === 1 && !forceManyOne) {
  82063. // Is one to one
  82064. var batchFrom = fromIsMany ? batchMany[0] : batchOne;
  82065. var batchTo = fromIsMany ? batchOne : batchMany[0];
  82066. if (isCombineMorphing(batchFrom)) {
  82067. // Keep doing combine animation.
  82068. morphOneBatch({
  82069. many: [batchFrom],
  82070. one: batchTo
  82071. }, true, animateIndex, animateCount, true);
  82072. } else {
  82073. var individualAnimationCfg = animationDelay ? defaults({
  82074. delay: animationDelay(animateIndex, animateCount)
  82075. }, animationCfg) : animationCfg;
  82076. morphPath(batchFrom, batchTo, individualAnimationCfg);
  82077. animateOtherProps(batchFrom, batchTo, batchFrom, batchTo, individualAnimationCfg);
  82078. }
  82079. } else {
  82080. var separateAnimationCfg = defaults({
  82081. dividePath: pathDividers[divideShape],
  82082. individualDelay: animationDelay && function (idx, count, fromPath, toPath) {
  82083. return animationDelay(idx + animateIndex, animateCount);
  82084. }
  82085. }, animationCfg);
  82086. var _a = fromIsMany ? combineMorph(batchMany, batchOne, separateAnimationCfg) : separateMorph(batchOne, batchMany, separateAnimationCfg),
  82087. fromIndividuals = _a.fromIndividuals,
  82088. toIndividuals = _a.toIndividuals;
  82089. var count = fromIndividuals.length;
  82090. for (var k = 0; k < count; k++) {
  82091. var individualAnimationCfg = animationDelay ? defaults({
  82092. delay: animationDelay(k, count)
  82093. }, animationCfg) : animationCfg;
  82094. animateOtherProps(fromIndividuals[k], toIndividuals[k], fromIsMany ? batchMany[k] : batch.one, fromIsMany ? batch.one : batchMany[k], individualAnimationCfg);
  82095. }
  82096. }
  82097. }
  82098. var fromIsMany = many ? many === from // Is one to one. If the path number not match. also needs do merge and separate morphing.
  82099. : from.length > to.length;
  82100. var morphBatches = many ? prepareMorphBatches(one, many) : prepareMorphBatches(fromIsMany ? to : from, [fromIsMany ? from : to]);
  82101. var animateCount = 0;
  82102. for (var i = 0; i < morphBatches.length; i++) {
  82103. animateCount += morphBatches[i].many.length;
  82104. }
  82105. var animateIndex = 0;
  82106. for (var i = 0; i < morphBatches.length; i++) {
  82107. morphOneBatch(morphBatches[i], fromIsMany, animateIndex, animateCount);
  82108. animateIndex += morphBatches[i].many.length;
  82109. }
  82110. }
  82111. function getPathList(elements) {
  82112. if (!elements) {
  82113. return [];
  82114. }
  82115. if (isArray(elements)) {
  82116. var pathList_1 = [];
  82117. for (var i = 0; i < elements.length; i++) {
  82118. pathList_1.push(getPathList(elements[i]));
  82119. }
  82120. return pathList_1;
  82121. }
  82122. var pathList = [];
  82123. elements.traverse(function (el) {
  82124. if (el instanceof Path && !el.disableMorphing && !el.invisible && !el.ignore) {
  82125. pathList.push(el);
  82126. }
  82127. });
  82128. return pathList;
  82129. }
  82130. var DATA_COUNT_THRESHOLD = 1e4;
  82131. var getUniversalTransitionGlobalStore = makeInner();
  82132. function getGroupIdDimension(data) {
  82133. var dimensions = data.dimensions;
  82134. for (var i = 0; i < dimensions.length; i++) {
  82135. var dimInfo = data.getDimensionInfo(dimensions[i]);
  82136. if (dimInfo && dimInfo.otherDims.itemGroupId === 0) {
  82137. return dimensions[i];
  82138. }
  82139. }
  82140. }
  82141. function flattenDataDiffItems(list) {
  82142. var items = [];
  82143. each(list, function (seriesInfo) {
  82144. var data = seriesInfo.data;
  82145. if (data.count() > DATA_COUNT_THRESHOLD) {
  82146. if ("development" !== 'production') {
  82147. warn('Universal transition is disabled on large data > 10k.');
  82148. }
  82149. return;
  82150. }
  82151. var indices = data.getIndices();
  82152. var groupDim = getGroupIdDimension(data);
  82153. for (var dataIndex = 0; dataIndex < indices.length; dataIndex++) {
  82154. items.push({
  82155. dataGroupId: seriesInfo.dataGroupId,
  82156. data: data,
  82157. dim: seriesInfo.dim || groupDim,
  82158. divide: seriesInfo.divide,
  82159. dataIndex: dataIndex
  82160. });
  82161. }
  82162. });
  82163. return items;
  82164. }
  82165. function fadeInElement(newEl, newSeries, newIndex) {
  82166. newEl.traverse(function (el) {
  82167. if (el instanceof Path) {
  82168. // TODO use fade in animation for target element.
  82169. initProps(el, {
  82170. style: {
  82171. opacity: 0
  82172. }
  82173. }, newSeries, {
  82174. dataIndex: newIndex,
  82175. isFrom: true
  82176. });
  82177. }
  82178. });
  82179. }
  82180. function removeEl$1(el) {
  82181. if (el.parent) {
  82182. // Bake parent transform to element.
  82183. // So it can still have proper transform to transition after it's removed.
  82184. var computedTransform = el.getComputedTransform();
  82185. el.setLocalTransform(computedTransform);
  82186. el.parent.remove(el);
  82187. }
  82188. }
  82189. function stopAnimation(el) {
  82190. el.stopAnimation();
  82191. if (el.isGroup) {
  82192. el.traverse(function (child) {
  82193. child.stopAnimation();
  82194. });
  82195. }
  82196. }
  82197. function animateElementStyles(el, dataIndex, seriesModel) {
  82198. var animationConfig = getAnimationConfig('update', seriesModel, dataIndex);
  82199. animationConfig && el.traverse(function (child) {
  82200. if (child instanceof Displayable) {
  82201. var oldStyle = getOldStyle(child);
  82202. if (oldStyle) {
  82203. child.animateFrom({
  82204. style: oldStyle
  82205. }, animationConfig);
  82206. }
  82207. }
  82208. });
  82209. }
  82210. function isAllIdSame(oldDiffItems, newDiffItems) {
  82211. var len = oldDiffItems.length;
  82212. if (len !== newDiffItems.length) {
  82213. return false;
  82214. }
  82215. for (var i = 0; i < len; i++) {
  82216. var oldItem = oldDiffItems[i];
  82217. var newItem = newDiffItems[i];
  82218. if (oldItem.data.getId(oldItem.dataIndex) !== newItem.data.getId(newItem.dataIndex)) {
  82219. return false;
  82220. }
  82221. }
  82222. return true;
  82223. }
  82224. function transitionBetween(oldList, newList, api) {
  82225. var oldDiffItems = flattenDataDiffItems(oldList);
  82226. var newDiffItems = flattenDataDiffItems(newList);
  82227. function updateMorphingPathProps(from, to, rawFrom, rawTo, animationCfg) {
  82228. if (rawFrom || from) {
  82229. to.animateFrom({
  82230. style: rawFrom && rawFrom !== from ? // dividingMethod like clone may override the style(opacity)
  82231. // So extend it to raw style.
  82232. extend(extend({}, rawFrom.style), from.style) : from.style
  82233. }, animationCfg);
  82234. }
  82235. }
  82236. function findKeyDim(items) {
  82237. for (var i = 0; i < items.length; i++) {
  82238. if (items[i].dim) {
  82239. return items[i].dim;
  82240. }
  82241. }
  82242. }
  82243. var oldKeyDim = findKeyDim(oldDiffItems);
  82244. var newKeyDim = findKeyDim(newDiffItems);
  82245. var hasMorphAnimation = false;
  82246. function createKeyGetter(isOld, onlyGetId) {
  82247. return function (diffItem) {
  82248. var data = diffItem.data;
  82249. var dataIndex = diffItem.dataIndex; // TODO if specified dim
  82250. if (onlyGetId) {
  82251. return data.getId(dataIndex);
  82252. } // Use group id as transition key by default.
  82253. // So we can achieve multiple to multiple animation like drilldown / up naturally.
  82254. // If group id not exits. Use id instead. If so, only one to one transition will be applied.
  82255. var dataGroupId = diffItem.dataGroupId; // If specified key dimension(itemGroupId by default). Use this same dimension from other data.
  82256. // PENDING: If only use key dimension of newData.
  82257. var keyDim = isOld ? oldKeyDim || newKeyDim : newKeyDim || oldKeyDim;
  82258. var dimInfo = keyDim && data.getDimensionInfo(keyDim);
  82259. var dimOrdinalMeta = dimInfo && dimInfo.ordinalMeta;
  82260. if (dimInfo) {
  82261. // Get from encode.itemGroupId.
  82262. var key = data.get(dimInfo.name, dataIndex);
  82263. if (dimOrdinalMeta) {
  82264. return dimOrdinalMeta.categories[key] || key + '';
  82265. }
  82266. return key + '';
  82267. } // Get groupId from raw item. { groupId: '' }
  82268. var itemVal = data.getRawDataItem(dataIndex);
  82269. if (itemVal && itemVal.groupId) {
  82270. return itemVal.groupId + '';
  82271. }
  82272. return dataGroupId || data.getId(dataIndex);
  82273. };
  82274. } // Use id if it's very likely to be an one to one animation
  82275. // It's more robust than groupId
  82276. // TODO Check if key dimension is specified.
  82277. var useId = isAllIdSame(oldDiffItems, newDiffItems);
  82278. var isElementStillInChart = {};
  82279. if (!useId) {
  82280. // We may have different diff strategy with basicTransition if we use other dimension as key.
  82281. // 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.
  82282. // We can't use the elements that already being morphed. Let it keep it's original basic transition.
  82283. for (var i = 0; i < newDiffItems.length; i++) {
  82284. var newItem = newDiffItems[i];
  82285. var el = newItem.data.getItemGraphicEl(newItem.dataIndex);
  82286. if (el) {
  82287. isElementStillInChart[el.id] = true;
  82288. }
  82289. }
  82290. }
  82291. function updateOneToOne(newIndex, oldIndex) {
  82292. var oldItem = oldDiffItems[oldIndex];
  82293. var newItem = newDiffItems[newIndex];
  82294. var newSeries = newItem.data.hostModel; // TODO Mark this elements is morphed and don't morph them anymore
  82295. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex);
  82296. var newEl = newItem.data.getItemGraphicEl(newItem.dataIndex); // Can't handle same elements.
  82297. if (oldEl === newEl) {
  82298. newEl && animateElementStyles(newEl, newItem.dataIndex, newSeries);
  82299. return;
  82300. }
  82301. if ( // We can't use the elements that already being morphed
  82302. oldEl && isElementStillInChart[oldEl.id]) {
  82303. return;
  82304. }
  82305. if (newEl) {
  82306. // TODO: If keep animating the group in case
  82307. // some of the elements don't want to be morphed.
  82308. // TODO Label?
  82309. stopAnimation(newEl);
  82310. if (oldEl) {
  82311. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82312. removeEl$1(oldEl);
  82313. hasMorphAnimation = true;
  82314. applyMorphAnimation(getPathList(oldEl), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82315. } else {
  82316. fadeInElement(newEl, newSeries, newIndex);
  82317. }
  82318. } // else keep oldEl leaving animation.
  82319. }
  82320. new DataDiffer(oldDiffItems, newDiffItems, createKeyGetter(true, useId), createKeyGetter(false, useId), null, 'multiple').update(updateOneToOne).updateManyToOne(function (newIndex, oldIndices) {
  82321. var newItem = newDiffItems[newIndex];
  82322. var newData = newItem.data;
  82323. var newSeries = newData.hostModel;
  82324. var newEl = newData.getItemGraphicEl(newItem.dataIndex);
  82325. var oldElsList = filter(map(oldIndices, function (idx) {
  82326. return oldDiffItems[idx].data.getItemGraphicEl(oldDiffItems[idx].dataIndex);
  82327. }), function (oldEl) {
  82328. return oldEl && oldEl !== newEl && !isElementStillInChart[oldEl.id];
  82329. });
  82330. if (newEl) {
  82331. stopAnimation(newEl);
  82332. if (oldElsList.length) {
  82333. // If old element is doing leaving animation. stop it and remove it immediately.
  82334. each(oldElsList, function (oldEl) {
  82335. stopAnimation(oldEl);
  82336. removeEl$1(oldEl);
  82337. });
  82338. hasMorphAnimation = true;
  82339. applyMorphAnimation(getPathList(oldElsList), getPathList(newEl), newItem.divide, newSeries, newIndex, updateMorphingPathProps);
  82340. } else {
  82341. fadeInElement(newEl, newSeries, newItem.dataIndex);
  82342. }
  82343. } // else keep oldEl leaving animation.
  82344. }).updateOneToMany(function (newIndices, oldIndex) {
  82345. var oldItem = oldDiffItems[oldIndex];
  82346. var oldEl = oldItem.data.getItemGraphicEl(oldItem.dataIndex); // We can't use the elements that already being morphed
  82347. if (oldEl && isElementStillInChart[oldEl.id]) {
  82348. return;
  82349. }
  82350. var newElsList = filter(map(newIndices, function (idx) {
  82351. return newDiffItems[idx].data.getItemGraphicEl(newDiffItems[idx].dataIndex);
  82352. }), function (el) {
  82353. return el && el !== oldEl;
  82354. });
  82355. var newSeris = newDiffItems[newIndices[0]].data.hostModel;
  82356. if (newElsList.length) {
  82357. each(newElsList, function (newEl) {
  82358. return stopAnimation(newEl);
  82359. });
  82360. if (oldEl) {
  82361. stopAnimation(oldEl); // If old element is doing leaving animation. stop it and remove it immediately.
  82362. removeEl$1(oldEl);
  82363. hasMorphAnimation = true;
  82364. applyMorphAnimation(getPathList(oldEl), getPathList(newElsList), oldItem.divide, // Use divide on old.
  82365. newSeris, newIndices[0], updateMorphingPathProps);
  82366. } else {
  82367. each(newElsList, function (newEl) {
  82368. return fadeInElement(newEl, newSeris, newIndices[0]);
  82369. });
  82370. }
  82371. } // else keep oldEl leaving animation.
  82372. }).updateManyToMany(function (newIndices, oldIndices) {
  82373. // If two data are same and both have groupId.
  82374. // Normally they should be diff by id.
  82375. new DataDiffer(oldIndices, newIndices, function (rawIdx) {
  82376. return oldDiffItems[rawIdx].data.getId(oldDiffItems[rawIdx].dataIndex);
  82377. }, function (rawIdx) {
  82378. return newDiffItems[rawIdx].data.getId(newDiffItems[rawIdx].dataIndex);
  82379. }).update(function (newIndex, oldIndex) {
  82380. // Use the original index
  82381. updateOneToOne(newIndices[newIndex], oldIndices[oldIndex]);
  82382. }).execute();
  82383. }).execute();
  82384. if (hasMorphAnimation) {
  82385. each(newList, function (_a) {
  82386. var data = _a.data;
  82387. var seriesModel = data.hostModel;
  82388. var view = seriesModel && api.getViewOfSeriesModel(seriesModel);
  82389. var animationCfg = getAnimationConfig('update', seriesModel, 0); // use 0 index.
  82390. if (view && seriesModel.isAnimationEnabled() && animationCfg && animationCfg.duration > 0) {
  82391. view.group.traverse(function (el) {
  82392. if (el instanceof Path && !el.animators.length) {
  82393. // We can't accept there still exists element that has no animation
  82394. // if universalTransition is enabled
  82395. el.animateFrom({
  82396. style: {
  82397. opacity: 0
  82398. }
  82399. }, animationCfg);
  82400. }
  82401. });
  82402. }
  82403. });
  82404. }
  82405. }
  82406. function getSeriesTransitionKey(series) {
  82407. var seriesKey = series.getModel('universalTransition').get('seriesKey');
  82408. if (!seriesKey) {
  82409. // Use series id by default.
  82410. return series.id;
  82411. }
  82412. return seriesKey;
  82413. }
  82414. function convertArraySeriesKeyToString(seriesKey) {
  82415. if (isArray(seriesKey)) {
  82416. // Order independent.
  82417. return seriesKey.sort().join(',');
  82418. }
  82419. return seriesKey;
  82420. }
  82421. function getDivideShapeFromData(data) {
  82422. if (data.hostModel) {
  82423. return data.hostModel.getModel('universalTransition').get('divideShape');
  82424. }
  82425. }
  82426. function findTransitionSeriesBatches(globalStore, params) {
  82427. var updateBatches = createHashMap();
  82428. var oldDataMap = createHashMap(); // Map that only store key in array seriesKey.
  82429. // Which is used to query the old data when transition from one to multiple series.
  82430. var oldDataMapForSplit = createHashMap();
  82431. each(globalStore.oldSeries, function (series, idx) {
  82432. var oldDataGroupId = globalStore.oldDataGroupIds[idx];
  82433. var oldData = globalStore.oldData[idx];
  82434. var transitionKey = getSeriesTransitionKey(series);
  82435. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey);
  82436. oldDataMap.set(transitionKeyStr, {
  82437. dataGroupId: oldDataGroupId,
  82438. data: oldData
  82439. });
  82440. if (isArray(transitionKey)) {
  82441. // Same key can't in different array seriesKey.
  82442. each(transitionKey, function (key) {
  82443. oldDataMapForSplit.set(key, {
  82444. key: transitionKeyStr,
  82445. dataGroupId: oldDataGroupId,
  82446. data: oldData
  82447. });
  82448. });
  82449. }
  82450. });
  82451. function checkTransitionSeriesKeyDuplicated(transitionKeyStr) {
  82452. if (updateBatches.get(transitionKeyStr)) {
  82453. warn("Duplicated seriesKey in universalTransition " + transitionKeyStr);
  82454. }
  82455. }
  82456. each(params.updatedSeries, function (series) {
  82457. if (series.isUniversalTransitionEnabled() && series.isAnimationEnabled()) {
  82458. var newDataGroupId = series.get('dataGroupId');
  82459. var newData = series.getData();
  82460. var transitionKey = getSeriesTransitionKey(series);
  82461. var transitionKeyStr = convertArraySeriesKeyToString(transitionKey); // Only transition between series with same id.
  82462. var oldData = oldDataMap.get(transitionKeyStr); // string transition key is the best match.
  82463. if (oldData) {
  82464. if ("development" !== 'production') {
  82465. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82466. } // TODO check if data is same?
  82467. updateBatches.set(transitionKeyStr, {
  82468. oldSeries: [{
  82469. dataGroupId: oldData.dataGroupId,
  82470. divide: getDivideShapeFromData(oldData.data),
  82471. data: oldData.data
  82472. }],
  82473. newSeries: [{
  82474. dataGroupId: newDataGroupId,
  82475. divide: getDivideShapeFromData(newData),
  82476. data: newData
  82477. }]
  82478. });
  82479. } else {
  82480. // Transition from multiple series.
  82481. if (isArray(transitionKey)) {
  82482. if ("development" !== 'production') {
  82483. checkTransitionSeriesKeyDuplicated(transitionKeyStr);
  82484. }
  82485. var oldSeries_1 = [];
  82486. each(transitionKey, function (key) {
  82487. var oldData = oldDataMap.get(key);
  82488. if (oldData.data) {
  82489. oldSeries_1.push({
  82490. dataGroupId: oldData.dataGroupId,
  82491. divide: getDivideShapeFromData(oldData.data),
  82492. data: oldData.data
  82493. });
  82494. }
  82495. });
  82496. if (oldSeries_1.length) {
  82497. updateBatches.set(transitionKeyStr, {
  82498. oldSeries: oldSeries_1,
  82499. newSeries: [{
  82500. dataGroupId: newDataGroupId,
  82501. data: newData,
  82502. divide: getDivideShapeFromData(newData)
  82503. }]
  82504. });
  82505. }
  82506. } else {
  82507. // Try transition to multiple series.
  82508. var oldData_1 = oldDataMapForSplit.get(transitionKey);
  82509. if (oldData_1) {
  82510. var batch = updateBatches.get(oldData_1.key);
  82511. if (!batch) {
  82512. batch = {
  82513. oldSeries: [{
  82514. dataGroupId: oldData_1.dataGroupId,
  82515. data: oldData_1.data,
  82516. divide: getDivideShapeFromData(oldData_1.data)
  82517. }],
  82518. newSeries: []
  82519. };
  82520. updateBatches.set(oldData_1.key, batch);
  82521. }
  82522. batch.newSeries.push({
  82523. dataGroupId: newDataGroupId,
  82524. data: newData,
  82525. divide: getDivideShapeFromData(newData)
  82526. });
  82527. }
  82528. }
  82529. }
  82530. }
  82531. });
  82532. return updateBatches;
  82533. }
  82534. function querySeries(series, finder) {
  82535. for (var i = 0; i < series.length; i++) {
  82536. var found = finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id;
  82537. if (found) {
  82538. return i;
  82539. }
  82540. }
  82541. }
  82542. function transitionSeriesFromOpt(transitionOpt, globalStore, params, api) {
  82543. var from = [];
  82544. var to = [];
  82545. each(normalizeToArray(transitionOpt.from), function (finder) {
  82546. var idx = querySeries(globalStore.oldSeries, finder);
  82547. if (idx >= 0) {
  82548. from.push({
  82549. dataGroupId: globalStore.oldDataGroupIds[idx],
  82550. data: globalStore.oldData[idx],
  82551. // TODO can specify divideShape in transition.
  82552. divide: getDivideShapeFromData(globalStore.oldData[idx]),
  82553. dim: finder.dimension
  82554. });
  82555. }
  82556. });
  82557. each(normalizeToArray(transitionOpt.to), function (finder) {
  82558. var idx = querySeries(params.updatedSeries, finder);
  82559. if (idx >= 0) {
  82560. var data = params.updatedSeries[idx].getData();
  82561. to.push({
  82562. dataGroupId: globalStore.oldDataGroupIds[idx],
  82563. data: data,
  82564. divide: getDivideShapeFromData(data),
  82565. dim: finder.dimension
  82566. });
  82567. }
  82568. });
  82569. if (from.length > 0 && to.length > 0) {
  82570. transitionBetween(from, to, api);
  82571. }
  82572. }
  82573. function installUniversalTransition(registers) {
  82574. registers.registerUpdateLifecycle('series:beforeupdate', function (ecMOdel, api, params) {
  82575. each(normalizeToArray(params.seriesTransition), function (transOpt) {
  82576. each(normalizeToArray(transOpt.to), function (finder) {
  82577. var series = params.updatedSeries;
  82578. for (var i = 0; i < series.length; i++) {
  82579. if (finder.seriesIndex != null && finder.seriesIndex === series[i].seriesIndex || finder.seriesId != null && finder.seriesId === series[i].id) {
  82580. series[i][SERIES_UNIVERSAL_TRANSITION_PROP] = true;
  82581. }
  82582. }
  82583. });
  82584. });
  82585. });
  82586. registers.registerUpdateLifecycle('series:transition', function (ecModel, api, params) {
  82587. // TODO api provide an namespace that can save stuff per instance
  82588. var globalStore = getUniversalTransitionGlobalStore(api); // TODO multiple to multiple series.
  82589. if (globalStore.oldSeries && params.updatedSeries && params.optionChanged) {
  82590. // Use give transition config if its' give;
  82591. var transitionOpt = params.seriesTransition;
  82592. if (transitionOpt) {
  82593. each(normalizeToArray(transitionOpt), function (opt) {
  82594. transitionSeriesFromOpt(opt, globalStore, params, api);
  82595. });
  82596. } else {
  82597. // Else guess from series based on transition series key.
  82598. var updateBatches_1 = findTransitionSeriesBatches(globalStore, params);
  82599. each(updateBatches_1.keys(), function (key) {
  82600. var batch = updateBatches_1.get(key);
  82601. transitionBetween(batch.oldSeries, batch.newSeries, api);
  82602. });
  82603. } // Reset
  82604. each(params.updatedSeries, function (series) {
  82605. // Reset;
  82606. if (series[SERIES_UNIVERSAL_TRANSITION_PROP]) {
  82607. series[SERIES_UNIVERSAL_TRANSITION_PROP] = false;
  82608. }
  82609. });
  82610. } // Save all series of current update. Not only the updated one.
  82611. var allSeries = ecModel.getSeries();
  82612. var savedSeries = globalStore.oldSeries = [];
  82613. var savedDataGroupIds = globalStore.oldDataGroupIds = [];
  82614. var savedData = globalStore.oldData = [];
  82615. for (var i = 0; i < allSeries.length; i++) {
  82616. var data = allSeries[i].getData(); // Only save the data that can have transition.
  82617. // Avoid large data costing too much extra memory
  82618. if (data.count() < DATA_COUNT_THRESHOLD) {
  82619. savedSeries.push(allSeries[i]);
  82620. savedDataGroupIds.push(allSeries[i].get('dataGroupId'));
  82621. savedData.push(data);
  82622. }
  82623. }
  82624. });
  82625. }
  82626. // Render engines
  82627. // -----------------
  82628. // Render via Canvas.
  82629. // echarts.init(dom, null, { renderer: 'canvas' })
  82630. use([install$1]); // Render via SVG.
  82631. // echarts.init(dom, null, { renderer: 'svg' })
  82632. use([install]); // ----------------
  82633. // Charts (series)
  82634. // ----------------
  82635. // All of the series types, for example:
  82636. // chart.setOption({
  82637. // series: [{
  82638. // type: 'line' // or 'bar', 'pie', ...
  82639. // }]
  82640. // });
  82641. 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]); // -------------------
  82642. // Coordinate systems
  82643. // -------------------
  82644. // All of the axis modules have been included in the
  82645. // coordinate system module below, do not need to
  82646. // make extra import.
  82647. // `cartesian` coordinate system. For some historical
  82648. // reasons, it is named as grid, for example:
  82649. // chart.setOption({
  82650. // grid: {...},
  82651. // xAxis: {...},
  82652. // yAxis: {...},
  82653. // series: [{...}]
  82654. // });
  82655. use(install$t); // `polar` coordinate system, for example:
  82656. // chart.setOption({
  82657. // polar: {...},
  82658. // radiusAxis: {...},
  82659. // angleAxis: {...},
  82660. // series: [{
  82661. // coordinateSystem: 'polar'
  82662. // }]
  82663. // });
  82664. use(install$u); // `geo` coordinate system, for example:
  82665. // chart.setOption({
  82666. // geo: {...},
  82667. // series: [{
  82668. // coordinateSystem: 'geo'
  82669. // }]
  82670. // });
  82671. use(install$9); // `singleAxis` coordinate system (notice, it is a coordinate system
  82672. // with only one axis, work for chart like theme river), for example:
  82673. // chart.setOption({
  82674. // singleAxis: {...}
  82675. // series: [{type: 'themeRiver', ...}]
  82676. // });
  82677. use(install$v); // `parallel` coordinate system, only work for parallel series, for example:
  82678. // chart.setOption({
  82679. // parallel: {...},
  82680. // parallelAxis: [{...}, ...],
  82681. // series: [{
  82682. // type: 'parallel'
  82683. // }]
  82684. // });
  82685. use(install$g); // `calendar` coordinate system. for example,
  82686. // chart.setOption({
  82687. // calendar: {...},
  82688. // series: [{
  82689. // coordinateSystem: 'calendar'
  82690. // }]
  82691. // );
  82692. use(install$w); // ------------------
  82693. // Other components
  82694. // ------------------
  82695. // `graphic` component, for example:
  82696. // chart.setOption({
  82697. // graphic: {...}
  82698. // });
  82699. use(install$x); // `toolbox` component, for example:
  82700. // chart.setOption({
  82701. // toolbox: {...}
  82702. // });
  82703. use(install$z); // `tooltip` component, for example:
  82704. // chart.setOption({
  82705. // tooltip: {...}
  82706. // });
  82707. use(install$A); // `axisPointer` component, for example:
  82708. // chart.setOption({
  82709. // tooltip: {axisPointer: {...}, ...}
  82710. // });
  82711. // Or
  82712. // chart.setOption({
  82713. // axisPointer: {...}
  82714. // });
  82715. use(install$s); // `brush` component, for example:
  82716. // chart.setOption({
  82717. // brush: {...}
  82718. // });
  82719. // Or
  82720. // chart.setOption({
  82721. // tooltip: {feature: {brush: {...}}
  82722. // })
  82723. use(install$B); // `title` component, for example:
  82724. // chart.setOption({
  82725. // title: {...}
  82726. // });
  82727. use(install$C); // `timeline` component, for example:
  82728. // chart.setOption({
  82729. // timeline: {...}
  82730. // });
  82731. use(install$D); // `markPoint` component, for example:
  82732. // chart.setOption({
  82733. // series: [{markPoint: {...}}]
  82734. // });
  82735. use(install$E); // `markLine` component, for example:
  82736. // chart.setOption({
  82737. // series: [{markLine: {...}}]
  82738. // });
  82739. use(install$F); // `markArea` component, for example:
  82740. // chart.setOption({
  82741. // series: [{markArea: {...}}]
  82742. // });
  82743. use(install$G); // `legend` component not scrollable. for example:
  82744. // chart.setOption({
  82745. // legend: {...}
  82746. // });
  82747. use(install$J); // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  82748. use(install$M); // `dataZoom` component providing drag, pinch, wheel behaviors
  82749. // inside coordinate system, for example:
  82750. // chart.setOption({
  82751. // dataZoom: {type: 'inside'}
  82752. // });
  82753. use(install$K); // `dataZoom` component providing a slider bar, for example:
  82754. // chart.setOption({
  82755. // dataZoom: {type: 'slider'}
  82756. // });
  82757. use(install$L); // `visualMap` component including both `visualMapContinuous` and `visualMapPiecewise`.
  82758. use(install$P); // `visualMap` component providing continuous bar, for example:
  82759. // chart.setOption({
  82760. // visualMap: {type: 'continuous'}
  82761. // });
  82762. use(install$N); // `visualMap` component providing pieces bar, for example:
  82763. // chart.setOption({
  82764. // visualMap: {type: 'piecewise'}
  82765. // });
  82766. use(install$O); // `aria` component providing aria, for example:
  82767. // chart.setOption({
  82768. // aria: {...}
  82769. // });
  82770. use(install$Q); // dataset transform
  82771. // chart.setOption({
  82772. // dataset: {
  82773. // transform: []
  82774. // }
  82775. // });
  82776. use(install$R);
  82777. use(install$S); // universal transition
  82778. // chart.setOption({
  82779. // series: {
  82780. // universalTransition: { enabled: true }
  82781. // }
  82782. // })
  82783. use(installUniversalTransition); // label layout
  82784. // chart.setOption({
  82785. // series: {
  82786. // labelLayout: { hideOverlap: true }
  82787. // }
  82788. // })
  82789. use(installLabelLayout);
  82790. 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 };
  82791. //# sourceMappingURL=echarts.esm.js.map