echarts.esm.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161
  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. extendStatics(d, b);
  40. function __() { this.constructor = d; }
  41. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  42. }
  43. var __assign = function() {
  44. __assign = Object.assign || function __assign(t) {
  45. for (var s, i = 1, n = arguments.length; i < n; i++) {
  46. s = arguments[i];
  47. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  48. }
  49. return t;
  50. };
  51. return __assign.apply(this, arguments);
  52. };
  53. function __spreadArrays() {
  54. for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  55. for (var r = Array(s), k = 0, i = 0; i < il; i++)
  56. for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
  57. r[k] = a[j];
  58. return r;
  59. }
  60. var Browser = (function () {
  61. function Browser() {
  62. this.firefox = false;
  63. this.ie = false;
  64. this.edge = false;
  65. this.newEdge = false;
  66. this.weChat = false;
  67. }
  68. return Browser;
  69. }());
  70. var Env = (function () {
  71. function Env() {
  72. this.browser = new Browser();
  73. this.node = false;
  74. this.wxa = false;
  75. this.worker = false;
  76. this.canvasSupported = false;
  77. this.svgSupported = false;
  78. this.touchEventsSupported = false;
  79. this.pointerEventsSupported = false;
  80. this.domSupported = false;
  81. }
  82. return Env;
  83. }());
  84. var env = new Env();
  85. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  86. env.wxa = true;
  87. env.canvasSupported = true;
  88. env.touchEventsSupported = true;
  89. }
  90. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  91. env.worker = true;
  92. env.canvasSupported = true;
  93. }
  94. else if (typeof navigator === 'undefined') {
  95. env.node = true;
  96. env.canvasSupported = true;
  97. env.svgSupported = true;
  98. }
  99. else {
  100. detect(navigator.userAgent, env);
  101. }
  102. function detect(ua, env) {
  103. var browser = env.browser;
  104. var firefox = ua.match(/Firefox\/([\d.]+)/);
  105. var ie = ua.match(/MSIE\s([\d.]+)/)
  106. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  107. var edge = ua.match(/Edge?\/([\d.]+)/);
  108. var weChat = (/micromessenger/i).test(ua);
  109. if (firefox) {
  110. browser.firefox = true;
  111. browser.version = firefox[1];
  112. }
  113. if (ie) {
  114. browser.ie = true;
  115. browser.version = ie[1];
  116. }
  117. if (edge) {
  118. browser.edge = true;
  119. browser.version = edge[1];
  120. browser.newEdge = +edge[1].split('.')[0] > 18;
  121. }
  122. if (weChat) {
  123. browser.weChat = true;
  124. }
  125. env.canvasSupported = !!document.createElement('canvas').getContext;
  126. env.svgSupported = typeof SVGRect !== 'undefined';
  127. env.touchEventsSupported = 'ontouchstart' in window && !browser.ie && !browser.edge;
  128. env.pointerEventsSupported = 'onpointerdown' in window
  129. && (browser.edge || (browser.ie && +browser.version >= 11));
  130. env.domSupported = typeof document !== 'undefined';
  131. }
  132. var BUILTIN_OBJECT = {
  133. '[object Function]': true,
  134. '[object RegExp]': true,
  135. '[object Date]': true,
  136. '[object Error]': true,
  137. '[object CanvasGradient]': true,
  138. '[object CanvasPattern]': true,
  139. '[object Image]': true,
  140. '[object Canvas]': true
  141. };
  142. var TYPED_ARRAY = {
  143. '[object Int8Array]': true,
  144. '[object Uint8Array]': true,
  145. '[object Uint8ClampedArray]': true,
  146. '[object Int16Array]': true,
  147. '[object Uint16Array]': true,
  148. '[object Int32Array]': true,
  149. '[object Uint32Array]': true,
  150. '[object Float32Array]': true,
  151. '[object Float64Array]': true
  152. };
  153. var objToString = Object.prototype.toString;
  154. var arrayProto = Array.prototype;
  155. var nativeForEach = arrayProto.forEach;
  156. var nativeFilter = arrayProto.filter;
  157. var nativeSlice = arrayProto.slice;
  158. var nativeMap = arrayProto.map;
  159. var ctorFunction = function () { }.constructor;
  160. var protoFunction = ctorFunction ? ctorFunction.prototype : null;
  161. var methods = {};
  162. function $override(name, fn) {
  163. methods[name] = fn;
  164. }
  165. var idStart = 0x0907;
  166. function guid() {
  167. return idStart++;
  168. }
  169. function logError() {
  170. var args = [];
  171. for (var _i = 0; _i < arguments.length; _i++) {
  172. args[_i] = arguments[_i];
  173. }
  174. if (typeof console !== 'undefined') {
  175. console.error.apply(console, args);
  176. }
  177. }
  178. function clone(source) {
  179. if (source == null || typeof source !== 'object') {
  180. return source;
  181. }
  182. var result = source;
  183. var typeStr = objToString.call(source);
  184. if (typeStr === '[object Array]') {
  185. if (!isPrimitive(source)) {
  186. result = [];
  187. for (var i = 0, len = source.length; i < len; i++) {
  188. result[i] = clone(source[i]);
  189. }
  190. }
  191. }
  192. else if (TYPED_ARRAY[typeStr]) {
  193. if (!isPrimitive(source)) {
  194. var Ctor = source.constructor;
  195. if (Ctor.from) {
  196. result = Ctor.from(source);
  197. }
  198. else {
  199. result = new Ctor(source.length);
  200. for (var i = 0, len = source.length; i < len; i++) {
  201. result[i] = clone(source[i]);
  202. }
  203. }
  204. }
  205. }
  206. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  207. result = {};
  208. for (var key in source) {
  209. if (source.hasOwnProperty(key)) {
  210. result[key] = clone(source[key]);
  211. }
  212. }
  213. }
  214. return result;
  215. }
  216. function merge(target, source, overwrite) {
  217. if (!isObject(source) || !isObject(target)) {
  218. return overwrite ? clone(source) : target;
  219. }
  220. for (var key in source) {
  221. if (source.hasOwnProperty(key)) {
  222. var targetProp = target[key];
  223. var sourceProp = source[key];
  224. if (isObject(sourceProp)
  225. && isObject(targetProp)
  226. && !isArray(sourceProp)
  227. && !isArray(targetProp)
  228. && !isDom(sourceProp)
  229. && !isDom(targetProp)
  230. && !isBuiltInObject(sourceProp)
  231. && !isBuiltInObject(targetProp)
  232. && !isPrimitive(sourceProp)
  233. && !isPrimitive(targetProp)) {
  234. merge(targetProp, sourceProp, overwrite);
  235. }
  236. else if (overwrite || !(key in target)) {
  237. target[key] = clone(source[key]);
  238. }
  239. }
  240. }
  241. return target;
  242. }
  243. function mergeAll(targetAndSources, overwrite) {
  244. var result = targetAndSources[0];
  245. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  246. result = merge(result, targetAndSources[i], overwrite);
  247. }
  248. return result;
  249. }
  250. function extend(target, source) {
  251. if (Object.assign) {
  252. Object.assign(target, source);
  253. }
  254. else {
  255. for (var key in source) {
  256. if (source.hasOwnProperty(key)) {
  257. target[key] = source[key];
  258. }
  259. }
  260. }
  261. return target;
  262. }
  263. function defaults(target, source, overlay) {
  264. var keysArr = keys(source);
  265. for (var i = 0; i < keysArr.length; i++) {
  266. var key = keysArr[i];
  267. if ((overlay ? source[key] != null : target[key] == null)) {
  268. target[key] = source[key];
  269. }
  270. }
  271. return target;
  272. }
  273. var createCanvas = function () {
  274. return methods.createCanvas();
  275. };
  276. methods.createCanvas = function () {
  277. return document.createElement('canvas');
  278. };
  279. function indexOf(array, value) {
  280. if (array) {
  281. if (array.indexOf) {
  282. return array.indexOf(value);
  283. }
  284. for (var i = 0, len = array.length; i < len; i++) {
  285. if (array[i] === value) {
  286. return i;
  287. }
  288. }
  289. }
  290. return -1;
  291. }
  292. function inherits(clazz, baseClazz) {
  293. var clazzPrototype = clazz.prototype;
  294. function F() { }
  295. F.prototype = baseClazz.prototype;
  296. clazz.prototype = new F();
  297. for (var prop in clazzPrototype) {
  298. if (clazzPrototype.hasOwnProperty(prop)) {
  299. clazz.prototype[prop] = clazzPrototype[prop];
  300. }
  301. }
  302. clazz.prototype.constructor = clazz;
  303. clazz.superClass = baseClazz;
  304. }
  305. function mixin(target, source, override) {
  306. target = 'prototype' in target ? target.prototype : target;
  307. source = 'prototype' in source ? source.prototype : source;
  308. if (Object.getOwnPropertyNames) {
  309. var keyList = Object.getOwnPropertyNames(source);
  310. for (var i = 0; i < keyList.length; i++) {
  311. var key = keyList[i];
  312. if (key !== 'constructor') {
  313. if ((override ? source[key] != null : target[key] == null)) {
  314. target[key] = source[key];
  315. }
  316. }
  317. }
  318. }
  319. else {
  320. defaults(target, source, override);
  321. }
  322. }
  323. function isArrayLike(data) {
  324. if (!data) {
  325. return false;
  326. }
  327. if (typeof data === 'string') {
  328. return false;
  329. }
  330. return typeof data.length === 'number';
  331. }
  332. function each(arr, cb, context) {
  333. if (!(arr && cb)) {
  334. return;
  335. }
  336. if (arr.forEach && arr.forEach === nativeForEach) {
  337. arr.forEach(cb, context);
  338. }
  339. else if (arr.length === +arr.length) {
  340. for (var i = 0, len = arr.length; i < len; i++) {
  341. cb.call(context, arr[i], i, arr);
  342. }
  343. }
  344. else {
  345. for (var key in arr) {
  346. if (arr.hasOwnProperty(key)) {
  347. cb.call(context, arr[key], key, arr);
  348. }
  349. }
  350. }
  351. }
  352. function map(arr, cb, context) {
  353. if (!arr) {
  354. return [];
  355. }
  356. if (!cb) {
  357. return slice(arr);
  358. }
  359. if (arr.map && arr.map === nativeMap) {
  360. return arr.map(cb, context);
  361. }
  362. else {
  363. var result = [];
  364. for (var i = 0, len = arr.length; i < len; i++) {
  365. result.push(cb.call(context, arr[i], i, arr));
  366. }
  367. return result;
  368. }
  369. }
  370. function reduce(arr, cb, memo, context) {
  371. if (!(arr && cb)) {
  372. return;
  373. }
  374. for (var i = 0, len = arr.length; i < len; i++) {
  375. memo = cb.call(context, memo, arr[i], i, arr);
  376. }
  377. return memo;
  378. }
  379. function filter(arr, cb, context) {
  380. if (!arr) {
  381. return [];
  382. }
  383. if (!cb) {
  384. return slice(arr);
  385. }
  386. if (arr.filter && arr.filter === nativeFilter) {
  387. return arr.filter(cb, context);
  388. }
  389. else {
  390. var result = [];
  391. for (var i = 0, len = arr.length; i < len; i++) {
  392. if (cb.call(context, arr[i], i, arr)) {
  393. result.push(arr[i]);
  394. }
  395. }
  396. return result;
  397. }
  398. }
  399. function find(arr, cb, context) {
  400. if (!(arr && cb)) {
  401. return;
  402. }
  403. for (var i = 0, len = arr.length; i < len; i++) {
  404. if (cb.call(context, arr[i], i, arr)) {
  405. return arr[i];
  406. }
  407. }
  408. }
  409. function keys(obj) {
  410. if (!obj) {
  411. return [];
  412. }
  413. if (Object.keys) {
  414. return Object.keys(obj);
  415. }
  416. var keyList = [];
  417. for (var key in obj) {
  418. if (obj.hasOwnProperty(key)) {
  419. keyList.push(key);
  420. }
  421. }
  422. return keyList;
  423. }
  424. function bindPolyfill(func, context) {
  425. var args = [];
  426. for (var _i = 2; _i < arguments.length; _i++) {
  427. args[_i - 2] = arguments[_i];
  428. }
  429. return function () {
  430. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  431. };
  432. }
  433. var bind = (protoFunction && isFunction(protoFunction.bind))
  434. ? protoFunction.call.bind(protoFunction.bind)
  435. : bindPolyfill;
  436. function curry(func) {
  437. var args = [];
  438. for (var _i = 1; _i < arguments.length; _i++) {
  439. args[_i - 1] = arguments[_i];
  440. }
  441. return function () {
  442. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  443. };
  444. }
  445. function isArray(value) {
  446. if (Array.isArray) {
  447. return Array.isArray(value);
  448. }
  449. return objToString.call(value) === '[object Array]';
  450. }
  451. function isFunction(value) {
  452. return typeof value === 'function';
  453. }
  454. function isString(value) {
  455. return typeof value === 'string';
  456. }
  457. function isStringSafe(value) {
  458. return objToString.call(value) === '[object String]';
  459. }
  460. function isNumber(value) {
  461. return typeof value === 'number';
  462. }
  463. function isObject(value) {
  464. var type = typeof value;
  465. return type === 'function' || (!!value && type === 'object');
  466. }
  467. function isBuiltInObject(value) {
  468. return !!BUILTIN_OBJECT[objToString.call(value)];
  469. }
  470. function isTypedArray(value) {
  471. return !!TYPED_ARRAY[objToString.call(value)];
  472. }
  473. function isDom(value) {
  474. return typeof value === 'object'
  475. && typeof value.nodeType === 'number'
  476. && typeof value.ownerDocument === 'object';
  477. }
  478. function isGradientObject(value) {
  479. return value.colorStops != null;
  480. }
  481. function isPatternObject(value) {
  482. return value.image != null;
  483. }
  484. function isRegExp(value) {
  485. return objToString.call(value) === '[object RegExp]';
  486. }
  487. function eqNaN(value) {
  488. return value !== value;
  489. }
  490. function retrieve() {
  491. var args = [];
  492. for (var _i = 0; _i < arguments.length; _i++) {
  493. args[_i] = arguments[_i];
  494. }
  495. for (var i = 0, len = args.length; i < len; i++) {
  496. if (args[i] != null) {
  497. return args[i];
  498. }
  499. }
  500. }
  501. function retrieve2(value0, value1) {
  502. return value0 != null
  503. ? value0
  504. : value1;
  505. }
  506. function retrieve3(value0, value1, value2) {
  507. return value0 != null
  508. ? value0
  509. : value1 != null
  510. ? value1
  511. : value2;
  512. }
  513. function slice(arr) {
  514. var args = [];
  515. for (var _i = 1; _i < arguments.length; _i++) {
  516. args[_i - 1] = arguments[_i];
  517. }
  518. return nativeSlice.apply(arr, args);
  519. }
  520. function normalizeCssArray(val) {
  521. if (typeof (val) === 'number') {
  522. return [val, val, val, val];
  523. }
  524. var len = val.length;
  525. if (len === 2) {
  526. return [val[0], val[1], val[0], val[1]];
  527. }
  528. else if (len === 3) {
  529. return [val[0], val[1], val[2], val[1]];
  530. }
  531. return val;
  532. }
  533. function assert(condition, message) {
  534. if (!condition) {
  535. throw new Error(message);
  536. }
  537. }
  538. function trim(str) {
  539. if (str == null) {
  540. return null;
  541. }
  542. else if (typeof str.trim === 'function') {
  543. return str.trim();
  544. }
  545. else {
  546. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  547. }
  548. }
  549. var primitiveKey = '__ec_primitive__';
  550. function setAsPrimitive(obj) {
  551. obj[primitiveKey] = true;
  552. }
  553. function isPrimitive(obj) {
  554. return obj[primitiveKey];
  555. }
  556. var HashMap = (function () {
  557. function HashMap(obj) {
  558. this.data = {};
  559. var isArr = isArray(obj);
  560. this.data = {};
  561. var thisMap = this;
  562. (obj instanceof HashMap)
  563. ? obj.each(visit)
  564. : (obj && each(obj, visit));
  565. function visit(value, key) {
  566. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  567. }
  568. }
  569. HashMap.prototype.get = function (key) {
  570. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  571. };
  572. HashMap.prototype.set = function (key, value) {
  573. return (this.data[key] = value);
  574. };
  575. HashMap.prototype.each = function (cb, context) {
  576. for (var key in this.data) {
  577. if (this.data.hasOwnProperty(key)) {
  578. cb.call(context, this.data[key], key);
  579. }
  580. }
  581. };
  582. HashMap.prototype.keys = function () {
  583. return keys(this.data);
  584. };
  585. HashMap.prototype.removeKey = function (key) {
  586. delete this.data[key];
  587. };
  588. return HashMap;
  589. }());
  590. function createHashMap(obj) {
  591. return new HashMap(obj);
  592. }
  593. function concatArray(a, b) {
  594. var newArray = new a.constructor(a.length + b.length);
  595. for (var i = 0; i < a.length; i++) {
  596. newArray[i] = a[i];
  597. }
  598. var offset = a.length;
  599. for (var i = 0; i < b.length; i++) {
  600. newArray[i + offset] = b[i];
  601. }
  602. return newArray;
  603. }
  604. function createObject(proto, properties) {
  605. var obj;
  606. if (Object.create) {
  607. obj = Object.create(proto);
  608. }
  609. else {
  610. var StyleCtor = function () { };
  611. StyleCtor.prototype = proto;
  612. obj = new StyleCtor();
  613. }
  614. if (properties) {
  615. extend(obj, properties);
  616. }
  617. return obj;
  618. }
  619. function hasOwn(own, prop) {
  620. return own.hasOwnProperty(prop);
  621. }
  622. function noop() { }
  623. var util = /*#__PURE__*/Object.freeze({
  624. __proto__: null,
  625. $override: $override,
  626. guid: guid,
  627. logError: logError,
  628. clone: clone,
  629. merge: merge,
  630. mergeAll: mergeAll,
  631. extend: extend,
  632. defaults: defaults,
  633. createCanvas: createCanvas,
  634. indexOf: indexOf,
  635. inherits: inherits,
  636. mixin: mixin,
  637. isArrayLike: isArrayLike,
  638. each: each,
  639. map: map,
  640. reduce: reduce,
  641. filter: filter,
  642. find: find,
  643. keys: keys,
  644. bind: bind,
  645. curry: curry,
  646. isArray: isArray,
  647. isFunction: isFunction,
  648. isString: isString,
  649. isStringSafe: isStringSafe,
  650. isNumber: isNumber,
  651. isObject: isObject,
  652. isBuiltInObject: isBuiltInObject,
  653. isTypedArray: isTypedArray,
  654. isDom: isDom,
  655. isGradientObject: isGradientObject,
  656. isPatternObject: isPatternObject,
  657. isRegExp: isRegExp,
  658. eqNaN: eqNaN,
  659. retrieve: retrieve,
  660. retrieve2: retrieve2,
  661. retrieve3: retrieve3,
  662. slice: slice,
  663. normalizeCssArray: normalizeCssArray,
  664. assert: assert,
  665. trim: trim,
  666. setAsPrimitive: setAsPrimitive,
  667. isPrimitive: isPrimitive,
  668. HashMap: HashMap,
  669. createHashMap: createHashMap,
  670. concatArray: concatArray,
  671. createObject: createObject,
  672. hasOwn: hasOwn,
  673. noop: noop
  674. });
  675. function create(x, y) {
  676. if (x == null) {
  677. x = 0;
  678. }
  679. if (y == null) {
  680. y = 0;
  681. }
  682. return [x, y];
  683. }
  684. function copy(out, v) {
  685. out[0] = v[0];
  686. out[1] = v[1];
  687. return out;
  688. }
  689. function clone$1(v) {
  690. return [v[0], v[1]];
  691. }
  692. function set(out, a, b) {
  693. out[0] = a;
  694. out[1] = b;
  695. return out;
  696. }
  697. function add(out, v1, v2) {
  698. out[0] = v1[0] + v2[0];
  699. out[1] = v1[1] + v2[1];
  700. return out;
  701. }
  702. function scaleAndAdd(out, v1, v2, a) {
  703. out[0] = v1[0] + v2[0] * a;
  704. out[1] = v1[1] + v2[1] * a;
  705. return out;
  706. }
  707. function sub(out, v1, v2) {
  708. out[0] = v1[0] - v2[0];
  709. out[1] = v1[1] - v2[1];
  710. return out;
  711. }
  712. function len(v) {
  713. return Math.sqrt(lenSquare(v));
  714. }
  715. var length = len;
  716. function lenSquare(v) {
  717. return v[0] * v[0] + v[1] * v[1];
  718. }
  719. var lengthSquare = lenSquare;
  720. function mul(out, v1, v2) {
  721. out[0] = v1[0] * v2[0];
  722. out[1] = v1[1] * v2[1];
  723. return out;
  724. }
  725. function div(out, v1, v2) {
  726. out[0] = v1[0] / v2[0];
  727. out[1] = v1[1] / v2[1];
  728. return out;
  729. }
  730. function dot(v1, v2) {
  731. return v1[0] * v2[0] + v1[1] * v2[1];
  732. }
  733. function scale(out, v, s) {
  734. out[0] = v[0] * s;
  735. out[1] = v[1] * s;
  736. return out;
  737. }
  738. function normalize(out, v) {
  739. var d = len(v);
  740. if (d === 0) {
  741. out[0] = 0;
  742. out[1] = 0;
  743. }
  744. else {
  745. out[0] = v[0] / d;
  746. out[1] = v[1] / d;
  747. }
  748. return out;
  749. }
  750. function distance(v1, v2) {
  751. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0])
  752. + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  753. }
  754. var dist = distance;
  755. function distanceSquare(v1, v2) {
  756. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  757. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  758. }
  759. var distSquare = distanceSquare;
  760. function negate(out, v) {
  761. out[0] = -v[0];
  762. out[1] = -v[1];
  763. return out;
  764. }
  765. function lerp(out, v1, v2, t) {
  766. out[0] = v1[0] + t * (v2[0] - v1[0]);
  767. out[1] = v1[1] + t * (v2[1] - v1[1]);
  768. return out;
  769. }
  770. function applyTransform(out, v, m) {
  771. var x = v[0];
  772. var y = v[1];
  773. out[0] = m[0] * x + m[2] * y + m[4];
  774. out[1] = m[1] * x + m[3] * y + m[5];
  775. return out;
  776. }
  777. function min(out, v1, v2) {
  778. out[0] = Math.min(v1[0], v2[0]);
  779. out[1] = Math.min(v1[1], v2[1]);
  780. return out;
  781. }
  782. function max(out, v1, v2) {
  783. out[0] = Math.max(v1[0], v2[0]);
  784. out[1] = Math.max(v1[1], v2[1]);
  785. return out;
  786. }
  787. var vector = /*#__PURE__*/Object.freeze({
  788. __proto__: null,
  789. create: create,
  790. copy: copy,
  791. clone: clone$1,
  792. set: set,
  793. add: add,
  794. scaleAndAdd: scaleAndAdd,
  795. sub: sub,
  796. len: len,
  797. length: length,
  798. lenSquare: lenSquare,
  799. lengthSquare: lengthSquare,
  800. mul: mul,
  801. div: div,
  802. dot: dot,
  803. scale: scale,
  804. normalize: normalize,
  805. distance: distance,
  806. dist: dist,
  807. distanceSquare: distanceSquare,
  808. distSquare: distSquare,
  809. negate: negate,
  810. lerp: lerp,
  811. applyTransform: applyTransform,
  812. min: min,
  813. max: max
  814. });
  815. var Param = (function () {
  816. function Param(target, e) {
  817. this.target = target;
  818. this.topTarget = e && e.topTarget;
  819. }
  820. return Param;
  821. }());
  822. var Draggable = (function () {
  823. function Draggable(handler) {
  824. this.handler = handler;
  825. handler.on('mousedown', this._dragStart, this);
  826. handler.on('mousemove', this._drag, this);
  827. handler.on('mouseup', this._dragEnd, this);
  828. }
  829. Draggable.prototype._dragStart = function (e) {
  830. var draggingTarget = e.target;
  831. while (draggingTarget && !draggingTarget.draggable) {
  832. draggingTarget = draggingTarget.parent;
  833. }
  834. if (draggingTarget) {
  835. this._draggingTarget = draggingTarget;
  836. draggingTarget.dragging = true;
  837. this._x = e.offsetX;
  838. this._y = e.offsetY;
  839. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  840. }
  841. };
  842. Draggable.prototype._drag = function (e) {
  843. var draggingTarget = this._draggingTarget;
  844. if (draggingTarget) {
  845. var x = e.offsetX;
  846. var y = e.offsetY;
  847. var dx = x - this._x;
  848. var dy = y - this._y;
  849. this._x = x;
  850. this._y = y;
  851. draggingTarget.drift(dx, dy, e);
  852. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  853. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  854. var lastDropTarget = this._dropTarget;
  855. this._dropTarget = dropTarget;
  856. if (draggingTarget !== dropTarget) {
  857. if (lastDropTarget && dropTarget !== lastDropTarget) {
  858. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  859. }
  860. if (dropTarget && dropTarget !== lastDropTarget) {
  861. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  862. }
  863. }
  864. }
  865. };
  866. Draggable.prototype._dragEnd = function (e) {
  867. var draggingTarget = this._draggingTarget;
  868. if (draggingTarget) {
  869. draggingTarget.dragging = false;
  870. }
  871. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  872. if (this._dropTarget) {
  873. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  874. }
  875. this._draggingTarget = null;
  876. this._dropTarget = null;
  877. };
  878. return Draggable;
  879. }());
  880. var Eventful = (function () {
  881. function Eventful(eventProcessors) {
  882. if (eventProcessors) {
  883. this._$eventProcessor = eventProcessors;
  884. }
  885. }
  886. Eventful.prototype.on = function (event, query, handler, context) {
  887. if (!this._$handlers) {
  888. this._$handlers = {};
  889. }
  890. var _h = this._$handlers;
  891. if (typeof query === 'function') {
  892. context = handler;
  893. handler = query;
  894. query = null;
  895. }
  896. if (!handler || !event) {
  897. return this;
  898. }
  899. var eventProcessor = this._$eventProcessor;
  900. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  901. query = eventProcessor.normalizeQuery(query);
  902. }
  903. if (!_h[event]) {
  904. _h[event] = [];
  905. }
  906. for (var i = 0; i < _h[event].length; i++) {
  907. if (_h[event][i].h === handler) {
  908. return this;
  909. }
  910. }
  911. var wrap = {
  912. h: handler,
  913. query: query,
  914. ctx: (context || this),
  915. callAtLast: handler.zrEventfulCallAtLast
  916. };
  917. var lastIndex = _h[event].length - 1;
  918. var lastWrap = _h[event][lastIndex];
  919. (lastWrap && lastWrap.callAtLast)
  920. ? _h[event].splice(lastIndex, 0, wrap)
  921. : _h[event].push(wrap);
  922. return this;
  923. };
  924. Eventful.prototype.isSilent = function (eventName) {
  925. var _h = this._$handlers;
  926. return !_h || !_h[eventName] || !_h[eventName].length;
  927. };
  928. Eventful.prototype.off = function (eventType, handler) {
  929. var _h = this._$handlers;
  930. if (!_h) {
  931. return this;
  932. }
  933. if (!eventType) {
  934. this._$handlers = {};
  935. return this;
  936. }
  937. if (handler) {
  938. if (_h[eventType]) {
  939. var newList = [];
  940. for (var i = 0, l = _h[eventType].length; i < l; i++) {
  941. if (_h[eventType][i].h !== handler) {
  942. newList.push(_h[eventType][i]);
  943. }
  944. }
  945. _h[eventType] = newList;
  946. }
  947. if (_h[eventType] && _h[eventType].length === 0) {
  948. delete _h[eventType];
  949. }
  950. }
  951. else {
  952. delete _h[eventType];
  953. }
  954. return this;
  955. };
  956. Eventful.prototype.trigger = function (eventType) {
  957. var args = [];
  958. for (var _i = 1; _i < arguments.length; _i++) {
  959. args[_i - 1] = arguments[_i];
  960. }
  961. if (!this._$handlers) {
  962. return this;
  963. }
  964. var _h = this._$handlers[eventType];
  965. var eventProcessor = this._$eventProcessor;
  966. if (_h) {
  967. var argLen = args.length;
  968. var len = _h.length;
  969. for (var i = 0; i < len; i++) {
  970. var hItem = _h[i];
  971. if (eventProcessor
  972. && eventProcessor.filter
  973. && hItem.query != null
  974. && !eventProcessor.filter(eventType, hItem.query)) {
  975. continue;
  976. }
  977. switch (argLen) {
  978. case 0:
  979. hItem.h.call(hItem.ctx);
  980. break;
  981. case 1:
  982. hItem.h.call(hItem.ctx, args[0]);
  983. break;
  984. case 2:
  985. hItem.h.call(hItem.ctx, args[0], args[1]);
  986. break;
  987. default:
  988. hItem.h.apply(hItem.ctx, args);
  989. break;
  990. }
  991. }
  992. }
  993. eventProcessor && eventProcessor.afterTrigger
  994. && eventProcessor.afterTrigger(eventType);
  995. return this;
  996. };
  997. Eventful.prototype.triggerWithContext = function (type) {
  998. if (!this._$handlers) {
  999. return this;
  1000. }
  1001. var _h = this._$handlers[type];
  1002. var eventProcessor = this._$eventProcessor;
  1003. if (_h) {
  1004. var args = arguments;
  1005. var argLen = args.length;
  1006. var ctx = args[argLen - 1];
  1007. var len = _h.length;
  1008. for (var i = 0; i < len; i++) {
  1009. var hItem = _h[i];
  1010. if (eventProcessor
  1011. && eventProcessor.filter
  1012. && hItem.query != null
  1013. && !eventProcessor.filter(type, hItem.query)) {
  1014. continue;
  1015. }
  1016. switch (argLen) {
  1017. case 0:
  1018. hItem.h.call(ctx);
  1019. break;
  1020. case 1:
  1021. hItem.h.call(ctx, args[0]);
  1022. break;
  1023. case 2:
  1024. hItem.h.call(ctx, args[0], args[1]);
  1025. break;
  1026. default:
  1027. hItem.h.apply(ctx, args.slice(1, argLen - 1));
  1028. break;
  1029. }
  1030. }
  1031. }
  1032. eventProcessor && eventProcessor.afterTrigger
  1033. && eventProcessor.afterTrigger(type);
  1034. return this;
  1035. };
  1036. return Eventful;
  1037. }());
  1038. var LN2 = Math.log(2);
  1039. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1040. var cacheKey = rowMask + '-' + colMask;
  1041. var fullRank = rows.length;
  1042. if (detCache.hasOwnProperty(cacheKey)) {
  1043. return detCache[cacheKey];
  1044. }
  1045. if (rank === 1) {
  1046. var colStart = Math.round(Math.log(((1 << fullRank) - 1) & ~colMask) / LN2);
  1047. return rows[rowStart][colStart];
  1048. }
  1049. var subRowMask = rowMask | (1 << rowStart);
  1050. var subRowStart = rowStart + 1;
  1051. while (rowMask & (1 << subRowStart)) {
  1052. subRowStart++;
  1053. }
  1054. var sum = 0;
  1055. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1056. var colTag = 1 << j;
  1057. if (!(colTag & colMask)) {
  1058. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j]
  1059. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1060. colLocalIdx++;
  1061. }
  1062. }
  1063. detCache[cacheKey] = sum;
  1064. return sum;
  1065. }
  1066. function buildTransformer(src, dest) {
  1067. var mA = [
  1068. [src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]],
  1069. [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]],
  1070. [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]],
  1071. [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]],
  1072. [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]],
  1073. [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]],
  1074. [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]],
  1075. [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]
  1076. ];
  1077. var detCache = {};
  1078. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1079. if (det === 0) {
  1080. return;
  1081. }
  1082. var vh = [];
  1083. for (var i = 0; i < 8; i++) {
  1084. for (var j = 0; j < 8; j++) {
  1085. vh[j] == null && (vh[j] = 0);
  1086. vh[j] += ((i + j) % 2 ? -1 : 1)
  1087. * determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache)
  1088. / det * dest[i];
  1089. }
  1090. }
  1091. return function (out, srcPointX, srcPointY) {
  1092. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1093. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1094. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1095. };
  1096. }
  1097. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1098. var _calcOut = [];
  1099. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1100. return transformCoordWithViewport(_calcOut, elFrom, inX, inY, true)
  1101. && transformCoordWithViewport(out, elTarget, _calcOut[0], _calcOut[1]);
  1102. }
  1103. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1104. if (el.getBoundingClientRect && env.domSupported && !isCanvasEl(el)) {
  1105. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1106. var markers = prepareCoordMarkers(el, saved);
  1107. var transformer = preparePointerTransformer(markers, saved, inverse);
  1108. if (transformer) {
  1109. transformer(out, inX, inY);
  1110. return true;
  1111. }
  1112. }
  1113. return false;
  1114. }
  1115. function prepareCoordMarkers(el, saved) {
  1116. var markers = saved.markers;
  1117. if (markers) {
  1118. return markers;
  1119. }
  1120. markers = saved.markers = [];
  1121. var propLR = ['left', 'right'];
  1122. var propTB = ['top', 'bottom'];
  1123. for (var i = 0; i < 4; i++) {
  1124. var marker = document.createElement('div');
  1125. var stl = marker.style;
  1126. var idxLR = i % 2;
  1127. var idxTB = (i >> 1) % 2;
  1128. stl.cssText = [
  1129. 'position: absolute',
  1130. 'visibility: hidden',
  1131. 'padding: 0',
  1132. 'margin: 0',
  1133. 'border-width: 0',
  1134. 'user-select: none',
  1135. 'width:0',
  1136. 'height:0',
  1137. propLR[idxLR] + ':0',
  1138. propTB[idxTB] + ':0',
  1139. propLR[1 - idxLR] + ':auto',
  1140. propTB[1 - idxTB] + ':auto',
  1141. ''
  1142. ].join('!important;');
  1143. el.appendChild(marker);
  1144. markers.push(marker);
  1145. }
  1146. return markers;
  1147. }
  1148. function preparePointerTransformer(markers, saved, inverse) {
  1149. var transformerName = inverse ? 'invTrans' : 'trans';
  1150. var transformer = saved[transformerName];
  1151. var oldSrcCoords = saved.srcCoords;
  1152. var srcCoords = [];
  1153. var destCoords = [];
  1154. var oldCoordTheSame = true;
  1155. for (var i = 0; i < 4; i++) {
  1156. var rect = markers[i].getBoundingClientRect();
  1157. var ii = 2 * i;
  1158. var x = rect.left;
  1159. var y = rect.top;
  1160. srcCoords.push(x, y);
  1161. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1162. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1163. }
  1164. return (oldCoordTheSame && transformer)
  1165. ? transformer
  1166. : (saved.srcCoords = srcCoords,
  1167. saved[transformerName] = inverse
  1168. ? buildTransformer(destCoords, srcCoords)
  1169. : buildTransformer(srcCoords, destCoords));
  1170. }
  1171. function isCanvasEl(el) {
  1172. return el.nodeName.toUpperCase() === 'CANVAS';
  1173. }
  1174. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  1175. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1176. var _calcOut$1 = [];
  1177. function clientToLocal(el, e, out, calculate) {
  1178. out = out || {};
  1179. if (calculate || !env.canvasSupported) {
  1180. calculateZrXY(el, e, out);
  1181. }
  1182. else if (env.browser.firefox
  1183. && e.layerX != null
  1184. && e.layerX !== e.offsetX) {
  1185. out.zrX = e.layerX;
  1186. out.zrY = e.layerY;
  1187. }
  1188. else if (e.offsetX != null) {
  1189. out.zrX = e.offsetX;
  1190. out.zrY = e.offsetY;
  1191. }
  1192. else {
  1193. calculateZrXY(el, e, out);
  1194. }
  1195. return out;
  1196. }
  1197. function calculateZrXY(el, e, out) {
  1198. if (env.domSupported && el.getBoundingClientRect) {
  1199. var ex = e.clientX;
  1200. var ey = e.clientY;
  1201. if (isCanvasEl(el)) {
  1202. var box = el.getBoundingClientRect();
  1203. out.zrX = ex - box.left;
  1204. out.zrY = ey - box.top;
  1205. return;
  1206. }
  1207. else {
  1208. if (transformCoordWithViewport(_calcOut$1, el, ex, ey)) {
  1209. out.zrX = _calcOut$1[0];
  1210. out.zrY = _calcOut$1[1];
  1211. return;
  1212. }
  1213. }
  1214. }
  1215. out.zrX = out.zrY = 0;
  1216. }
  1217. function getNativeEvent(e) {
  1218. return e
  1219. || window.event;
  1220. }
  1221. function normalizeEvent(el, e, calculate) {
  1222. e = getNativeEvent(e);
  1223. if (e.zrX != null) {
  1224. return e;
  1225. }
  1226. var eventType = e.type;
  1227. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1228. if (!isTouch) {
  1229. clientToLocal(el, e, e, calculate);
  1230. var wheelDelta = getWheelDeltaMayPolyfill(e);
  1231. e.zrDelta = wheelDelta ? wheelDelta / 120 : -(e.detail || 0) / 3;
  1232. }
  1233. else {
  1234. var touch = eventType !== 'touchend'
  1235. ? e.targetTouches[0]
  1236. : e.changedTouches[0];
  1237. touch && clientToLocal(el, touch, e, calculate);
  1238. }
  1239. var button = e.button;
  1240. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1241. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  1242. }
  1243. return e;
  1244. }
  1245. function getWheelDeltaMayPolyfill(e) {
  1246. var rawWheelDelta = e.wheelDelta;
  1247. if (rawWheelDelta) {
  1248. return rawWheelDelta;
  1249. }
  1250. var deltaX = e.deltaX;
  1251. var deltaY = e.deltaY;
  1252. if (deltaX == null || deltaY == null) {
  1253. return rawWheelDelta;
  1254. }
  1255. var delta = deltaY !== 0 ? Math.abs(deltaY) : Math.abs(deltaX);
  1256. var sign = deltaY > 0 ? -1
  1257. : deltaY < 0 ? 1
  1258. : deltaX > 0 ? -1
  1259. : 1;
  1260. return 3 * delta * sign;
  1261. }
  1262. function addEventListener(el, name, handler, opt) {
  1263. if (isDomLevel2) {
  1264. el.addEventListener(name, handler, opt);
  1265. }
  1266. else {
  1267. el.attachEvent('on' + name, handler);
  1268. }
  1269. }
  1270. function removeEventListener(el, name, handler, opt) {
  1271. if (isDomLevel2) {
  1272. el.removeEventListener(name, handler, opt);
  1273. }
  1274. else {
  1275. el.detachEvent('on' + name, handler);
  1276. }
  1277. }
  1278. var stop = isDomLevel2
  1279. ? function (e) {
  1280. e.preventDefault();
  1281. e.stopPropagation();
  1282. e.cancelBubble = true;
  1283. }
  1284. : function (e) {
  1285. e.returnValue = false;
  1286. e.cancelBubble = true;
  1287. };
  1288. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1289. return e.which === 2 || e.which === 3;
  1290. }
  1291. var GestureMgr = (function () {
  1292. function GestureMgr() {
  1293. this._track = [];
  1294. }
  1295. GestureMgr.prototype.recognize = function (event, target, root) {
  1296. this._doTrack(event, target, root);
  1297. return this._recognize(event);
  1298. };
  1299. GestureMgr.prototype.clear = function () {
  1300. this._track.length = 0;
  1301. return this;
  1302. };
  1303. GestureMgr.prototype._doTrack = function (event, target, root) {
  1304. var touches = event.touches;
  1305. if (!touches) {
  1306. return;
  1307. }
  1308. var trackItem = {
  1309. points: [],
  1310. touches: [],
  1311. target: target,
  1312. event: event
  1313. };
  1314. for (var i = 0, len = touches.length; i < len; i++) {
  1315. var touch = touches[i];
  1316. var pos = clientToLocal(root, touch, {});
  1317. trackItem.points.push([pos.zrX, pos.zrY]);
  1318. trackItem.touches.push(touch);
  1319. }
  1320. this._track.push(trackItem);
  1321. };
  1322. GestureMgr.prototype._recognize = function (event) {
  1323. for (var eventName in recognizers) {
  1324. if (recognizers.hasOwnProperty(eventName)) {
  1325. var gestureInfo = recognizers[eventName](this._track, event);
  1326. if (gestureInfo) {
  1327. return gestureInfo;
  1328. }
  1329. }
  1330. }
  1331. };
  1332. return GestureMgr;
  1333. }());
  1334. function dist$1(pointPair) {
  1335. var dx = pointPair[1][0] - pointPair[0][0];
  1336. var dy = pointPair[1][1] - pointPair[0][1];
  1337. return Math.sqrt(dx * dx + dy * dy);
  1338. }
  1339. function center(pointPair) {
  1340. return [
  1341. (pointPair[0][0] + pointPair[1][0]) / 2,
  1342. (pointPair[0][1] + pointPair[1][1]) / 2
  1343. ];
  1344. }
  1345. var recognizers = {
  1346. pinch: function (tracks, event) {
  1347. var trackLen = tracks.length;
  1348. if (!trackLen) {
  1349. return;
  1350. }
  1351. var pinchEnd = (tracks[trackLen - 1] || {}).points;
  1352. var pinchPre = (tracks[trackLen - 2] || {}).points || pinchEnd;
  1353. if (pinchPre
  1354. && pinchPre.length > 1
  1355. && pinchEnd
  1356. && pinchEnd.length > 1) {
  1357. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1358. !isFinite(pinchScale) && (pinchScale = 1);
  1359. event.pinchScale = pinchScale;
  1360. var pinchCenter = center(pinchEnd);
  1361. event.pinchX = pinchCenter[0];
  1362. event.pinchY = pinchCenter[1];
  1363. return {
  1364. type: 'pinch',
  1365. target: tracks[0].target,
  1366. event: event
  1367. };
  1368. }
  1369. }
  1370. };
  1371. var SILENT = 'silent';
  1372. function makeEventPacket(eveType, targetInfo, event) {
  1373. return {
  1374. type: eveType,
  1375. event: event,
  1376. target: targetInfo.target,
  1377. topTarget: targetInfo.topTarget,
  1378. cancelBubble: false,
  1379. offsetX: event.zrX,
  1380. offsetY: event.zrY,
  1381. gestureEvent: event.gestureEvent,
  1382. pinchX: event.pinchX,
  1383. pinchY: event.pinchY,
  1384. pinchScale: event.pinchScale,
  1385. wheelDelta: event.zrDelta,
  1386. zrByTouch: event.zrByTouch,
  1387. which: event.which,
  1388. stop: stopEvent
  1389. };
  1390. }
  1391. function stopEvent() {
  1392. stop(this.event);
  1393. }
  1394. var EmptyProxy = (function (_super) {
  1395. __extends(EmptyProxy, _super);
  1396. function EmptyProxy() {
  1397. var _this = _super !== null && _super.apply(this, arguments) || this;
  1398. _this.handler = null;
  1399. return _this;
  1400. }
  1401. EmptyProxy.prototype.dispose = function () { };
  1402. EmptyProxy.prototype.setCursor = function () { };
  1403. return EmptyProxy;
  1404. }(Eventful));
  1405. var HoveredResult = (function () {
  1406. function HoveredResult(x, y) {
  1407. this.x = x;
  1408. this.y = y;
  1409. }
  1410. return HoveredResult;
  1411. }());
  1412. var handlerNames = [
  1413. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1414. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1415. ];
  1416. var Handler = (function (_super) {
  1417. __extends(Handler, _super);
  1418. function Handler(storage, painter, proxy, painterRoot) {
  1419. var _this = _super.call(this) || this;
  1420. _this._hovered = new HoveredResult(0, 0);
  1421. _this.storage = storage;
  1422. _this.painter = painter;
  1423. _this.painterRoot = painterRoot;
  1424. proxy = proxy || new EmptyProxy();
  1425. _this.proxy = null;
  1426. _this.setHandlerProxy(proxy);
  1427. _this._draggingMgr = new Draggable(_this);
  1428. return _this;
  1429. }
  1430. Handler.prototype.setHandlerProxy = function (proxy) {
  1431. if (this.proxy) {
  1432. this.proxy.dispose();
  1433. }
  1434. if (proxy) {
  1435. each(handlerNames, function (name) {
  1436. proxy.on && proxy.on(name, this[name], this);
  1437. }, this);
  1438. proxy.handler = this;
  1439. }
  1440. this.proxy = proxy;
  1441. };
  1442. Handler.prototype.mousemove = function (event) {
  1443. var x = event.zrX;
  1444. var y = event.zrY;
  1445. var isOutside = isOutsideBoundary(this, x, y);
  1446. var lastHovered = this._hovered;
  1447. var lastHoveredTarget = lastHovered.target;
  1448. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1449. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1450. lastHoveredTarget = lastHovered.target;
  1451. }
  1452. var hovered = this._hovered = isOutside ? new HoveredResult(x, y) : this.findHover(x, y);
  1453. var hoveredTarget = hovered.target;
  1454. var proxy = this.proxy;
  1455. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1456. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1457. this.dispatchToElement(lastHovered, 'mouseout', event);
  1458. }
  1459. this.dispatchToElement(hovered, 'mousemove', event);
  1460. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1461. this.dispatchToElement(hovered, 'mouseover', event);
  1462. }
  1463. };
  1464. Handler.prototype.mouseout = function (event) {
  1465. var eventControl = event.zrEventControl;
  1466. if (eventControl !== 'only_globalout') {
  1467. this.dispatchToElement(this._hovered, 'mouseout', event);
  1468. }
  1469. if (eventControl !== 'no_globalout') {
  1470. this.trigger('globalout', { type: 'globalout', event: event });
  1471. }
  1472. };
  1473. Handler.prototype.resize = function () {
  1474. this._hovered = new HoveredResult(0, 0);
  1475. };
  1476. Handler.prototype.dispatch = function (eventName, eventArgs) {
  1477. var handler = this[eventName];
  1478. handler && handler.call(this, eventArgs);
  1479. };
  1480. Handler.prototype.dispose = function () {
  1481. this.proxy.dispose();
  1482. this.storage = null;
  1483. this.proxy = null;
  1484. this.painter = null;
  1485. };
  1486. Handler.prototype.setCursorStyle = function (cursorStyle) {
  1487. var proxy = this.proxy;
  1488. proxy.setCursor && proxy.setCursor(cursorStyle);
  1489. };
  1490. Handler.prototype.dispatchToElement = function (targetInfo, eventName, event) {
  1491. targetInfo = targetInfo || {};
  1492. var el = targetInfo.target;
  1493. if (el && el.silent) {
  1494. return;
  1495. }
  1496. var eventKey = ('on' + eventName);
  1497. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1498. while (el) {
  1499. el[eventKey]
  1500. && (eventPacket.cancelBubble = !!el[eventKey].call(el, eventPacket));
  1501. el.trigger(eventName, eventPacket);
  1502. el = el.__hostTarget ? el.__hostTarget : el.parent;
  1503. if (eventPacket.cancelBubble) {
  1504. break;
  1505. }
  1506. }
  1507. if (!eventPacket.cancelBubble) {
  1508. this.trigger(eventName, eventPacket);
  1509. if (this.painter && this.painter.eachOtherLayer) {
  1510. this.painter.eachOtherLayer(function (layer) {
  1511. if (typeof (layer[eventKey]) === 'function') {
  1512. layer[eventKey].call(layer, eventPacket);
  1513. }
  1514. if (layer.trigger) {
  1515. layer.trigger(eventName, eventPacket);
  1516. }
  1517. });
  1518. }
  1519. }
  1520. };
  1521. Handler.prototype.findHover = function (x, y, exclude) {
  1522. var list = this.storage.getDisplayList();
  1523. var out = new HoveredResult(x, y);
  1524. for (var i = list.length - 1; i >= 0; i--) {
  1525. var hoverCheckResult = void 0;
  1526. if (list[i] !== exclude
  1527. && !list[i].ignore
  1528. && (hoverCheckResult = isHover(list[i], x, y))) {
  1529. !out.topTarget && (out.topTarget = list[i]);
  1530. if (hoverCheckResult !== SILENT) {
  1531. out.target = list[i];
  1532. break;
  1533. }
  1534. }
  1535. }
  1536. return out;
  1537. };
  1538. Handler.prototype.processGesture = function (event, stage) {
  1539. if (!this._gestureMgr) {
  1540. this._gestureMgr = new GestureMgr();
  1541. }
  1542. var gestureMgr = this._gestureMgr;
  1543. stage === 'start' && gestureMgr.clear();
  1544. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  1545. stage === 'end' && gestureMgr.clear();
  1546. if (gestureInfo) {
  1547. var type = gestureInfo.type;
  1548. event.gestureEvent = type;
  1549. var res = new HoveredResult();
  1550. res.target = gestureInfo.target;
  1551. this.dispatchToElement(res, type, gestureInfo.event);
  1552. }
  1553. };
  1554. return Handler;
  1555. }(Eventful));
  1556. each(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1557. Handler.prototype[name] = function (event) {
  1558. var x = event.zrX;
  1559. var y = event.zrY;
  1560. var isOutside = isOutsideBoundary(this, x, y);
  1561. var hovered;
  1562. var hoveredTarget;
  1563. if (name !== 'mouseup' || !isOutside) {
  1564. hovered = this.findHover(x, y);
  1565. hoveredTarget = hovered.target;
  1566. }
  1567. if (name === 'mousedown') {
  1568. this._downEl = hoveredTarget;
  1569. this._downPoint = [event.zrX, event.zrY];
  1570. this._upEl = hoveredTarget;
  1571. }
  1572. else if (name === 'mouseup') {
  1573. this._upEl = hoveredTarget;
  1574. }
  1575. else if (name === 'click') {
  1576. if (this._downEl !== this._upEl
  1577. || !this._downPoint
  1578. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  1579. return;
  1580. }
  1581. this._downPoint = null;
  1582. }
  1583. this.dispatchToElement(hovered, name, event);
  1584. };
  1585. });
  1586. function isHover(displayable, x, y) {
  1587. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1588. var el = displayable;
  1589. var isSilent = void 0;
  1590. var ignoreClip = false;
  1591. while (el) {
  1592. if (el.ignoreClip) {
  1593. ignoreClip = true;
  1594. }
  1595. if (!ignoreClip) {
  1596. var clipPath = el.getClipPath();
  1597. if (clipPath && !clipPath.contain(x, y)) {
  1598. return false;
  1599. }
  1600. if (el.silent) {
  1601. isSilent = true;
  1602. }
  1603. }
  1604. var hostEl = el.__hostTarget;
  1605. el = hostEl ? hostEl : el.parent;
  1606. }
  1607. return isSilent ? SILENT : true;
  1608. }
  1609. return false;
  1610. }
  1611. function isOutsideBoundary(handlerInstance, x, y) {
  1612. var painter = handlerInstance.painter;
  1613. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  1614. }
  1615. function create$1() {
  1616. return [1, 0, 0, 1, 0, 0];
  1617. }
  1618. function identity(out) {
  1619. out[0] = 1;
  1620. out[1] = 0;
  1621. out[2] = 0;
  1622. out[3] = 1;
  1623. out[4] = 0;
  1624. out[5] = 0;
  1625. return out;
  1626. }
  1627. function copy$1(out, m) {
  1628. out[0] = m[0];
  1629. out[1] = m[1];
  1630. out[2] = m[2];
  1631. out[3] = m[3];
  1632. out[4] = m[4];
  1633. out[5] = m[5];
  1634. return out;
  1635. }
  1636. function mul$1(out, m1, m2) {
  1637. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1638. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1639. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1640. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1641. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1642. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1643. out[0] = out0;
  1644. out[1] = out1;
  1645. out[2] = out2;
  1646. out[3] = out3;
  1647. out[4] = out4;
  1648. out[5] = out5;
  1649. return out;
  1650. }
  1651. function translate(out, a, v) {
  1652. out[0] = a[0];
  1653. out[1] = a[1];
  1654. out[2] = a[2];
  1655. out[3] = a[3];
  1656. out[4] = a[4] + v[0];
  1657. out[5] = a[5] + v[1];
  1658. return out;
  1659. }
  1660. function rotate(out, a, rad) {
  1661. var aa = a[0];
  1662. var ac = a[2];
  1663. var atx = a[4];
  1664. var ab = a[1];
  1665. var ad = a[3];
  1666. var aty = a[5];
  1667. var st = Math.sin(rad);
  1668. var ct = Math.cos(rad);
  1669. out[0] = aa * ct + ab * st;
  1670. out[1] = -aa * st + ab * ct;
  1671. out[2] = ac * ct + ad * st;
  1672. out[3] = -ac * st + ct * ad;
  1673. out[4] = ct * atx + st * aty;
  1674. out[5] = ct * aty - st * atx;
  1675. return out;
  1676. }
  1677. function scale$1(out, a, v) {
  1678. var vx = v[0];
  1679. var vy = v[1];
  1680. out[0] = a[0] * vx;
  1681. out[1] = a[1] * vy;
  1682. out[2] = a[2] * vx;
  1683. out[3] = a[3] * vy;
  1684. out[4] = a[4] * vx;
  1685. out[5] = a[5] * vy;
  1686. return out;
  1687. }
  1688. function invert(out, a) {
  1689. var aa = a[0];
  1690. var ac = a[2];
  1691. var atx = a[4];
  1692. var ab = a[1];
  1693. var ad = a[3];
  1694. var aty = a[5];
  1695. var det = aa * ad - ab * ac;
  1696. if (!det) {
  1697. return null;
  1698. }
  1699. det = 1.0 / det;
  1700. out[0] = ad * det;
  1701. out[1] = -ab * det;
  1702. out[2] = -ac * det;
  1703. out[3] = aa * det;
  1704. out[4] = (ac * aty - ad * atx) * det;
  1705. out[5] = (ab * atx - aa * aty) * det;
  1706. return out;
  1707. }
  1708. function clone$2(a) {
  1709. var b = create$1();
  1710. copy$1(b, a);
  1711. return b;
  1712. }
  1713. var matrix = /*#__PURE__*/Object.freeze({
  1714. __proto__: null,
  1715. create: create$1,
  1716. identity: identity,
  1717. copy: copy$1,
  1718. mul: mul$1,
  1719. translate: translate,
  1720. rotate: rotate,
  1721. scale: scale$1,
  1722. invert: invert,
  1723. clone: clone$2
  1724. });
  1725. var mIdentity = identity;
  1726. var EPSILON = 5e-5;
  1727. function isNotAroundZero(val) {
  1728. return val > EPSILON || val < -EPSILON;
  1729. }
  1730. var scaleTmp = [];
  1731. var tmpTransform = [];
  1732. var originTransform = create$1();
  1733. var abs = Math.abs;
  1734. var Transformable = (function () {
  1735. function Transformable() {
  1736. }
  1737. Transformable.prototype.setPosition = function (arr) {
  1738. this.x = arr[0];
  1739. this.y = arr[1];
  1740. };
  1741. Transformable.prototype.setScale = function (arr) {
  1742. this.scaleX = arr[0];
  1743. this.scaleY = arr[1];
  1744. };
  1745. Transformable.prototype.setOrigin = function (arr) {
  1746. this.originX = arr[0];
  1747. this.originY = arr[1];
  1748. };
  1749. Transformable.prototype.needLocalTransform = function () {
  1750. return isNotAroundZero(this.rotation)
  1751. || isNotAroundZero(this.x)
  1752. || isNotAroundZero(this.y)
  1753. || isNotAroundZero(this.scaleX - 1)
  1754. || isNotAroundZero(this.scaleY - 1);
  1755. };
  1756. Transformable.prototype.updateTransform = function () {
  1757. var parent = this.parent;
  1758. var parentHasTransform = parent && parent.transform;
  1759. var needLocalTransform = this.needLocalTransform();
  1760. var m = this.transform;
  1761. if (!(needLocalTransform || parentHasTransform)) {
  1762. m && mIdentity(m);
  1763. return;
  1764. }
  1765. m = m || create$1();
  1766. if (needLocalTransform) {
  1767. this.getLocalTransform(m);
  1768. }
  1769. else {
  1770. mIdentity(m);
  1771. }
  1772. if (parentHasTransform) {
  1773. if (needLocalTransform) {
  1774. mul$1(m, parent.transform, m);
  1775. }
  1776. else {
  1777. copy$1(m, parent.transform);
  1778. }
  1779. }
  1780. this.transform = m;
  1781. this._resolveGlobalScaleRatio(m);
  1782. };
  1783. Transformable.prototype._resolveGlobalScaleRatio = function (m) {
  1784. var globalScaleRatio = this.globalScaleRatio;
  1785. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  1786. this.getGlobalScale(scaleTmp);
  1787. var relX = scaleTmp[0] < 0 ? -1 : 1;
  1788. var relY = scaleTmp[1] < 0 ? -1 : 1;
  1789. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  1790. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  1791. m[0] *= sx;
  1792. m[1] *= sx;
  1793. m[2] *= sy;
  1794. m[3] *= sy;
  1795. }
  1796. this.invTransform = this.invTransform || create$1();
  1797. invert(this.invTransform, m);
  1798. };
  1799. Transformable.prototype.getLocalTransform = function (m) {
  1800. return Transformable.getLocalTransform(this, m);
  1801. };
  1802. Transformable.prototype.getComputedTransform = function () {
  1803. var transformNode = this;
  1804. var ancestors = [];
  1805. while (transformNode) {
  1806. ancestors.push(transformNode);
  1807. transformNode = transformNode.parent;
  1808. }
  1809. while (transformNode = ancestors.pop()) {
  1810. transformNode.updateTransform();
  1811. }
  1812. return this.transform;
  1813. };
  1814. Transformable.prototype.setLocalTransform = function (m) {
  1815. if (!m) {
  1816. return;
  1817. }
  1818. var sx = m[0] * m[0] + m[1] * m[1];
  1819. var sy = m[2] * m[2] + m[3] * m[3];
  1820. if (isNotAroundZero(sx - 1)) {
  1821. sx = Math.sqrt(sx);
  1822. }
  1823. if (isNotAroundZero(sy - 1)) {
  1824. sy = Math.sqrt(sy);
  1825. }
  1826. if (m[0] < 0) {
  1827. sx = -sx;
  1828. }
  1829. if (m[3] < 0) {
  1830. sy = -sy;
  1831. }
  1832. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1833. if (sx < 0 && sy < 0) {
  1834. this.rotation += Math.PI;
  1835. sx = -sx;
  1836. sy = -sy;
  1837. }
  1838. this.x = m[4];
  1839. this.y = m[5];
  1840. this.scaleX = sx;
  1841. this.scaleY = sy;
  1842. };
  1843. Transformable.prototype.decomposeTransform = function () {
  1844. if (!this.transform) {
  1845. return;
  1846. }
  1847. var parent = this.parent;
  1848. var m = this.transform;
  1849. if (parent && parent.transform) {
  1850. mul$1(tmpTransform, parent.invTransform, m);
  1851. m = tmpTransform;
  1852. }
  1853. var ox = this.originX;
  1854. var oy = this.originY;
  1855. if (ox || oy) {
  1856. originTransform[4] = ox;
  1857. originTransform[5] = oy;
  1858. mul$1(tmpTransform, m, originTransform);
  1859. tmpTransform[4] -= ox;
  1860. tmpTransform[5] -= oy;
  1861. m = tmpTransform;
  1862. }
  1863. this.setLocalTransform(m);
  1864. };
  1865. Transformable.prototype.getGlobalScale = function (out) {
  1866. var m = this.transform;
  1867. out = out || [];
  1868. if (!m) {
  1869. out[0] = 1;
  1870. out[1] = 1;
  1871. return out;
  1872. }
  1873. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1874. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1875. if (m[0] < 0) {
  1876. out[0] = -out[0];
  1877. }
  1878. if (m[3] < 0) {
  1879. out[1] = -out[1];
  1880. }
  1881. return out;
  1882. };
  1883. Transformable.prototype.transformCoordToLocal = function (x, y) {
  1884. var v2 = [x, y];
  1885. var invTransform = this.invTransform;
  1886. if (invTransform) {
  1887. applyTransform(v2, v2, invTransform);
  1888. }
  1889. return v2;
  1890. };
  1891. Transformable.prototype.transformCoordToGlobal = function (x, y) {
  1892. var v2 = [x, y];
  1893. var transform = this.transform;
  1894. if (transform) {
  1895. applyTransform(v2, v2, transform);
  1896. }
  1897. return v2;
  1898. };
  1899. Transformable.prototype.getLineScale = function () {
  1900. var m = this.transform;
  1901. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  1902. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  1903. : 1;
  1904. };
  1905. Transformable.getLocalTransform = function (target, m) {
  1906. m = m || [];
  1907. mIdentity(m);
  1908. var ox = target.originX || 0;
  1909. var oy = target.originY || 0;
  1910. var sx = target.scaleX;
  1911. var sy = target.scaleY;
  1912. var rotation = target.rotation || 0;
  1913. var x = target.x;
  1914. var y = target.y;
  1915. m[4] -= ox;
  1916. m[5] -= oy;
  1917. m[0] *= sx;
  1918. m[1] *= sy;
  1919. m[2] *= sx;
  1920. m[3] *= sy;
  1921. m[4] *= sx;
  1922. m[5] *= sy;
  1923. if (rotation) {
  1924. rotate(m, m, rotation);
  1925. }
  1926. m[4] += ox;
  1927. m[5] += oy;
  1928. m[4] += x;
  1929. m[5] += y;
  1930. return m;
  1931. };
  1932. Transformable.initDefaultProps = (function () {
  1933. var proto = Transformable.prototype;
  1934. proto.x = 0;
  1935. proto.y = 0;
  1936. proto.scaleX = 1;
  1937. proto.scaleY = 1;
  1938. proto.originX = 0;
  1939. proto.originY = 0;
  1940. proto.rotation = 0;
  1941. proto.globalScaleRatio = 1;
  1942. })();
  1943. return Transformable;
  1944. }());
  1945. var easing = {
  1946. linear: function (k) {
  1947. return k;
  1948. },
  1949. quadraticIn: function (k) {
  1950. return k * k;
  1951. },
  1952. quadraticOut: function (k) {
  1953. return k * (2 - k);
  1954. },
  1955. quadraticInOut: function (k) {
  1956. if ((k *= 2) < 1) {
  1957. return 0.5 * k * k;
  1958. }
  1959. return -0.5 * (--k * (k - 2) - 1);
  1960. },
  1961. cubicIn: function (k) {
  1962. return k * k * k;
  1963. },
  1964. cubicOut: function (k) {
  1965. return --k * k * k + 1;
  1966. },
  1967. cubicInOut: function (k) {
  1968. if ((k *= 2) < 1) {
  1969. return 0.5 * k * k * k;
  1970. }
  1971. return 0.5 * ((k -= 2) * k * k + 2);
  1972. },
  1973. quarticIn: function (k) {
  1974. return k * k * k * k;
  1975. },
  1976. quarticOut: function (k) {
  1977. return 1 - (--k * k * k * k);
  1978. },
  1979. quarticInOut: function (k) {
  1980. if ((k *= 2) < 1) {
  1981. return 0.5 * k * k * k * k;
  1982. }
  1983. return -0.5 * ((k -= 2) * k * k * k - 2);
  1984. },
  1985. quinticIn: function (k) {
  1986. return k * k * k * k * k;
  1987. },
  1988. quinticOut: function (k) {
  1989. return --k * k * k * k * k + 1;
  1990. },
  1991. quinticInOut: function (k) {
  1992. if ((k *= 2) < 1) {
  1993. return 0.5 * k * k * k * k * k;
  1994. }
  1995. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  1996. },
  1997. sinusoidalIn: function (k) {
  1998. return 1 - Math.cos(k * Math.PI / 2);
  1999. },
  2000. sinusoidalOut: function (k) {
  2001. return Math.sin(k * Math.PI / 2);
  2002. },
  2003. sinusoidalInOut: function (k) {
  2004. return 0.5 * (1 - Math.cos(Math.PI * k));
  2005. },
  2006. exponentialIn: function (k) {
  2007. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2008. },
  2009. exponentialOut: function (k) {
  2010. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2011. },
  2012. exponentialInOut: function (k) {
  2013. if (k === 0) {
  2014. return 0;
  2015. }
  2016. if (k === 1) {
  2017. return 1;
  2018. }
  2019. if ((k *= 2) < 1) {
  2020. return 0.5 * Math.pow(1024, k - 1);
  2021. }
  2022. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2023. },
  2024. circularIn: function (k) {
  2025. return 1 - Math.sqrt(1 - k * k);
  2026. },
  2027. circularOut: function (k) {
  2028. return Math.sqrt(1 - (--k * k));
  2029. },
  2030. circularInOut: function (k) {
  2031. if ((k *= 2) < 1) {
  2032. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2033. }
  2034. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2035. },
  2036. elasticIn: function (k) {
  2037. var s;
  2038. var a = 0.1;
  2039. var p = 0.4;
  2040. if (k === 0) {
  2041. return 0;
  2042. }
  2043. if (k === 1) {
  2044. return 1;
  2045. }
  2046. if (!a || a < 1) {
  2047. a = 1;
  2048. s = p / 4;
  2049. }
  2050. else {
  2051. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2052. }
  2053. return -(a * Math.pow(2, 10 * (k -= 1))
  2054. * Math.sin((k - s) * (2 * Math.PI) / p));
  2055. },
  2056. elasticOut: function (k) {
  2057. var s;
  2058. var a = 0.1;
  2059. var p = 0.4;
  2060. if (k === 0) {
  2061. return 0;
  2062. }
  2063. if (k === 1) {
  2064. return 1;
  2065. }
  2066. if (!a || a < 1) {
  2067. a = 1;
  2068. s = p / 4;
  2069. }
  2070. else {
  2071. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2072. }
  2073. return (a * Math.pow(2, -10 * k)
  2074. * Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2075. },
  2076. elasticInOut: function (k) {
  2077. var s;
  2078. var a = 0.1;
  2079. var p = 0.4;
  2080. if (k === 0) {
  2081. return 0;
  2082. }
  2083. if (k === 1) {
  2084. return 1;
  2085. }
  2086. if (!a || a < 1) {
  2087. a = 1;
  2088. s = p / 4;
  2089. }
  2090. else {
  2091. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2092. }
  2093. if ((k *= 2) < 1) {
  2094. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2095. * Math.sin((k - s) * (2 * Math.PI) / p));
  2096. }
  2097. return a * Math.pow(2, -10 * (k -= 1))
  2098. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2099. },
  2100. backIn: function (k) {
  2101. var s = 1.70158;
  2102. return k * k * ((s + 1) * k - s);
  2103. },
  2104. backOut: function (k) {
  2105. var s = 1.70158;
  2106. return --k * k * ((s + 1) * k + s) + 1;
  2107. },
  2108. backInOut: function (k) {
  2109. var s = 1.70158 * 1.525;
  2110. if ((k *= 2) < 1) {
  2111. return 0.5 * (k * k * ((s + 1) * k - s));
  2112. }
  2113. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2114. },
  2115. bounceIn: function (k) {
  2116. return 1 - easing.bounceOut(1 - k);
  2117. },
  2118. bounceOut: function (k) {
  2119. if (k < (1 / 2.75)) {
  2120. return 7.5625 * k * k;
  2121. }
  2122. else if (k < (2 / 2.75)) {
  2123. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2124. }
  2125. else if (k < (2.5 / 2.75)) {
  2126. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2127. }
  2128. else {
  2129. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2130. }
  2131. },
  2132. bounceInOut: function (k) {
  2133. if (k < 0.5) {
  2134. return easing.bounceIn(k * 2) * 0.5;
  2135. }
  2136. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2137. }
  2138. };
  2139. var Clip = (function () {
  2140. function Clip(opts) {
  2141. this._initialized = false;
  2142. this._startTime = 0;
  2143. this._pausedTime = 0;
  2144. this._paused = false;
  2145. this._life = opts.life || 1000;
  2146. this._delay = opts.delay || 0;
  2147. this.loop = opts.loop == null ? false : opts.loop;
  2148. this.gap = opts.gap || 0;
  2149. this.easing = opts.easing || 'linear';
  2150. this.onframe = opts.onframe;
  2151. this.ondestroy = opts.ondestroy;
  2152. this.onrestart = opts.onrestart;
  2153. }
  2154. Clip.prototype.step = function (globalTime, deltaTime) {
  2155. if (!this._initialized) {
  2156. this._startTime = globalTime + this._delay;
  2157. this._initialized = true;
  2158. }
  2159. if (this._paused) {
  2160. this._pausedTime += deltaTime;
  2161. return;
  2162. }
  2163. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2164. if (percent < 0) {
  2165. percent = 0;
  2166. }
  2167. percent = Math.min(percent, 1);
  2168. var easing$1 = this.easing;
  2169. var easingFunc = typeof easing$1 === 'string'
  2170. ? easing[easing$1] : easing$1;
  2171. var schedule = typeof easingFunc === 'function'
  2172. ? easingFunc(percent)
  2173. : percent;
  2174. this.onframe && this.onframe(schedule);
  2175. if (percent === 1) {
  2176. if (this.loop) {
  2177. this._restart(globalTime);
  2178. this.onrestart && this.onrestart();
  2179. }
  2180. else {
  2181. return true;
  2182. }
  2183. }
  2184. return false;
  2185. };
  2186. Clip.prototype._restart = function (globalTime) {
  2187. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2188. this._startTime = globalTime - remainder + this.gap;
  2189. this._pausedTime = 0;
  2190. };
  2191. Clip.prototype.pause = function () {
  2192. this._paused = true;
  2193. };
  2194. Clip.prototype.resume = function () {
  2195. this._paused = false;
  2196. };
  2197. return Clip;
  2198. }());
  2199. var Entry = (function () {
  2200. function Entry(val) {
  2201. this.value = val;
  2202. }
  2203. return Entry;
  2204. }());
  2205. var LinkedList = (function () {
  2206. function LinkedList() {
  2207. this._len = 0;
  2208. }
  2209. LinkedList.prototype.insert = function (val) {
  2210. var entry = new Entry(val);
  2211. this.insertEntry(entry);
  2212. return entry;
  2213. };
  2214. LinkedList.prototype.insertEntry = function (entry) {
  2215. if (!this.head) {
  2216. this.head = this.tail = entry;
  2217. }
  2218. else {
  2219. this.tail.next = entry;
  2220. entry.prev = this.tail;
  2221. entry.next = null;
  2222. this.tail = entry;
  2223. }
  2224. this._len++;
  2225. };
  2226. LinkedList.prototype.remove = function (entry) {
  2227. var prev = entry.prev;
  2228. var next = entry.next;
  2229. if (prev) {
  2230. prev.next = next;
  2231. }
  2232. else {
  2233. this.head = next;
  2234. }
  2235. if (next) {
  2236. next.prev = prev;
  2237. }
  2238. else {
  2239. this.tail = prev;
  2240. }
  2241. entry.next = entry.prev = null;
  2242. this._len--;
  2243. };
  2244. LinkedList.prototype.len = function () {
  2245. return this._len;
  2246. };
  2247. LinkedList.prototype.clear = function () {
  2248. this.head = this.tail = null;
  2249. this._len = 0;
  2250. };
  2251. return LinkedList;
  2252. }());
  2253. var LRU = (function () {
  2254. function LRU(maxSize) {
  2255. this._list = new LinkedList();
  2256. this._maxSize = 10;
  2257. this._map = {};
  2258. this._maxSize = maxSize;
  2259. }
  2260. LRU.prototype.put = function (key, value) {
  2261. var list = this._list;
  2262. var map = this._map;
  2263. var removed = null;
  2264. if (map[key] == null) {
  2265. var len = list.len();
  2266. var entry = this._lastRemovedEntry;
  2267. if (len >= this._maxSize && len > 0) {
  2268. var leastUsedEntry = list.head;
  2269. list.remove(leastUsedEntry);
  2270. delete map[leastUsedEntry.key];
  2271. removed = leastUsedEntry.value;
  2272. this._lastRemovedEntry = leastUsedEntry;
  2273. }
  2274. if (entry) {
  2275. entry.value = value;
  2276. }
  2277. else {
  2278. entry = new Entry(value);
  2279. }
  2280. entry.key = key;
  2281. list.insertEntry(entry);
  2282. map[key] = entry;
  2283. }
  2284. return removed;
  2285. };
  2286. LRU.prototype.get = function (key) {
  2287. var entry = this._map[key];
  2288. var list = this._list;
  2289. if (entry != null) {
  2290. if (entry !== list.tail) {
  2291. list.remove(entry);
  2292. list.insertEntry(entry);
  2293. }
  2294. return entry.value;
  2295. }
  2296. };
  2297. LRU.prototype.clear = function () {
  2298. this._list.clear();
  2299. this._map = {};
  2300. };
  2301. LRU.prototype.len = function () {
  2302. return this._list.len();
  2303. };
  2304. return LRU;
  2305. }());
  2306. var kCSSColorTable = {
  2307. 'transparent': [0, 0, 0, 0], 'aliceblue': [240, 248, 255, 1],
  2308. 'antiquewhite': [250, 235, 215, 1], 'aqua': [0, 255, 255, 1],
  2309. 'aquamarine': [127, 255, 212, 1], 'azure': [240, 255, 255, 1],
  2310. 'beige': [245, 245, 220, 1], 'bisque': [255, 228, 196, 1],
  2311. 'black': [0, 0, 0, 1], 'blanchedalmond': [255, 235, 205, 1],
  2312. 'blue': [0, 0, 255, 1], 'blueviolet': [138, 43, 226, 1],
  2313. 'brown': [165, 42, 42, 1], 'burlywood': [222, 184, 135, 1],
  2314. 'cadetblue': [95, 158, 160, 1], 'chartreuse': [127, 255, 0, 1],
  2315. 'chocolate': [210, 105, 30, 1], 'coral': [255, 127, 80, 1],
  2316. 'cornflowerblue': [100, 149, 237, 1], 'cornsilk': [255, 248, 220, 1],
  2317. 'crimson': [220, 20, 60, 1], 'cyan': [0, 255, 255, 1],
  2318. 'darkblue': [0, 0, 139, 1], 'darkcyan': [0, 139, 139, 1],
  2319. 'darkgoldenrod': [184, 134, 11, 1], 'darkgray': [169, 169, 169, 1],
  2320. 'darkgreen': [0, 100, 0, 1], 'darkgrey': [169, 169, 169, 1],
  2321. 'darkkhaki': [189, 183, 107, 1], 'darkmagenta': [139, 0, 139, 1],
  2322. 'darkolivegreen': [85, 107, 47, 1], 'darkorange': [255, 140, 0, 1],
  2323. 'darkorchid': [153, 50, 204, 1], 'darkred': [139, 0, 0, 1],
  2324. 'darksalmon': [233, 150, 122, 1], 'darkseagreen': [143, 188, 143, 1],
  2325. 'darkslateblue': [72, 61, 139, 1], 'darkslategray': [47, 79, 79, 1],
  2326. 'darkslategrey': [47, 79, 79, 1], 'darkturquoise': [0, 206, 209, 1],
  2327. 'darkviolet': [148, 0, 211, 1], 'deeppink': [255, 20, 147, 1],
  2328. 'deepskyblue': [0, 191, 255, 1], 'dimgray': [105, 105, 105, 1],
  2329. 'dimgrey': [105, 105, 105, 1], 'dodgerblue': [30, 144, 255, 1],
  2330. 'firebrick': [178, 34, 34, 1], 'floralwhite': [255, 250, 240, 1],
  2331. 'forestgreen': [34, 139, 34, 1], 'fuchsia': [255, 0, 255, 1],
  2332. 'gainsboro': [220, 220, 220, 1], 'ghostwhite': [248, 248, 255, 1],
  2333. 'gold': [255, 215, 0, 1], 'goldenrod': [218, 165, 32, 1],
  2334. 'gray': [128, 128, 128, 1], 'green': [0, 128, 0, 1],
  2335. 'greenyellow': [173, 255, 47, 1], 'grey': [128, 128, 128, 1],
  2336. 'honeydew': [240, 255, 240, 1], 'hotpink': [255, 105, 180, 1],
  2337. 'indianred': [205, 92, 92, 1], 'indigo': [75, 0, 130, 1],
  2338. 'ivory': [255, 255, 240, 1], 'khaki': [240, 230, 140, 1],
  2339. 'lavender': [230, 230, 250, 1], 'lavenderblush': [255, 240, 245, 1],
  2340. 'lawngreen': [124, 252, 0, 1], 'lemonchiffon': [255, 250, 205, 1],
  2341. 'lightblue': [173, 216, 230, 1], 'lightcoral': [240, 128, 128, 1],
  2342. 'lightcyan': [224, 255, 255, 1], 'lightgoldenrodyellow': [250, 250, 210, 1],
  2343. 'lightgray': [211, 211, 211, 1], 'lightgreen': [144, 238, 144, 1],
  2344. 'lightgrey': [211, 211, 211, 1], 'lightpink': [255, 182, 193, 1],
  2345. 'lightsalmon': [255, 160, 122, 1], 'lightseagreen': [32, 178, 170, 1],
  2346. 'lightskyblue': [135, 206, 250, 1], 'lightslategray': [119, 136, 153, 1],
  2347. 'lightslategrey': [119, 136, 153, 1], 'lightsteelblue': [176, 196, 222, 1],
  2348. 'lightyellow': [255, 255, 224, 1], 'lime': [0, 255, 0, 1],
  2349. 'limegreen': [50, 205, 50, 1], 'linen': [250, 240, 230, 1],
  2350. 'magenta': [255, 0, 255, 1], 'maroon': [128, 0, 0, 1],
  2351. 'mediumaquamarine': [102, 205, 170, 1], 'mediumblue': [0, 0, 205, 1],
  2352. 'mediumorchid': [186, 85, 211, 1], 'mediumpurple': [147, 112, 219, 1],
  2353. 'mediumseagreen': [60, 179, 113, 1], 'mediumslateblue': [123, 104, 238, 1],
  2354. 'mediumspringgreen': [0, 250, 154, 1], 'mediumturquoise': [72, 209, 204, 1],
  2355. 'mediumvioletred': [199, 21, 133, 1], 'midnightblue': [25, 25, 112, 1],
  2356. 'mintcream': [245, 255, 250, 1], 'mistyrose': [255, 228, 225, 1],
  2357. 'moccasin': [255, 228, 181, 1], 'navajowhite': [255, 222, 173, 1],
  2358. 'navy': [0, 0, 128, 1], 'oldlace': [253, 245, 230, 1],
  2359. 'olive': [128, 128, 0, 1], 'olivedrab': [107, 142, 35, 1],
  2360. 'orange': [255, 165, 0, 1], 'orangered': [255, 69, 0, 1],
  2361. 'orchid': [218, 112, 214, 1], 'palegoldenrod': [238, 232, 170, 1],
  2362. 'palegreen': [152, 251, 152, 1], 'paleturquoise': [175, 238, 238, 1],
  2363. 'palevioletred': [219, 112, 147, 1], 'papayawhip': [255, 239, 213, 1],
  2364. 'peachpuff': [255, 218, 185, 1], 'peru': [205, 133, 63, 1],
  2365. 'pink': [255, 192, 203, 1], 'plum': [221, 160, 221, 1],
  2366. 'powderblue': [176, 224, 230, 1], 'purple': [128, 0, 128, 1],
  2367. 'red': [255, 0, 0, 1], 'rosybrown': [188, 143, 143, 1],
  2368. 'royalblue': [65, 105, 225, 1], 'saddlebrown': [139, 69, 19, 1],
  2369. 'salmon': [250, 128, 114, 1], 'sandybrown': [244, 164, 96, 1],
  2370. 'seagreen': [46, 139, 87, 1], 'seashell': [255, 245, 238, 1],
  2371. 'sienna': [160, 82, 45, 1], 'silver': [192, 192, 192, 1],
  2372. 'skyblue': [135, 206, 235, 1], 'slateblue': [106, 90, 205, 1],
  2373. 'slategray': [112, 128, 144, 1], 'slategrey': [112, 128, 144, 1],
  2374. 'snow': [255, 250, 250, 1], 'springgreen': [0, 255, 127, 1],
  2375. 'steelblue': [70, 130, 180, 1], 'tan': [210, 180, 140, 1],
  2376. 'teal': [0, 128, 128, 1], 'thistle': [216, 191, 216, 1],
  2377. 'tomato': [255, 99, 71, 1], 'turquoise': [64, 224, 208, 1],
  2378. 'violet': [238, 130, 238, 1], 'wheat': [245, 222, 179, 1],
  2379. 'white': [255, 255, 255, 1], 'whitesmoke': [245, 245, 245, 1],
  2380. 'yellow': [255, 255, 0, 1], 'yellowgreen': [154, 205, 50, 1]
  2381. };
  2382. function clampCssByte(i) {
  2383. i = Math.round(i);
  2384. return i < 0 ? 0 : i > 255 ? 255 : i;
  2385. }
  2386. function clampCssAngle(i) {
  2387. i = Math.round(i);
  2388. return i < 0 ? 0 : i > 360 ? 360 : i;
  2389. }
  2390. function clampCssFloat(f) {
  2391. return f < 0 ? 0 : f > 1 ? 1 : f;
  2392. }
  2393. function parseCssInt(val) {
  2394. var str = val;
  2395. if (str.length && str.charAt(str.length - 1) === '%') {
  2396. return clampCssByte(parseFloat(str) / 100 * 255);
  2397. }
  2398. return clampCssByte(parseInt(str, 10));
  2399. }
  2400. function parseCssFloat(val) {
  2401. var str = val;
  2402. if (str.length && str.charAt(str.length - 1) === '%') {
  2403. return clampCssFloat(parseFloat(str) / 100);
  2404. }
  2405. return clampCssFloat(parseFloat(str));
  2406. }
  2407. function cssHueToRgb(m1, m2, h) {
  2408. if (h < 0) {
  2409. h += 1;
  2410. }
  2411. else if (h > 1) {
  2412. h -= 1;
  2413. }
  2414. if (h * 6 < 1) {
  2415. return m1 + (m2 - m1) * h * 6;
  2416. }
  2417. if (h * 2 < 1) {
  2418. return m2;
  2419. }
  2420. if (h * 3 < 2) {
  2421. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  2422. }
  2423. return m1;
  2424. }
  2425. function lerpNumber(a, b, p) {
  2426. return a + (b - a) * p;
  2427. }
  2428. function setRgba(out, r, g, b, a) {
  2429. out[0] = r;
  2430. out[1] = g;
  2431. out[2] = b;
  2432. out[3] = a;
  2433. return out;
  2434. }
  2435. function copyRgba(out, a) {
  2436. out[0] = a[0];
  2437. out[1] = a[1];
  2438. out[2] = a[2];
  2439. out[3] = a[3];
  2440. return out;
  2441. }
  2442. var colorCache = new LRU(20);
  2443. var lastRemovedArr = null;
  2444. function putToCache(colorStr, rgbaArr) {
  2445. if (lastRemovedArr) {
  2446. copyRgba(lastRemovedArr, rgbaArr);
  2447. }
  2448. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2449. }
  2450. function parse(colorStr, rgbaArr) {
  2451. if (!colorStr) {
  2452. return;
  2453. }
  2454. rgbaArr = rgbaArr || [];
  2455. var cached = colorCache.get(colorStr);
  2456. if (cached) {
  2457. return copyRgba(rgbaArr, cached);
  2458. }
  2459. colorStr = colorStr + '';
  2460. var str = colorStr.replace(/ /g, '').toLowerCase();
  2461. if (str in kCSSColorTable) {
  2462. copyRgba(rgbaArr, kCSSColorTable[str]);
  2463. putToCache(colorStr, rgbaArr);
  2464. return rgbaArr;
  2465. }
  2466. var strLen = str.length;
  2467. if (str.charAt(0) === '#') {
  2468. if (strLen === 4 || strLen === 5) {
  2469. var iv = parseInt(str.slice(1, 4), 16);
  2470. if (!(iv >= 0 && iv <= 0xfff)) {
  2471. setRgba(rgbaArr, 0, 0, 0, 1);
  2472. return;
  2473. }
  2474. 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);
  2475. putToCache(colorStr, rgbaArr);
  2476. return rgbaArr;
  2477. }
  2478. else if (strLen === 7 || strLen === 9) {
  2479. var iv = parseInt(str.slice(1, 7), 16);
  2480. if (!(iv >= 0 && iv <= 0xffffff)) {
  2481. setRgba(rgbaArr, 0, 0, 0, 1);
  2482. return;
  2483. }
  2484. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, strLen === 9 ? parseInt(str.slice(7), 16) / 0xff : 1);
  2485. putToCache(colorStr, rgbaArr);
  2486. return rgbaArr;
  2487. }
  2488. return;
  2489. }
  2490. var op = str.indexOf('(');
  2491. var ep = str.indexOf(')');
  2492. if (op !== -1 && ep + 1 === strLen) {
  2493. var fname = str.substr(0, op);
  2494. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2495. var alpha = 1;
  2496. switch (fname) {
  2497. case 'rgba':
  2498. if (params.length !== 4) {
  2499. return params.length === 3
  2500. ? setRgba(rgbaArr, +params[0], +params[1], +params[2], 1)
  2501. : setRgba(rgbaArr, 0, 0, 0, 1);
  2502. }
  2503. alpha = parseCssFloat(params.pop());
  2504. case 'rgb':
  2505. if (params.length !== 3) {
  2506. setRgba(rgbaArr, 0, 0, 0, 1);
  2507. return;
  2508. }
  2509. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  2510. putToCache(colorStr, rgbaArr);
  2511. return rgbaArr;
  2512. case 'hsla':
  2513. if (params.length !== 4) {
  2514. setRgba(rgbaArr, 0, 0, 0, 1);
  2515. return;
  2516. }
  2517. params[3] = parseCssFloat(params[3]);
  2518. hsla2rgba(params, rgbaArr);
  2519. putToCache(colorStr, rgbaArr);
  2520. return rgbaArr;
  2521. case 'hsl':
  2522. if (params.length !== 3) {
  2523. setRgba(rgbaArr, 0, 0, 0, 1);
  2524. return;
  2525. }
  2526. hsla2rgba(params, rgbaArr);
  2527. putToCache(colorStr, rgbaArr);
  2528. return rgbaArr;
  2529. default:
  2530. return;
  2531. }
  2532. }
  2533. setRgba(rgbaArr, 0, 0, 0, 1);
  2534. return;
  2535. }
  2536. function hsla2rgba(hsla, rgba) {
  2537. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360;
  2538. var s = parseCssFloat(hsla[1]);
  2539. var l = parseCssFloat(hsla[2]);
  2540. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2541. var m1 = l * 2 - m2;
  2542. rgba = rgba || [];
  2543. 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);
  2544. if (hsla.length === 4) {
  2545. rgba[3] = hsla[3];
  2546. }
  2547. return rgba;
  2548. }
  2549. function rgba2hsla(rgba) {
  2550. if (!rgba) {
  2551. return;
  2552. }
  2553. var R = rgba[0] / 255;
  2554. var G = rgba[1] / 255;
  2555. var B = rgba[2] / 255;
  2556. var vMin = Math.min(R, G, B);
  2557. var vMax = Math.max(R, G, B);
  2558. var delta = vMax - vMin;
  2559. var L = (vMax + vMin) / 2;
  2560. var H;
  2561. var S;
  2562. if (delta === 0) {
  2563. H = 0;
  2564. S = 0;
  2565. }
  2566. else {
  2567. if (L < 0.5) {
  2568. S = delta / (vMax + vMin);
  2569. }
  2570. else {
  2571. S = delta / (2 - vMax - vMin);
  2572. }
  2573. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2574. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2575. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2576. if (R === vMax) {
  2577. H = deltaB - deltaG;
  2578. }
  2579. else if (G === vMax) {
  2580. H = (1 / 3) + deltaR - deltaB;
  2581. }
  2582. else if (B === vMax) {
  2583. H = (2 / 3) + deltaG - deltaR;
  2584. }
  2585. if (H < 0) {
  2586. H += 1;
  2587. }
  2588. if (H > 1) {
  2589. H -= 1;
  2590. }
  2591. }
  2592. var hsla = [H * 360, S, L];
  2593. if (rgba[3] != null) {
  2594. hsla.push(rgba[3]);
  2595. }
  2596. return hsla;
  2597. }
  2598. function lift(color, level) {
  2599. var colorArr = parse(color);
  2600. if (colorArr) {
  2601. for (var i = 0; i < 3; i++) {
  2602. if (level < 0) {
  2603. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2604. }
  2605. else {
  2606. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2607. }
  2608. if (colorArr[i] > 255) {
  2609. colorArr[i] = 255;
  2610. }
  2611. else if (colorArr[i] < 0) {
  2612. colorArr[i] = 0;
  2613. }
  2614. }
  2615. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  2616. }
  2617. }
  2618. function toHex(color) {
  2619. var colorArr = parse(color);
  2620. if (colorArr) {
  2621. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  2622. }
  2623. }
  2624. function fastLerp(normalizedValue, colors, out) {
  2625. if (!(colors && colors.length)
  2626. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2627. return;
  2628. }
  2629. out = out || [];
  2630. var value = normalizedValue * (colors.length - 1);
  2631. var leftIndex = Math.floor(value);
  2632. var rightIndex = Math.ceil(value);
  2633. var leftColor = colors[leftIndex];
  2634. var rightColor = colors[rightIndex];
  2635. var dv = value - leftIndex;
  2636. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  2637. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  2638. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  2639. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  2640. return out;
  2641. }
  2642. var fastMapToColor = fastLerp;
  2643. function lerp$1(normalizedValue, colors, fullOutput) {
  2644. if (!(colors && colors.length)
  2645. || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  2646. return;
  2647. }
  2648. var value = normalizedValue * (colors.length - 1);
  2649. var leftIndex = Math.floor(value);
  2650. var rightIndex = Math.ceil(value);
  2651. var leftColor = parse(colors[leftIndex]);
  2652. var rightColor = parse(colors[rightIndex]);
  2653. var dv = value - leftIndex;
  2654. var color = stringify([
  2655. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  2656. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  2657. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  2658. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  2659. ], 'rgba');
  2660. return fullOutput
  2661. ? {
  2662. color: color,
  2663. leftIndex: leftIndex,
  2664. rightIndex: rightIndex,
  2665. value: value
  2666. }
  2667. : color;
  2668. }
  2669. var mapToColor = lerp$1;
  2670. function modifyHSL(color, h, s, l) {
  2671. var colorArr = parse(color);
  2672. if (color) {
  2673. colorArr = rgba2hsla(colorArr);
  2674. h != null && (colorArr[0] = clampCssAngle(h));
  2675. s != null && (colorArr[1] = parseCssFloat(s));
  2676. l != null && (colorArr[2] = parseCssFloat(l));
  2677. return stringify(hsla2rgba(colorArr), 'rgba');
  2678. }
  2679. }
  2680. function modifyAlpha(color, alpha) {
  2681. var colorArr = parse(color);
  2682. if (colorArr && alpha != null) {
  2683. colorArr[3] = clampCssFloat(alpha);
  2684. return stringify(colorArr, 'rgba');
  2685. }
  2686. }
  2687. function stringify(arrColor, type) {
  2688. if (!arrColor || !arrColor.length) {
  2689. return;
  2690. }
  2691. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  2692. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  2693. colorStr += ',' + arrColor[3];
  2694. }
  2695. return type + '(' + colorStr + ')';
  2696. }
  2697. function lum(color, backgroundLum) {
  2698. var arr = parse(color);
  2699. return arr
  2700. ? (0.299 * arr[0] + 0.587 * arr[1] + 0.114 * arr[2]) * arr[3] / 255
  2701. + (1 - arr[3]) * backgroundLum
  2702. : 0;
  2703. }
  2704. function random() {
  2705. var r = Math.round(Math.random() * 255);
  2706. var g = Math.round(Math.random() * 255);
  2707. var b = Math.round(Math.random() * 255);
  2708. return 'rgb(' + r + ',' + g + ',' + b + ')';
  2709. }
  2710. var color = /*#__PURE__*/Object.freeze({
  2711. __proto__: null,
  2712. parse: parse,
  2713. lift: lift,
  2714. toHex: toHex,
  2715. fastLerp: fastLerp,
  2716. fastMapToColor: fastMapToColor,
  2717. lerp: lerp$1,
  2718. mapToColor: mapToColor,
  2719. modifyHSL: modifyHSL,
  2720. modifyAlpha: modifyAlpha,
  2721. stringify: stringify,
  2722. lum: lum,
  2723. random: random
  2724. });
  2725. var arraySlice = Array.prototype.slice;
  2726. function interpolateNumber(p0, p1, percent) {
  2727. return (p1 - p0) * percent + p0;
  2728. }
  2729. function step(p0, p1, percent) {
  2730. return percent > 0.5 ? p1 : p0;
  2731. }
  2732. function interpolate1DArray(out, p0, p1, percent) {
  2733. var len = p0.length;
  2734. for (var i = 0; i < len; i++) {
  2735. out[i] = interpolateNumber(p0[i], p1[i], percent);
  2736. }
  2737. }
  2738. function interpolate2DArray(out, p0, p1, percent) {
  2739. var len = p0.length;
  2740. var len2 = len && p0[0].length;
  2741. for (var i = 0; i < len; i++) {
  2742. if (!out[i]) {
  2743. out[i] = [];
  2744. }
  2745. for (var j = 0; j < len2; j++) {
  2746. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  2747. }
  2748. }
  2749. }
  2750. function add1DArray(out, p0, p1, sign) {
  2751. var len = p0.length;
  2752. for (var i = 0; i < len; i++) {
  2753. out[i] = p0[i] + p1[i] * sign;
  2754. }
  2755. return out;
  2756. }
  2757. function add2DArray(out, p0, p1, sign) {
  2758. var len = p0.length;
  2759. var len2 = len && p0[0].length;
  2760. for (var i = 0; i < len; i++) {
  2761. if (!out[i]) {
  2762. out[i] = [];
  2763. }
  2764. for (var j = 0; j < len2; j++) {
  2765. out[i][j] = p0[i][j] + p1[i][j] * sign;
  2766. }
  2767. }
  2768. return out;
  2769. }
  2770. function fillArray(val0, val1, arrDim) {
  2771. var arr0 = val0;
  2772. var arr1 = val1;
  2773. if (!arr0.push || !arr1.push) {
  2774. return;
  2775. }
  2776. var arr0Len = arr0.length;
  2777. var arr1Len = arr1.length;
  2778. if (arr0Len !== arr1Len) {
  2779. var isPreviousLarger = arr0Len > arr1Len;
  2780. if (isPreviousLarger) {
  2781. arr0.length = arr1Len;
  2782. }
  2783. else {
  2784. for (var i = arr0Len; i < arr1Len; i++) {
  2785. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  2786. }
  2787. }
  2788. }
  2789. var len2 = arr0[0] && arr0[0].length;
  2790. for (var i = 0; i < arr0.length; i++) {
  2791. if (arrDim === 1) {
  2792. if (isNaN(arr0[i])) {
  2793. arr0[i] = arr1[i];
  2794. }
  2795. }
  2796. else {
  2797. for (var j = 0; j < len2; j++) {
  2798. if (isNaN(arr0[i][j])) {
  2799. arr0[i][j] = arr1[i][j];
  2800. }
  2801. }
  2802. }
  2803. }
  2804. }
  2805. function is1DArraySame(arr0, arr1) {
  2806. var len = arr0.length;
  2807. if (len !== arr1.length) {
  2808. return false;
  2809. }
  2810. for (var i = 0; i < len; i++) {
  2811. if (arr0[i] !== arr1[i]) {
  2812. return false;
  2813. }
  2814. }
  2815. return true;
  2816. }
  2817. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  2818. var v0 = (p2 - p0) * 0.5;
  2819. var v1 = (p3 - p1) * 0.5;
  2820. return (2 * (p1 - p2) + v0 + v1) * t3
  2821. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  2822. + v0 * t + p1;
  2823. }
  2824. function catmullRomInterpolate1DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2825. var len = p0.length;
  2826. for (var i = 0; i < len; i++) {
  2827. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  2828. }
  2829. }
  2830. function catmullRomInterpolate2DArray(out, p0, p1, p2, p3, t, t2, t3) {
  2831. var len = p0.length;
  2832. var len2 = p0[0].length;
  2833. for (var i = 0; i < len; i++) {
  2834. if (!out[i]) {
  2835. out[1] = [];
  2836. }
  2837. for (var j = 0; j < len2; j++) {
  2838. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  2839. }
  2840. }
  2841. }
  2842. function cloneValue(value) {
  2843. if (isArrayLike(value)) {
  2844. var len = value.length;
  2845. if (isArrayLike(value[0])) {
  2846. var ret = [];
  2847. for (var i = 0; i < len; i++) {
  2848. ret.push(arraySlice.call(value[i]));
  2849. }
  2850. return ret;
  2851. }
  2852. return arraySlice.call(value);
  2853. }
  2854. return value;
  2855. }
  2856. function rgba2String(rgba) {
  2857. rgba[0] = Math.floor(rgba[0]);
  2858. rgba[1] = Math.floor(rgba[1]);
  2859. rgba[2] = Math.floor(rgba[2]);
  2860. return 'rgba(' + rgba.join(',') + ')';
  2861. }
  2862. function guessArrayDim(value) {
  2863. return isArrayLike(value && value[0]) ? 2 : 1;
  2864. }
  2865. var tmpRgba = [0, 0, 0, 0];
  2866. var Track = (function () {
  2867. function Track(propName) {
  2868. this.keyframes = [];
  2869. this.maxTime = 0;
  2870. this.arrDim = 0;
  2871. this.interpolable = true;
  2872. this._needsSort = false;
  2873. this._isAllValueEqual = true;
  2874. this._lastFrame = 0;
  2875. this._lastFramePercent = 0;
  2876. this.propName = propName;
  2877. }
  2878. Track.prototype.isFinished = function () {
  2879. return this._finished;
  2880. };
  2881. Track.prototype.setFinished = function () {
  2882. this._finished = true;
  2883. if (this._additiveTrack) {
  2884. this._additiveTrack.setFinished();
  2885. }
  2886. };
  2887. Track.prototype.needsAnimate = function () {
  2888. return !this._isAllValueEqual && this.keyframes.length >= 2 && this.interpolable;
  2889. };
  2890. Track.prototype.getAdditiveTrack = function () {
  2891. return this._additiveTrack;
  2892. };
  2893. Track.prototype.addKeyframe = function (time, value) {
  2894. if (time >= this.maxTime) {
  2895. this.maxTime = time;
  2896. }
  2897. else {
  2898. this._needsSort = true;
  2899. }
  2900. var keyframes = this.keyframes;
  2901. var len = keyframes.length;
  2902. if (this.interpolable) {
  2903. if (isArrayLike(value)) {
  2904. var arrayDim = guessArrayDim(value);
  2905. if (len > 0 && this.arrDim !== arrayDim) {
  2906. this.interpolable = false;
  2907. return;
  2908. }
  2909. if (arrayDim === 1 && typeof value[0] !== 'number'
  2910. || arrayDim === 2 && typeof value[0][0] !== 'number') {
  2911. this.interpolable = false;
  2912. return;
  2913. }
  2914. if (len > 0) {
  2915. var lastFrame = keyframes[len - 1];
  2916. if (this._isAllValueEqual) {
  2917. if (arrayDim === 1) {
  2918. if (!is1DArraySame(value, lastFrame.value)) {
  2919. this._isAllValueEqual = false;
  2920. }
  2921. }
  2922. else {
  2923. this._isAllValueEqual = false;
  2924. }
  2925. }
  2926. }
  2927. this.arrDim = arrayDim;
  2928. }
  2929. else {
  2930. if (this.arrDim > 0) {
  2931. this.interpolable = false;
  2932. return;
  2933. }
  2934. if (typeof value === 'string') {
  2935. var colorArray = parse(value);
  2936. if (colorArray) {
  2937. value = colorArray;
  2938. this.isValueColor = true;
  2939. }
  2940. else {
  2941. this.interpolable = false;
  2942. }
  2943. }
  2944. else if (typeof value !== 'number') {
  2945. this.interpolable = false;
  2946. return;
  2947. }
  2948. if (this._isAllValueEqual && len > 0) {
  2949. var lastFrame = keyframes[len - 1];
  2950. if (this.isValueColor && !is1DArraySame(lastFrame.value, value)) {
  2951. this._isAllValueEqual = false;
  2952. }
  2953. else if (lastFrame.value !== value) {
  2954. this._isAllValueEqual = false;
  2955. }
  2956. }
  2957. }
  2958. }
  2959. var kf = {
  2960. time: time,
  2961. value: value,
  2962. percent: 0
  2963. };
  2964. this.keyframes.push(kf);
  2965. return kf;
  2966. };
  2967. Track.prototype.prepare = function (additiveTrack) {
  2968. var kfs = this.keyframes;
  2969. if (this._needsSort) {
  2970. kfs.sort(function (a, b) {
  2971. return a.time - b.time;
  2972. });
  2973. }
  2974. var arrDim = this.arrDim;
  2975. var kfsLen = kfs.length;
  2976. var lastKf = kfs[kfsLen - 1];
  2977. for (var i = 0; i < kfsLen; i++) {
  2978. kfs[i].percent = kfs[i].time / this.maxTime;
  2979. if (arrDim > 0 && i !== kfsLen - 1) {
  2980. fillArray(kfs[i].value, lastKf.value, arrDim);
  2981. }
  2982. }
  2983. if (additiveTrack
  2984. && this.needsAnimate()
  2985. && additiveTrack.needsAnimate()
  2986. && arrDim === additiveTrack.arrDim
  2987. && this.isValueColor === additiveTrack.isValueColor
  2988. && !additiveTrack._finished) {
  2989. this._additiveTrack = additiveTrack;
  2990. var startValue = kfs[0].value;
  2991. for (var i = 0; i < kfsLen; i++) {
  2992. if (arrDim === 0) {
  2993. if (this.isValueColor) {
  2994. kfs[i].additiveValue
  2995. = add1DArray([], kfs[i].value, startValue, -1);
  2996. }
  2997. else {
  2998. kfs[i].additiveValue = kfs[i].value - startValue;
  2999. }
  3000. }
  3001. else if (arrDim === 1) {
  3002. kfs[i].additiveValue = add1DArray([], kfs[i].value, startValue, -1);
  3003. }
  3004. else if (arrDim === 2) {
  3005. kfs[i].additiveValue = add2DArray([], kfs[i].value, startValue, -1);
  3006. }
  3007. }
  3008. }
  3009. };
  3010. Track.prototype.step = function (target, percent) {
  3011. if (this._finished) {
  3012. return;
  3013. }
  3014. if (this._additiveTrack && this._additiveTrack._finished) {
  3015. this._additiveTrack = null;
  3016. }
  3017. var isAdditive = this._additiveTrack != null;
  3018. var valueKey = isAdditive ? 'additiveValue' : 'value';
  3019. var keyframes = this.keyframes;
  3020. var kfsNum = this.keyframes.length;
  3021. var propName = this.propName;
  3022. var arrDim = this.arrDim;
  3023. var isValueColor = this.isValueColor;
  3024. var frameIdx;
  3025. if (percent < 0) {
  3026. frameIdx = 0;
  3027. }
  3028. else if (percent < this._lastFramePercent) {
  3029. var start = Math.min(this._lastFrame + 1, kfsNum - 1);
  3030. for (frameIdx = start; frameIdx >= 0; frameIdx--) {
  3031. if (keyframes[frameIdx].percent <= percent) {
  3032. break;
  3033. }
  3034. }
  3035. frameIdx = Math.min(frameIdx, kfsNum - 2);
  3036. }
  3037. else {
  3038. for (frameIdx = this._lastFrame; frameIdx < kfsNum; frameIdx++) {
  3039. if (keyframes[frameIdx].percent > percent) {
  3040. break;
  3041. }
  3042. }
  3043. frameIdx = Math.min(frameIdx - 1, kfsNum - 2);
  3044. }
  3045. var nextFrame = keyframes[frameIdx + 1];
  3046. var frame = keyframes[frameIdx];
  3047. if (!(frame && nextFrame)) {
  3048. return;
  3049. }
  3050. this._lastFrame = frameIdx;
  3051. this._lastFramePercent = percent;
  3052. var range = (nextFrame.percent - frame.percent);
  3053. if (range === 0) {
  3054. return;
  3055. }
  3056. var w = (percent - frame.percent) / range;
  3057. var targetArr = isAdditive ? this._additiveValue
  3058. : (isValueColor ? tmpRgba : target[propName]);
  3059. if ((arrDim > 0 || isValueColor) && !targetArr) {
  3060. targetArr = this._additiveValue = [];
  3061. }
  3062. if (this.useSpline) {
  3063. var p1 = keyframes[frameIdx][valueKey];
  3064. var p0 = keyframes[frameIdx === 0 ? frameIdx : frameIdx - 1][valueKey];
  3065. var p2 = keyframes[frameIdx > kfsNum - 2 ? kfsNum - 1 : frameIdx + 1][valueKey];
  3066. var p3 = keyframes[frameIdx > kfsNum - 3 ? kfsNum - 1 : frameIdx + 2][valueKey];
  3067. if (arrDim > 0) {
  3068. arrDim === 1
  3069. ? catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w)
  3070. : catmullRomInterpolate2DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3071. }
  3072. else if (isValueColor) {
  3073. catmullRomInterpolate1DArray(targetArr, p0, p1, p2, p3, w, w * w, w * w * w);
  3074. if (!isAdditive) {
  3075. target[propName] = rgba2String(targetArr);
  3076. }
  3077. }
  3078. else {
  3079. var value = void 0;
  3080. if (!this.interpolable) {
  3081. value = p2;
  3082. }
  3083. else {
  3084. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  3085. }
  3086. if (isAdditive) {
  3087. this._additiveValue = value;
  3088. }
  3089. else {
  3090. target[propName] = value;
  3091. }
  3092. }
  3093. }
  3094. else {
  3095. if (arrDim > 0) {
  3096. arrDim === 1
  3097. ? interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w)
  3098. : interpolate2DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3099. }
  3100. else if (isValueColor) {
  3101. interpolate1DArray(targetArr, frame[valueKey], nextFrame[valueKey], w);
  3102. if (!isAdditive) {
  3103. target[propName] = rgba2String(targetArr);
  3104. }
  3105. }
  3106. else {
  3107. var value = void 0;
  3108. if (!this.interpolable) {
  3109. value = step(frame[valueKey], nextFrame[valueKey], w);
  3110. }
  3111. else {
  3112. value = interpolateNumber(frame[valueKey], nextFrame[valueKey], w);
  3113. }
  3114. if (isAdditive) {
  3115. this._additiveValue = value;
  3116. }
  3117. else {
  3118. target[propName] = value;
  3119. }
  3120. }
  3121. }
  3122. if (isAdditive) {
  3123. this._addToTarget(target);
  3124. }
  3125. };
  3126. Track.prototype._addToTarget = function (target) {
  3127. var arrDim = this.arrDim;
  3128. var propName = this.propName;
  3129. var additiveValue = this._additiveValue;
  3130. if (arrDim === 0) {
  3131. if (this.isValueColor) {
  3132. parse(target[propName], tmpRgba);
  3133. add1DArray(tmpRgba, tmpRgba, additiveValue, 1);
  3134. target[propName] = rgba2String(tmpRgba);
  3135. }
  3136. else {
  3137. target[propName] = target[propName] + additiveValue;
  3138. }
  3139. }
  3140. else if (arrDim === 1) {
  3141. add1DArray(target[propName], target[propName], additiveValue, 1);
  3142. }
  3143. else if (arrDim === 2) {
  3144. add2DArray(target[propName], target[propName], additiveValue, 1);
  3145. }
  3146. };
  3147. return Track;
  3148. }());
  3149. var Animator = (function () {
  3150. function Animator(target, loop, additiveTo) {
  3151. this._tracks = {};
  3152. this._trackKeys = [];
  3153. this._delay = 0;
  3154. this._maxTime = 0;
  3155. this._paused = false;
  3156. this._started = 0;
  3157. this._clip = null;
  3158. this._target = target;
  3159. this._loop = loop;
  3160. if (loop && additiveTo) {
  3161. logError('Can\' use additive animation on looped animation.');
  3162. return;
  3163. }
  3164. this._additiveAnimators = additiveTo;
  3165. }
  3166. Animator.prototype.getTarget = function () {
  3167. return this._target;
  3168. };
  3169. Animator.prototype.changeTarget = function (target) {
  3170. this._target = target;
  3171. };
  3172. Animator.prototype.when = function (time, props) {
  3173. return this.whenWithKeys(time, props, keys(props));
  3174. };
  3175. Animator.prototype.whenWithKeys = function (time, props, propNames) {
  3176. var tracks = this._tracks;
  3177. for (var i = 0; i < propNames.length; i++) {
  3178. var propName = propNames[i];
  3179. var track = tracks[propName];
  3180. if (!track) {
  3181. track = tracks[propName] = new Track(propName);
  3182. var initialValue = void 0;
  3183. var additiveTrack = this._getAdditiveTrack(propName);
  3184. if (additiveTrack) {
  3185. var lastFinalKf = additiveTrack.keyframes[additiveTrack.keyframes.length - 1];
  3186. initialValue = lastFinalKf && lastFinalKf.value;
  3187. if (additiveTrack.isValueColor && initialValue) {
  3188. initialValue = rgba2String(initialValue);
  3189. }
  3190. }
  3191. else {
  3192. initialValue = this._target[propName];
  3193. }
  3194. if (initialValue == null) {
  3195. continue;
  3196. }
  3197. if (time !== 0) {
  3198. track.addKeyframe(0, cloneValue(initialValue));
  3199. }
  3200. this._trackKeys.push(propName);
  3201. }
  3202. track.addKeyframe(time, cloneValue(props[propName]));
  3203. }
  3204. this._maxTime = Math.max(this._maxTime, time);
  3205. return this;
  3206. };
  3207. Animator.prototype.pause = function () {
  3208. this._clip.pause();
  3209. this._paused = true;
  3210. };
  3211. Animator.prototype.resume = function () {
  3212. this._clip.resume();
  3213. this._paused = false;
  3214. };
  3215. Animator.prototype.isPaused = function () {
  3216. return !!this._paused;
  3217. };
  3218. Animator.prototype._doneCallback = function () {
  3219. this._setTracksFinished();
  3220. this._clip = null;
  3221. var doneList = this._doneList;
  3222. if (doneList) {
  3223. var len = doneList.length;
  3224. for (var i = 0; i < len; i++) {
  3225. doneList[i].call(this);
  3226. }
  3227. }
  3228. };
  3229. Animator.prototype._abortedCallback = function () {
  3230. this._setTracksFinished();
  3231. var animation = this.animation;
  3232. var abortedList = this._abortedList;
  3233. if (animation) {
  3234. animation.removeClip(this._clip);
  3235. }
  3236. this._clip = null;
  3237. if (abortedList) {
  3238. for (var i = 0; i < abortedList.length; i++) {
  3239. abortedList[i].call(this);
  3240. }
  3241. }
  3242. };
  3243. Animator.prototype._setTracksFinished = function () {
  3244. var tracks = this._tracks;
  3245. var tracksKeys = this._trackKeys;
  3246. for (var i = 0; i < tracksKeys.length; i++) {
  3247. tracks[tracksKeys[i]].setFinished();
  3248. }
  3249. };
  3250. Animator.prototype._getAdditiveTrack = function (trackName) {
  3251. var additiveTrack;
  3252. var additiveAnimators = this._additiveAnimators;
  3253. if (additiveAnimators) {
  3254. for (var i = 0; i < additiveAnimators.length; i++) {
  3255. var track = additiveAnimators[i].getTrack(trackName);
  3256. if (track) {
  3257. additiveTrack = track;
  3258. }
  3259. }
  3260. }
  3261. return additiveTrack;
  3262. };
  3263. Animator.prototype.start = function (easing, forceAnimate) {
  3264. if (this._started > 0) {
  3265. return;
  3266. }
  3267. this._started = 1;
  3268. var self = this;
  3269. var tracks = [];
  3270. for (var i = 0; i < this._trackKeys.length; i++) {
  3271. var propName = this._trackKeys[i];
  3272. var track = this._tracks[propName];
  3273. var additiveTrack = this._getAdditiveTrack(propName);
  3274. var kfs = track.keyframes;
  3275. track.prepare(additiveTrack);
  3276. if (track.needsAnimate()) {
  3277. tracks.push(track);
  3278. }
  3279. else if (!track.interpolable) {
  3280. var lastKf = kfs[kfs.length - 1];
  3281. if (lastKf) {
  3282. self._target[track.propName] = lastKf.value;
  3283. }
  3284. }
  3285. }
  3286. if (tracks.length || forceAnimate) {
  3287. var clip = new Clip({
  3288. life: this._maxTime,
  3289. loop: this._loop,
  3290. delay: this._delay,
  3291. onframe: function (percent) {
  3292. self._started = 2;
  3293. var additiveAnimators = self._additiveAnimators;
  3294. if (additiveAnimators) {
  3295. var stillHasAdditiveAnimator = false;
  3296. for (var i = 0; i < additiveAnimators.length; i++) {
  3297. if (additiveAnimators[i]._clip) {
  3298. stillHasAdditiveAnimator = true;
  3299. break;
  3300. }
  3301. }
  3302. if (!stillHasAdditiveAnimator) {
  3303. self._additiveAnimators = null;
  3304. }
  3305. }
  3306. for (var i = 0; i < tracks.length; i++) {
  3307. tracks[i].step(self._target, percent);
  3308. }
  3309. var onframeList = self._onframeList;
  3310. if (onframeList) {
  3311. for (var i = 0; i < onframeList.length; i++) {
  3312. onframeList[i](self._target, percent);
  3313. }
  3314. }
  3315. },
  3316. ondestroy: function () {
  3317. self._doneCallback();
  3318. }
  3319. });
  3320. this._clip = clip;
  3321. if (this.animation) {
  3322. this.animation.addClip(clip);
  3323. }
  3324. if (easing && easing !== 'spline') {
  3325. clip.easing = easing;
  3326. }
  3327. }
  3328. else {
  3329. this._doneCallback();
  3330. }
  3331. return this;
  3332. };
  3333. Animator.prototype.stop = function (forwardToLast) {
  3334. if (!this._clip) {
  3335. return;
  3336. }
  3337. var clip = this._clip;
  3338. if (forwardToLast) {
  3339. clip.onframe(1);
  3340. }
  3341. this._abortedCallback();
  3342. };
  3343. Animator.prototype.delay = function (time) {
  3344. this._delay = time;
  3345. return this;
  3346. };
  3347. Animator.prototype.during = function (cb) {
  3348. if (cb) {
  3349. if (!this._onframeList) {
  3350. this._onframeList = [];
  3351. }
  3352. this._onframeList.push(cb);
  3353. }
  3354. return this;
  3355. };
  3356. Animator.prototype.done = function (cb) {
  3357. if (cb) {
  3358. if (!this._doneList) {
  3359. this._doneList = [];
  3360. }
  3361. this._doneList.push(cb);
  3362. }
  3363. return this;
  3364. };
  3365. Animator.prototype.aborted = function (cb) {
  3366. if (cb) {
  3367. if (!this._abortedList) {
  3368. this._abortedList = [];
  3369. }
  3370. this._abortedList.push(cb);
  3371. }
  3372. return this;
  3373. };
  3374. Animator.prototype.getClip = function () {
  3375. return this._clip;
  3376. };
  3377. Animator.prototype.getTrack = function (propName) {
  3378. return this._tracks[propName];
  3379. };
  3380. Animator.prototype.stopTracks = function (propNames, forwardToLast) {
  3381. if (!propNames.length || !this._clip) {
  3382. return true;
  3383. }
  3384. var tracks = this._tracks;
  3385. var tracksKeys = this._trackKeys;
  3386. for (var i = 0; i < propNames.length; i++) {
  3387. var track = tracks[propNames[i]];
  3388. if (track) {
  3389. if (forwardToLast) {
  3390. track.step(this._target, 1);
  3391. }
  3392. else if (this._started === 1) {
  3393. track.step(this._target, 0);
  3394. }
  3395. track.setFinished();
  3396. }
  3397. }
  3398. var allAborted = true;
  3399. for (var i = 0; i < tracksKeys.length; i++) {
  3400. if (!tracks[tracksKeys[i]].isFinished()) {
  3401. allAborted = false;
  3402. break;
  3403. }
  3404. }
  3405. if (allAborted) {
  3406. this._abortedCallback();
  3407. }
  3408. return allAborted;
  3409. };
  3410. Animator.prototype.saveFinalToTarget = function (target, trackKeys) {
  3411. if (!target) {
  3412. return;
  3413. }
  3414. trackKeys = trackKeys || this._trackKeys;
  3415. for (var i = 0; i < trackKeys.length; i++) {
  3416. var propName = trackKeys[i];
  3417. var track = this._tracks[propName];
  3418. if (!track || track.isFinished()) {
  3419. continue;
  3420. }
  3421. var kfs = track.keyframes;
  3422. var lastKf = kfs[kfs.length - 1];
  3423. if (lastKf) {
  3424. var val = cloneValue(lastKf.value);
  3425. if (track.isValueColor) {
  3426. val = rgba2String(val);
  3427. }
  3428. target[propName] = val;
  3429. }
  3430. }
  3431. };
  3432. Animator.prototype.__changeFinalValue = function (finalProps, trackKeys) {
  3433. trackKeys = trackKeys || keys(finalProps);
  3434. for (var i = 0; i < trackKeys.length; i++) {
  3435. var propName = trackKeys[i];
  3436. var track = this._tracks[propName];
  3437. if (!track) {
  3438. continue;
  3439. }
  3440. var kfs = track.keyframes;
  3441. if (kfs.length > 1) {
  3442. var lastKf = kfs.pop();
  3443. track.addKeyframe(lastKf.time, finalProps[propName]);
  3444. track.prepare(track.getAdditiveTrack());
  3445. }
  3446. }
  3447. };
  3448. return Animator;
  3449. }());
  3450. var Point = (function () {
  3451. function Point(x, y) {
  3452. this.x = x || 0;
  3453. this.y = y || 0;
  3454. }
  3455. Point.prototype.copy = function (other) {
  3456. this.x = other.x;
  3457. this.y = other.y;
  3458. return this;
  3459. };
  3460. Point.prototype.clone = function () {
  3461. return new Point(this.x, this.y);
  3462. };
  3463. Point.prototype.set = function (x, y) {
  3464. this.x = x;
  3465. this.y = y;
  3466. return this;
  3467. };
  3468. Point.prototype.equal = function (other) {
  3469. return other.x === this.x && other.y === this.y;
  3470. };
  3471. Point.prototype.add = function (other) {
  3472. this.x += other.x;
  3473. this.y += other.y;
  3474. return this;
  3475. };
  3476. Point.prototype.scale = function (scalar) {
  3477. this.x *= scalar;
  3478. this.y *= scalar;
  3479. };
  3480. Point.prototype.scaleAndAdd = function (other, scalar) {
  3481. this.x += other.x * scalar;
  3482. this.y += other.y * scalar;
  3483. };
  3484. Point.prototype.sub = function (other) {
  3485. this.x -= other.x;
  3486. this.y -= other.y;
  3487. return this;
  3488. };
  3489. Point.prototype.dot = function (other) {
  3490. return this.x * other.x + this.y * other.y;
  3491. };
  3492. Point.prototype.len = function () {
  3493. return Math.sqrt(this.x * this.x + this.y * this.y);
  3494. };
  3495. Point.prototype.lenSquare = function () {
  3496. return this.x * this.x + this.y * this.y;
  3497. };
  3498. Point.prototype.normalize = function () {
  3499. var len = this.len();
  3500. this.x /= len;
  3501. this.y /= len;
  3502. return this;
  3503. };
  3504. Point.prototype.distance = function (other) {
  3505. var dx = this.x - other.x;
  3506. var dy = this.y - other.y;
  3507. return Math.sqrt(dx * dx + dy * dy);
  3508. };
  3509. Point.prototype.distanceSquare = function (other) {
  3510. var dx = this.x - other.x;
  3511. var dy = this.y - other.y;
  3512. return dx * dx + dy * dy;
  3513. };
  3514. Point.prototype.negate = function () {
  3515. this.x = -this.x;
  3516. this.y = -this.y;
  3517. return this;
  3518. };
  3519. Point.prototype.transform = function (m) {
  3520. if (!m) {
  3521. return;
  3522. }
  3523. var x = this.x;
  3524. var y = this.y;
  3525. this.x = m[0] * x + m[2] * y + m[4];
  3526. this.y = m[1] * x + m[3] * y + m[5];
  3527. return this;
  3528. };
  3529. Point.prototype.toArray = function (out) {
  3530. out[0] = this.x;
  3531. out[1] = this.y;
  3532. return out;
  3533. };
  3534. Point.prototype.fromArray = function (input) {
  3535. this.x = input[0];
  3536. this.y = input[1];
  3537. };
  3538. Point.set = function (p, x, y) {
  3539. p.x = x;
  3540. p.y = y;
  3541. };
  3542. Point.copy = function (p, p2) {
  3543. p.x = p2.x;
  3544. p.y = p2.y;
  3545. };
  3546. Point.len = function (p) {
  3547. return Math.sqrt(p.x * p.x + p.y * p.y);
  3548. };
  3549. Point.lenSquare = function (p) {
  3550. return p.x * p.x + p.y * p.y;
  3551. };
  3552. Point.dot = function (p0, p1) {
  3553. return p0.x * p1.x + p0.y * p1.y;
  3554. };
  3555. Point.add = function (out, p0, p1) {
  3556. out.x = p0.x + p1.x;
  3557. out.y = p0.y + p1.y;
  3558. };
  3559. Point.sub = function (out, p0, p1) {
  3560. out.x = p0.x - p1.x;
  3561. out.y = p0.y - p1.y;
  3562. };
  3563. Point.scale = function (out, p0, scalar) {
  3564. out.x = p0.x * scalar;
  3565. out.y = p0.y * scalar;
  3566. };
  3567. Point.scaleAndAdd = function (out, p0, p1, scalar) {
  3568. out.x = p0.x + p1.x * scalar;
  3569. out.y = p0.y + p1.y * scalar;
  3570. };
  3571. Point.lerp = function (out, p0, p1, t) {
  3572. var onet = 1 - t;
  3573. out.x = onet * p0.x + t * p1.x;
  3574. out.y = onet * p0.y + t * p1.y;
  3575. };
  3576. return Point;
  3577. }());
  3578. var mathMin = Math.min;
  3579. var mathMax = Math.max;
  3580. var lt = new Point();
  3581. var rb = new Point();
  3582. var lb = new Point();
  3583. var rt = new Point();
  3584. var minTv = new Point();
  3585. var maxTv = new Point();
  3586. var BoundingRect = (function () {
  3587. function BoundingRect(x, y, width, height) {
  3588. if (width < 0 && isFinite(width)) {
  3589. x = x + width;
  3590. width = -width;
  3591. }
  3592. if (height < 0 && isFinite(height)) {
  3593. y = y + height;
  3594. height = -height;
  3595. }
  3596. this.x = x;
  3597. this.y = y;
  3598. this.width = width;
  3599. this.height = height;
  3600. }
  3601. BoundingRect.prototype.union = function (other) {
  3602. var x = mathMin(other.x, this.x);
  3603. var y = mathMin(other.y, this.y);
  3604. if (isFinite(this.x) && isFinite(this.width)) {
  3605. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  3606. }
  3607. else {
  3608. this.width = other.width;
  3609. }
  3610. if (isFinite(this.y) && isFinite(this.height)) {
  3611. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  3612. }
  3613. else {
  3614. this.height = other.height;
  3615. }
  3616. this.x = x;
  3617. this.y = y;
  3618. };
  3619. BoundingRect.prototype.applyTransform = function (m) {
  3620. BoundingRect.applyTransform(this, this, m);
  3621. };
  3622. BoundingRect.prototype.calculateTransform = function (b) {
  3623. var a = this;
  3624. var sx = b.width / a.width;
  3625. var sy = b.height / a.height;
  3626. var m = create$1();
  3627. translate(m, m, [-a.x, -a.y]);
  3628. scale$1(m, m, [sx, sy]);
  3629. translate(m, m, [b.x, b.y]);
  3630. return m;
  3631. };
  3632. BoundingRect.prototype.intersect = function (b, mtv) {
  3633. if (!b) {
  3634. return false;
  3635. }
  3636. if (!(b instanceof BoundingRect)) {
  3637. b = BoundingRect.create(b);
  3638. }
  3639. var a = this;
  3640. var ax0 = a.x;
  3641. var ax1 = a.x + a.width;
  3642. var ay0 = a.y;
  3643. var ay1 = a.y + a.height;
  3644. var bx0 = b.x;
  3645. var bx1 = b.x + b.width;
  3646. var by0 = b.y;
  3647. var by1 = b.y + b.height;
  3648. var overlap = !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  3649. if (mtv) {
  3650. var dMin = Infinity;
  3651. var dMax = 0;
  3652. var d0 = Math.abs(ax1 - bx0);
  3653. var d1 = Math.abs(bx1 - ax0);
  3654. var d2 = Math.abs(ay1 - by0);
  3655. var d3 = Math.abs(by1 - ay0);
  3656. var dx = Math.min(d0, d1);
  3657. var dy = Math.min(d2, d3);
  3658. if (ax1 < bx0 || bx1 < ax0) {
  3659. if (dx > dMax) {
  3660. dMax = dx;
  3661. if (d0 < d1) {
  3662. Point.set(maxTv, -d0, 0);
  3663. }
  3664. else {
  3665. Point.set(maxTv, d1, 0);
  3666. }
  3667. }
  3668. }
  3669. else {
  3670. if (dx < dMin) {
  3671. dMin = dx;
  3672. if (d0 < d1) {
  3673. Point.set(minTv, d0, 0);
  3674. }
  3675. else {
  3676. Point.set(minTv, -d1, 0);
  3677. }
  3678. }
  3679. }
  3680. if (ay1 < by0 || by1 < ay0) {
  3681. if (dy > dMax) {
  3682. dMax = dy;
  3683. if (d2 < d3) {
  3684. Point.set(maxTv, 0, -d2);
  3685. }
  3686. else {
  3687. Point.set(maxTv, 0, d3);
  3688. }
  3689. }
  3690. }
  3691. else {
  3692. if (dx < dMin) {
  3693. dMin = dx;
  3694. if (d2 < d3) {
  3695. Point.set(minTv, 0, d2);
  3696. }
  3697. else {
  3698. Point.set(minTv, 0, -d3);
  3699. }
  3700. }
  3701. }
  3702. }
  3703. if (mtv) {
  3704. Point.copy(mtv, overlap ? minTv : maxTv);
  3705. }
  3706. return overlap;
  3707. };
  3708. BoundingRect.prototype.contain = function (x, y) {
  3709. var rect = this;
  3710. return x >= rect.x
  3711. && x <= (rect.x + rect.width)
  3712. && y >= rect.y
  3713. && y <= (rect.y + rect.height);
  3714. };
  3715. BoundingRect.prototype.clone = function () {
  3716. return new BoundingRect(this.x, this.y, this.width, this.height);
  3717. };
  3718. BoundingRect.prototype.copy = function (other) {
  3719. BoundingRect.copy(this, other);
  3720. };
  3721. BoundingRect.prototype.plain = function () {
  3722. return {
  3723. x: this.x,
  3724. y: this.y,
  3725. width: this.width,
  3726. height: this.height
  3727. };
  3728. };
  3729. BoundingRect.prototype.isFinite = function () {
  3730. return isFinite(this.x)
  3731. && isFinite(this.y)
  3732. && isFinite(this.width)
  3733. && isFinite(this.height);
  3734. };
  3735. BoundingRect.prototype.isZero = function () {
  3736. return this.width === 0 || this.height === 0;
  3737. };
  3738. BoundingRect.create = function (rect) {
  3739. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  3740. };
  3741. BoundingRect.copy = function (target, source) {
  3742. target.x = source.x;
  3743. target.y = source.y;
  3744. target.width = source.width;
  3745. target.height = source.height;
  3746. };
  3747. BoundingRect.applyTransform = function (target, source, m) {
  3748. if (!m) {
  3749. if (target !== source) {
  3750. BoundingRect.copy(target, source);
  3751. }
  3752. return;
  3753. }
  3754. if (m[1] < 1e-5 && m[1] > -1e-5 && m[2] < 1e-5 && m[2] > -1e-5) {
  3755. var sx = m[0];
  3756. var sy = m[3];
  3757. var tx = m[4];
  3758. var ty = m[5];
  3759. target.x = source.x * sx + tx;
  3760. target.y = source.y * sy + ty;
  3761. target.width = source.width * sx;
  3762. target.height = source.height * sy;
  3763. if (target.width < 0) {
  3764. target.x += target.width;
  3765. target.width = -target.width;
  3766. }
  3767. if (target.height < 0) {
  3768. target.y += target.height;
  3769. target.height = -target.height;
  3770. }
  3771. return;
  3772. }
  3773. lt.x = lb.x = source.x;
  3774. lt.y = rt.y = source.y;
  3775. rb.x = rt.x = source.x + source.width;
  3776. rb.y = lb.y = source.y + source.height;
  3777. lt.transform(m);
  3778. rt.transform(m);
  3779. rb.transform(m);
  3780. lb.transform(m);
  3781. target.x = mathMin(lt.x, rb.x, lb.x, rt.x);
  3782. target.y = mathMin(lt.y, rb.y, lb.y, rt.y);
  3783. var maxX = mathMax(lt.x, rb.x, lb.x, rt.x);
  3784. var maxY = mathMax(lt.y, rb.y, lb.y, rt.y);
  3785. target.width = maxX - target.x;
  3786. target.height = maxY - target.y;
  3787. };
  3788. return BoundingRect;
  3789. }());
  3790. var textWidthCache = {};
  3791. var DEFAULT_FONT = '12px sans-serif';
  3792. var _ctx;
  3793. var _cachedFont;
  3794. function defaultMeasureText(text, font) {
  3795. if (!_ctx) {
  3796. _ctx = createCanvas().getContext('2d');
  3797. }
  3798. if (_cachedFont !== font) {
  3799. _cachedFont = _ctx.font = font || DEFAULT_FONT;
  3800. }
  3801. return _ctx.measureText(text);
  3802. }
  3803. var methods$1 = {
  3804. measureText: defaultMeasureText
  3805. };
  3806. function getWidth(text, font) {
  3807. font = font || DEFAULT_FONT;
  3808. var cacheOfFont = textWidthCache[font];
  3809. if (!cacheOfFont) {
  3810. cacheOfFont = textWidthCache[font] = new LRU(500);
  3811. }
  3812. var width = cacheOfFont.get(text);
  3813. if (width == null) {
  3814. width = methods$1.measureText(text, font).width;
  3815. cacheOfFont.put(text, width);
  3816. }
  3817. return width;
  3818. }
  3819. function innerGetBoundingRect(text, font, textAlign, textBaseline) {
  3820. var width = getWidth(text, font);
  3821. var height = getLineHeight(font);
  3822. var x = adjustTextX(0, width, textAlign);
  3823. var y = adjustTextY(0, height, textBaseline);
  3824. var rect = new BoundingRect(x, y, width, height);
  3825. return rect;
  3826. }
  3827. function getBoundingRect(text, font, textAlign, textBaseline) {
  3828. var textLines = ((text || '') + '').split('\n');
  3829. var len = textLines.length;
  3830. if (len === 1) {
  3831. return innerGetBoundingRect(textLines[0], font, textAlign, textBaseline);
  3832. }
  3833. else {
  3834. var uniondRect = new BoundingRect(0, 0, 0, 0);
  3835. for (var i = 0; i < textLines.length; i++) {
  3836. var rect = innerGetBoundingRect(textLines[i], font, textAlign, textBaseline);
  3837. i === 0 ? uniondRect.copy(rect) : uniondRect.union(rect);
  3838. }
  3839. return uniondRect;
  3840. }
  3841. }
  3842. function adjustTextX(x, width, textAlign) {
  3843. if (textAlign === 'right') {
  3844. x -= width;
  3845. }
  3846. else if (textAlign === 'center') {
  3847. x -= width / 2;
  3848. }
  3849. return x;
  3850. }
  3851. function adjustTextY(y, height, verticalAlign) {
  3852. if (verticalAlign === 'middle') {
  3853. y -= height / 2;
  3854. }
  3855. else if (verticalAlign === 'bottom') {
  3856. y -= height;
  3857. }
  3858. return y;
  3859. }
  3860. function getLineHeight(font) {
  3861. return getWidth('国', font);
  3862. }
  3863. function parsePercent(value, maxValue) {
  3864. if (typeof value === 'string') {
  3865. if (value.lastIndexOf('%') >= 0) {
  3866. return parseFloat(value) / 100 * maxValue;
  3867. }
  3868. return parseFloat(value);
  3869. }
  3870. return value;
  3871. }
  3872. function calculateTextPosition(out, opts, rect) {
  3873. var textPosition = opts.position || 'inside';
  3874. var distance = opts.distance != null ? opts.distance : 5;
  3875. var height = rect.height;
  3876. var width = rect.width;
  3877. var halfHeight = height / 2;
  3878. var x = rect.x;
  3879. var y = rect.y;
  3880. var textAlign = 'left';
  3881. var textVerticalAlign = 'top';
  3882. if (textPosition instanceof Array) {
  3883. x += parsePercent(textPosition[0], rect.width);
  3884. y += parsePercent(textPosition[1], rect.height);
  3885. textAlign = null;
  3886. textVerticalAlign = null;
  3887. }
  3888. else {
  3889. switch (textPosition) {
  3890. case 'left':
  3891. x -= distance;
  3892. y += halfHeight;
  3893. textAlign = 'right';
  3894. textVerticalAlign = 'middle';
  3895. break;
  3896. case 'right':
  3897. x += distance + width;
  3898. y += halfHeight;
  3899. textVerticalAlign = 'middle';
  3900. break;
  3901. case 'top':
  3902. x += width / 2;
  3903. y -= distance;
  3904. textAlign = 'center';
  3905. textVerticalAlign = 'bottom';
  3906. break;
  3907. case 'bottom':
  3908. x += width / 2;
  3909. y += height + distance;
  3910. textAlign = 'center';
  3911. break;
  3912. case 'inside':
  3913. x += width / 2;
  3914. y += halfHeight;
  3915. textAlign = 'center';
  3916. textVerticalAlign = 'middle';
  3917. break;
  3918. case 'insideLeft':
  3919. x += distance;
  3920. y += halfHeight;
  3921. textVerticalAlign = 'middle';
  3922. break;
  3923. case 'insideRight':
  3924. x += width - distance;
  3925. y += halfHeight;
  3926. textAlign = 'right';
  3927. textVerticalAlign = 'middle';
  3928. break;
  3929. case 'insideTop':
  3930. x += width / 2;
  3931. y += distance;
  3932. textAlign = 'center';
  3933. break;
  3934. case 'insideBottom':
  3935. x += width / 2;
  3936. y += height - distance;
  3937. textAlign = 'center';
  3938. textVerticalAlign = 'bottom';
  3939. break;
  3940. case 'insideTopLeft':
  3941. x += distance;
  3942. y += distance;
  3943. break;
  3944. case 'insideTopRight':
  3945. x += width - distance;
  3946. y += distance;
  3947. textAlign = 'right';
  3948. break;
  3949. case 'insideBottomLeft':
  3950. x += distance;
  3951. y += height - distance;
  3952. textVerticalAlign = 'bottom';
  3953. break;
  3954. case 'insideBottomRight':
  3955. x += width - distance;
  3956. y += height - distance;
  3957. textAlign = 'right';
  3958. textVerticalAlign = 'bottom';
  3959. break;
  3960. }
  3961. }
  3962. out = out || {};
  3963. out.x = x;
  3964. out.y = y;
  3965. out.align = textAlign;
  3966. out.verticalAlign = textVerticalAlign;
  3967. return out;
  3968. }
  3969. var dpr = 1;
  3970. if (typeof window !== 'undefined') {
  3971. dpr = Math.max(window.devicePixelRatio
  3972. || (window.screen && window.screen.deviceXDPI / window.screen.logicalXDPI)
  3973. || 1, 1);
  3974. }
  3975. var devicePixelRatio = dpr;
  3976. var DARK_MODE_THRESHOLD = 0.4;
  3977. var DARK_LABEL_COLOR = '#333';
  3978. var LIGHT_LABEL_COLOR = '#ccc';
  3979. var LIGHTER_LABEL_COLOR = '#eee';
  3980. var PRESERVED_NORMAL_STATE = '__zr_normal__';
  3981. var PRIMARY_STATES_KEYS = ['x', 'y', 'scaleX', 'scaleY', 'originX', 'originY', 'rotation', 'ignore'];
  3982. var DEFAULT_ANIMATABLE_MAP = {
  3983. x: true,
  3984. y: true,
  3985. scaleX: true,
  3986. scaleY: true,
  3987. originX: true,
  3988. originY: true,
  3989. rotation: true,
  3990. ignore: false
  3991. };
  3992. var tmpTextPosCalcRes = {};
  3993. var tmpBoundingRect = new BoundingRect(0, 0, 0, 0);
  3994. var Element = (function () {
  3995. function Element(props) {
  3996. this.id = guid();
  3997. this.animators = [];
  3998. this.currentStates = [];
  3999. this.states = {};
  4000. this._init(props);
  4001. }
  4002. Element.prototype._init = function (props) {
  4003. this.attr(props);
  4004. };
  4005. Element.prototype.drift = function (dx, dy, e) {
  4006. switch (this.draggable) {
  4007. case 'horizontal':
  4008. dy = 0;
  4009. break;
  4010. case 'vertical':
  4011. dx = 0;
  4012. break;
  4013. }
  4014. var m = this.transform;
  4015. if (!m) {
  4016. m = this.transform = [1, 0, 0, 1, 0, 0];
  4017. }
  4018. m[4] += dx;
  4019. m[5] += dy;
  4020. this.decomposeTransform();
  4021. this.markRedraw();
  4022. };
  4023. Element.prototype.beforeUpdate = function () { };
  4024. Element.prototype.afterUpdate = function () { };
  4025. Element.prototype.update = function () {
  4026. this.updateTransform();
  4027. if (this.__dirty) {
  4028. this.updateInnerText();
  4029. }
  4030. };
  4031. Element.prototype.updateInnerText = function (forceUpdate) {
  4032. var textEl = this._textContent;
  4033. if (textEl && (!textEl.ignore || forceUpdate)) {
  4034. if (!this.textConfig) {
  4035. this.textConfig = {};
  4036. }
  4037. var textConfig = this.textConfig;
  4038. var isLocal = textConfig.local;
  4039. var attachedTransform = textEl.attachedTransform;
  4040. var textAlign = void 0;
  4041. var textVerticalAlign = void 0;
  4042. var textStyleChanged = false;
  4043. if (isLocal) {
  4044. attachedTransform.parent = this;
  4045. }
  4046. else {
  4047. attachedTransform.parent = null;
  4048. }
  4049. var innerOrigin = false;
  4050. attachedTransform.x = textEl.x;
  4051. attachedTransform.y = textEl.y;
  4052. attachedTransform.originX = textEl.originX;
  4053. attachedTransform.originY = textEl.originY;
  4054. attachedTransform.rotation = textEl.rotation;
  4055. attachedTransform.scaleX = textEl.scaleX;
  4056. attachedTransform.scaleY = textEl.scaleY;
  4057. if (textConfig.position != null) {
  4058. var layoutRect = tmpBoundingRect;
  4059. if (textConfig.layoutRect) {
  4060. layoutRect.copy(textConfig.layoutRect);
  4061. }
  4062. else {
  4063. layoutRect.copy(this.getBoundingRect());
  4064. }
  4065. if (!isLocal) {
  4066. layoutRect.applyTransform(this.transform);
  4067. }
  4068. if (this.calculateTextPosition) {
  4069. this.calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4070. }
  4071. else {
  4072. calculateTextPosition(tmpTextPosCalcRes, textConfig, layoutRect);
  4073. }
  4074. attachedTransform.x = tmpTextPosCalcRes.x;
  4075. attachedTransform.y = tmpTextPosCalcRes.y;
  4076. textAlign = tmpTextPosCalcRes.align;
  4077. textVerticalAlign = tmpTextPosCalcRes.verticalAlign;
  4078. var textOrigin = textConfig.origin;
  4079. if (textOrigin && textConfig.rotation != null) {
  4080. var relOriginX = void 0;
  4081. var relOriginY = void 0;
  4082. if (textOrigin === 'center') {
  4083. relOriginX = layoutRect.width * 0.5;
  4084. relOriginY = layoutRect.height * 0.5;
  4085. }
  4086. else {
  4087. relOriginX = parsePercent(textOrigin[0], layoutRect.width);
  4088. relOriginY = parsePercent(textOrigin[1], layoutRect.height);
  4089. }
  4090. innerOrigin = true;
  4091. attachedTransform.originX = -attachedTransform.x + relOriginX + (isLocal ? 0 : layoutRect.x);
  4092. attachedTransform.originY = -attachedTransform.y + relOriginY + (isLocal ? 0 : layoutRect.y);
  4093. }
  4094. }
  4095. if (textConfig.rotation != null) {
  4096. attachedTransform.rotation = textConfig.rotation;
  4097. }
  4098. var textOffset = textConfig.offset;
  4099. if (textOffset) {
  4100. attachedTransform.x += textOffset[0];
  4101. attachedTransform.y += textOffset[1];
  4102. if (!innerOrigin) {
  4103. attachedTransform.originX = -textOffset[0];
  4104. attachedTransform.originY = -textOffset[1];
  4105. }
  4106. }
  4107. var isInside = textConfig.inside == null
  4108. ? (typeof textConfig.position === 'string' && textConfig.position.indexOf('inside') >= 0)
  4109. : textConfig.inside;
  4110. var innerTextDefaultStyle = this._innerTextDefaultStyle || (this._innerTextDefaultStyle = {});
  4111. var textFill = void 0;
  4112. var textStroke = void 0;
  4113. var autoStroke = void 0;
  4114. if (isInside && this.canBeInsideText()) {
  4115. textFill = textConfig.insideFill;
  4116. textStroke = textConfig.insideStroke;
  4117. if (textFill == null || textFill === 'auto') {
  4118. textFill = this.getInsideTextFill();
  4119. }
  4120. if (textStroke == null || textStroke === 'auto') {
  4121. textStroke = this.getInsideTextStroke(textFill);
  4122. autoStroke = true;
  4123. }
  4124. }
  4125. else {
  4126. textFill = textConfig.outsideFill;
  4127. textStroke = textConfig.outsideStroke;
  4128. if (textFill == null || textFill === 'auto') {
  4129. textFill = this.getOutsideFill();
  4130. }
  4131. if (textStroke == null || textStroke === 'auto') {
  4132. textStroke = this.getOutsideStroke(textFill);
  4133. autoStroke = true;
  4134. }
  4135. }
  4136. textFill = textFill || '#000';
  4137. if (textFill !== innerTextDefaultStyle.fill
  4138. || textStroke !== innerTextDefaultStyle.stroke
  4139. || autoStroke !== innerTextDefaultStyle.autoStroke
  4140. || textAlign !== innerTextDefaultStyle.align
  4141. || textVerticalAlign !== innerTextDefaultStyle.verticalAlign) {
  4142. textStyleChanged = true;
  4143. innerTextDefaultStyle.fill = textFill;
  4144. innerTextDefaultStyle.stroke = textStroke;
  4145. innerTextDefaultStyle.autoStroke = autoStroke;
  4146. innerTextDefaultStyle.align = textAlign;
  4147. innerTextDefaultStyle.verticalAlign = textVerticalAlign;
  4148. textEl.setDefaultTextStyle(innerTextDefaultStyle);
  4149. }
  4150. if (textStyleChanged) {
  4151. textEl.dirtyStyle();
  4152. }
  4153. textEl.markRedraw();
  4154. }
  4155. };
  4156. Element.prototype.canBeInsideText = function () {
  4157. return true;
  4158. };
  4159. Element.prototype.getInsideTextFill = function () {
  4160. return '#fff';
  4161. };
  4162. Element.prototype.getInsideTextStroke = function (textFill) {
  4163. return '#000';
  4164. };
  4165. Element.prototype.getOutsideFill = function () {
  4166. return this.__zr && this.__zr.isDarkMode() ? LIGHT_LABEL_COLOR : DARK_LABEL_COLOR;
  4167. };
  4168. Element.prototype.getOutsideStroke = function (textFill) {
  4169. var backgroundColor = this.__zr && this.__zr.getBackgroundColor();
  4170. var colorArr = typeof backgroundColor === 'string' && parse(backgroundColor);
  4171. if (!colorArr) {
  4172. colorArr = [255, 255, 255, 1];
  4173. }
  4174. var alpha = colorArr[3];
  4175. var isDark = this.__zr.isDarkMode();
  4176. for (var i = 0; i < 3; i++) {
  4177. colorArr[i] = colorArr[i] * alpha + (isDark ? 0 : 255) * (1 - alpha);
  4178. }
  4179. colorArr[3] = 1;
  4180. return stringify(colorArr, 'rgba');
  4181. };
  4182. Element.prototype.traverse = function (cb, context) { };
  4183. Element.prototype.attrKV = function (key, value) {
  4184. if (key === 'textConfig') {
  4185. this.setTextConfig(value);
  4186. }
  4187. else if (key === 'textContent') {
  4188. this.setTextContent(value);
  4189. }
  4190. else if (key === 'clipPath') {
  4191. this.setClipPath(value);
  4192. }
  4193. else if (key === 'extra') {
  4194. this.extra = this.extra || {};
  4195. extend(this.extra, value);
  4196. }
  4197. else {
  4198. this[key] = value;
  4199. }
  4200. };
  4201. Element.prototype.hide = function () {
  4202. this.ignore = true;
  4203. this.markRedraw();
  4204. };
  4205. Element.prototype.show = function () {
  4206. this.ignore = false;
  4207. this.markRedraw();
  4208. };
  4209. Element.prototype.attr = function (keyOrObj, value) {
  4210. if (typeof keyOrObj === 'string') {
  4211. this.attrKV(keyOrObj, value);
  4212. }
  4213. else if (isObject(keyOrObj)) {
  4214. var obj = keyOrObj;
  4215. var keysArr = keys(obj);
  4216. for (var i = 0; i < keysArr.length; i++) {
  4217. var key = keysArr[i];
  4218. this.attrKV(key, keyOrObj[key]);
  4219. }
  4220. }
  4221. this.markRedraw();
  4222. return this;
  4223. };
  4224. Element.prototype.saveCurrentToNormalState = function (toState) {
  4225. this._innerSaveToNormal(toState);
  4226. var normalState = this._normalState;
  4227. for (var i = 0; i < this.animators.length; i++) {
  4228. var animator = this.animators[i];
  4229. var fromStateTransition = animator.__fromStateTransition;
  4230. if (fromStateTransition && fromStateTransition !== PRESERVED_NORMAL_STATE) {
  4231. continue;
  4232. }
  4233. var targetName = animator.targetName;
  4234. var target = targetName
  4235. ? normalState[targetName] : normalState;
  4236. animator.saveFinalToTarget(target);
  4237. }
  4238. };
  4239. Element.prototype._innerSaveToNormal = function (toState) {
  4240. var normalState = this._normalState;
  4241. if (!normalState) {
  4242. normalState = this._normalState = {};
  4243. }
  4244. if (toState.textConfig && !normalState.textConfig) {
  4245. normalState.textConfig = this.textConfig;
  4246. }
  4247. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS);
  4248. };
  4249. Element.prototype._savePrimaryToNormal = function (toState, normalState, primaryKeys) {
  4250. for (var i = 0; i < primaryKeys.length; i++) {
  4251. var key = primaryKeys[i];
  4252. if (toState[key] != null && !(key in normalState)) {
  4253. normalState[key] = this[key];
  4254. }
  4255. }
  4256. };
  4257. Element.prototype.hasState = function () {
  4258. return this.currentStates.length > 0;
  4259. };
  4260. Element.prototype.getState = function (name) {
  4261. return this.states[name];
  4262. };
  4263. Element.prototype.ensureState = function (name) {
  4264. var states = this.states;
  4265. if (!states[name]) {
  4266. states[name] = {};
  4267. }
  4268. return states[name];
  4269. };
  4270. Element.prototype.clearStates = function (noAnimation) {
  4271. this.useState(PRESERVED_NORMAL_STATE, false, noAnimation);
  4272. };
  4273. Element.prototype.useState = function (stateName, keepCurrentStates, noAnimation) {
  4274. var toNormalState = stateName === PRESERVED_NORMAL_STATE;
  4275. var hasStates = this.hasState();
  4276. if (!hasStates && toNormalState) {
  4277. return;
  4278. }
  4279. var currentStates = this.currentStates;
  4280. var animationCfg = this.stateTransition;
  4281. if (indexOf(currentStates, stateName) >= 0 && (keepCurrentStates || currentStates.length === 1)) {
  4282. return;
  4283. }
  4284. var state;
  4285. if (this.stateProxy && !toNormalState) {
  4286. state = this.stateProxy(stateName);
  4287. }
  4288. if (!state) {
  4289. state = (this.states && this.states[stateName]);
  4290. }
  4291. if (!state && !toNormalState) {
  4292. logError("State " + stateName + " not exists.");
  4293. return;
  4294. }
  4295. if (!toNormalState) {
  4296. this.saveCurrentToNormalState(state);
  4297. }
  4298. var useHoverLayer = !!(state && state.hoverLayer);
  4299. if (useHoverLayer) {
  4300. this._toggleHoverLayerFlag(true);
  4301. }
  4302. this._applyStateObj(stateName, state, this._normalState, keepCurrentStates, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4303. if (this._textContent) {
  4304. this._textContent.useState(stateName, keepCurrentStates);
  4305. }
  4306. if (this._textGuide) {
  4307. this._textGuide.useState(stateName, keepCurrentStates);
  4308. }
  4309. if (toNormalState) {
  4310. this.currentStates = [];
  4311. this._normalState = {};
  4312. }
  4313. else {
  4314. if (!keepCurrentStates) {
  4315. this.currentStates = [stateName];
  4316. }
  4317. else {
  4318. this.currentStates.push(stateName);
  4319. }
  4320. }
  4321. this._updateAnimationTargets();
  4322. this.markRedraw();
  4323. if (!useHoverLayer && this.__inHover) {
  4324. this._toggleHoverLayerFlag(false);
  4325. this.__dirty &= ~Element.REDARAW_BIT;
  4326. }
  4327. return state;
  4328. };
  4329. Element.prototype.useStates = function (states, noAnimation) {
  4330. if (!states.length) {
  4331. this.clearStates();
  4332. }
  4333. else {
  4334. var stateObjects = [];
  4335. var currentStates = this.currentStates;
  4336. var len = states.length;
  4337. var notChange = len === currentStates.length;
  4338. if (notChange) {
  4339. for (var i = 0; i < len; i++) {
  4340. if (states[i] !== currentStates[i]) {
  4341. notChange = false;
  4342. break;
  4343. }
  4344. }
  4345. }
  4346. if (notChange) {
  4347. return;
  4348. }
  4349. for (var i = 0; i < len; i++) {
  4350. var stateName = states[i];
  4351. var stateObj = void 0;
  4352. if (this.stateProxy) {
  4353. stateObj = this.stateProxy(stateName, states);
  4354. }
  4355. if (!stateObj) {
  4356. stateObj = this.states[stateName];
  4357. }
  4358. if (stateObj) {
  4359. stateObjects.push(stateObj);
  4360. }
  4361. }
  4362. var useHoverLayer = !!(stateObjects[len - 1] && stateObjects[len - 1].hoverLayer);
  4363. if (useHoverLayer) {
  4364. this._toggleHoverLayerFlag(true);
  4365. }
  4366. var mergedState = this._mergeStates(stateObjects);
  4367. var animationCfg = this.stateTransition;
  4368. this.saveCurrentToNormalState(mergedState);
  4369. this._applyStateObj(states.join(','), mergedState, this._normalState, false, !noAnimation && !this.__inHover && animationCfg && animationCfg.duration > 0, animationCfg);
  4370. if (this._textContent) {
  4371. this._textContent.useStates(states);
  4372. }
  4373. if (this._textGuide) {
  4374. this._textGuide.useStates(states);
  4375. }
  4376. this._updateAnimationTargets();
  4377. this.currentStates = states.slice();
  4378. this.markRedraw();
  4379. if (!useHoverLayer && this.__inHover) {
  4380. this._toggleHoverLayerFlag(false);
  4381. this.__dirty &= ~Element.REDARAW_BIT;
  4382. }
  4383. }
  4384. };
  4385. Element.prototype._updateAnimationTargets = function () {
  4386. for (var i = 0; i < this.animators.length; i++) {
  4387. var animator = this.animators[i];
  4388. if (animator.targetName) {
  4389. animator.changeTarget(this[animator.targetName]);
  4390. }
  4391. }
  4392. };
  4393. Element.prototype.removeState = function (state) {
  4394. var idx = indexOf(this.currentStates, state);
  4395. if (idx >= 0) {
  4396. var currentStates = this.currentStates.slice();
  4397. currentStates.splice(idx, 1);
  4398. this.useStates(currentStates);
  4399. }
  4400. };
  4401. Element.prototype.replaceState = function (oldState, newState, forceAdd) {
  4402. var currentStates = this.currentStates.slice();
  4403. var idx = indexOf(currentStates, oldState);
  4404. var newStateExists = indexOf(currentStates, newState) >= 0;
  4405. if (idx >= 0) {
  4406. if (!newStateExists) {
  4407. currentStates[idx] = newState;
  4408. }
  4409. else {
  4410. currentStates.splice(idx, 1);
  4411. }
  4412. }
  4413. else if (forceAdd && !newStateExists) {
  4414. currentStates.push(newState);
  4415. }
  4416. this.useStates(currentStates);
  4417. };
  4418. Element.prototype.toggleState = function (state, enable) {
  4419. if (enable) {
  4420. this.useState(state, true);
  4421. }
  4422. else {
  4423. this.removeState(state);
  4424. }
  4425. };
  4426. Element.prototype._mergeStates = function (states) {
  4427. var mergedState = {};
  4428. var mergedTextConfig;
  4429. for (var i = 0; i < states.length; i++) {
  4430. var state = states[i];
  4431. extend(mergedState, state);
  4432. if (state.textConfig) {
  4433. mergedTextConfig = mergedTextConfig || {};
  4434. extend(mergedTextConfig, state.textConfig);
  4435. }
  4436. }
  4437. if (mergedTextConfig) {
  4438. mergedState.textConfig = mergedTextConfig;
  4439. }
  4440. return mergedState;
  4441. };
  4442. Element.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  4443. var needsRestoreToNormal = !(state && keepCurrentStates);
  4444. if (state && state.textConfig) {
  4445. this.textConfig = extend({}, keepCurrentStates ? this.textConfig : normalState.textConfig);
  4446. extend(this.textConfig, state.textConfig);
  4447. }
  4448. else if (needsRestoreToNormal) {
  4449. if (normalState.textConfig) {
  4450. this.textConfig = normalState.textConfig;
  4451. }
  4452. }
  4453. var transitionTarget = {};
  4454. var hasTransition = false;
  4455. for (var i = 0; i < PRIMARY_STATES_KEYS.length; i++) {
  4456. var key = PRIMARY_STATES_KEYS[i];
  4457. var propNeedsTransition = transition && DEFAULT_ANIMATABLE_MAP[key];
  4458. if (state && state[key] != null) {
  4459. if (propNeedsTransition) {
  4460. hasTransition = true;
  4461. transitionTarget[key] = state[key];
  4462. }
  4463. else {
  4464. this[key] = state[key];
  4465. }
  4466. }
  4467. else if (needsRestoreToNormal) {
  4468. if (normalState[key] != null) {
  4469. if (propNeedsTransition) {
  4470. hasTransition = true;
  4471. transitionTarget[key] = normalState[key];
  4472. }
  4473. else {
  4474. this[key] = normalState[key];
  4475. }
  4476. }
  4477. }
  4478. }
  4479. if (!transition) {
  4480. for (var i = 0; i < this.animators.length; i++) {
  4481. var animator = this.animators[i];
  4482. var targetName = animator.targetName;
  4483. animator.__changeFinalValue(targetName
  4484. ? (state || normalState)[targetName]
  4485. : (state || normalState));
  4486. }
  4487. }
  4488. if (hasTransition) {
  4489. this._transitionState(stateName, transitionTarget, animationCfg);
  4490. }
  4491. };
  4492. Element.prototype._attachComponent = function (componentEl) {
  4493. if (componentEl.__zr && !componentEl.__hostTarget) {
  4494. throw new Error('Text element has been added to zrender.');
  4495. }
  4496. if (componentEl === this) {
  4497. throw new Error('Recursive component attachment.');
  4498. }
  4499. var zr = this.__zr;
  4500. if (zr) {
  4501. componentEl.addSelfToZr(zr);
  4502. }
  4503. componentEl.__zr = zr;
  4504. componentEl.__hostTarget = this;
  4505. };
  4506. Element.prototype._detachComponent = function (componentEl) {
  4507. if (componentEl.__zr) {
  4508. componentEl.removeSelfFromZr(componentEl.__zr);
  4509. }
  4510. componentEl.__zr = null;
  4511. componentEl.__hostTarget = null;
  4512. };
  4513. Element.prototype.getClipPath = function () {
  4514. return this._clipPath;
  4515. };
  4516. Element.prototype.setClipPath = function (clipPath) {
  4517. if (this._clipPath && this._clipPath !== clipPath) {
  4518. this.removeClipPath();
  4519. }
  4520. this._attachComponent(clipPath);
  4521. this._clipPath = clipPath;
  4522. this.markRedraw();
  4523. };
  4524. Element.prototype.removeClipPath = function () {
  4525. var clipPath = this._clipPath;
  4526. if (clipPath) {
  4527. this._detachComponent(clipPath);
  4528. this._clipPath = null;
  4529. this.markRedraw();
  4530. }
  4531. };
  4532. Element.prototype.getTextContent = function () {
  4533. return this._textContent;
  4534. };
  4535. Element.prototype.setTextContent = function (textEl) {
  4536. var previousTextContent = this._textContent;
  4537. if (previousTextContent === textEl) {
  4538. return;
  4539. }
  4540. if (previousTextContent && previousTextContent !== textEl) {
  4541. this.removeTextContent();
  4542. }
  4543. if (textEl.__zr && !textEl.__hostTarget) {
  4544. throw new Error('Text element has been added to zrender.');
  4545. }
  4546. textEl.attachedTransform = new Transformable();
  4547. this._attachComponent(textEl);
  4548. this._textContent = textEl;
  4549. this.markRedraw();
  4550. };
  4551. Element.prototype.setTextConfig = function (cfg) {
  4552. if (!this.textConfig) {
  4553. this.textConfig = {};
  4554. }
  4555. extend(this.textConfig, cfg);
  4556. this.markRedraw();
  4557. };
  4558. Element.prototype.removeTextContent = function () {
  4559. var textEl = this._textContent;
  4560. if (textEl) {
  4561. textEl.attachedTransform = null;
  4562. this._detachComponent(textEl);
  4563. this._textContent = null;
  4564. this._innerTextDefaultStyle = null;
  4565. this.markRedraw();
  4566. }
  4567. };
  4568. Element.prototype.getTextGuideLine = function () {
  4569. return this._textGuide;
  4570. };
  4571. Element.prototype.setTextGuideLine = function (guideLine) {
  4572. if (this._textGuide && this._textGuide !== guideLine) {
  4573. this.removeTextGuideLine();
  4574. }
  4575. this._attachComponent(guideLine);
  4576. this._textGuide = guideLine;
  4577. this.markRedraw();
  4578. };
  4579. Element.prototype.removeTextGuideLine = function () {
  4580. var textGuide = this._textGuide;
  4581. if (textGuide) {
  4582. this._detachComponent(textGuide);
  4583. this._textGuide = null;
  4584. this.markRedraw();
  4585. }
  4586. };
  4587. Element.prototype.markRedraw = function () {
  4588. this.__dirty |= Element.REDARAW_BIT;
  4589. var zr = this.__zr;
  4590. if (zr) {
  4591. if (this.__inHover) {
  4592. zr.refreshHover();
  4593. }
  4594. else {
  4595. zr.refresh();
  4596. }
  4597. }
  4598. if (this.__hostTarget) {
  4599. this.__hostTarget.markRedraw();
  4600. }
  4601. };
  4602. Element.prototype.dirty = function () {
  4603. this.markRedraw();
  4604. };
  4605. Element.prototype._toggleHoverLayerFlag = function (inHover) {
  4606. this.__inHover = inHover;
  4607. var textContent = this._textContent;
  4608. var textGuide = this._textGuide;
  4609. if (textContent) {
  4610. textContent.__inHover = inHover;
  4611. }
  4612. if (textGuide) {
  4613. textGuide.__inHover = inHover;
  4614. }
  4615. };
  4616. Element.prototype.addSelfToZr = function (zr) {
  4617. this.__zr = zr;
  4618. var animators = this.animators;
  4619. if (animators) {
  4620. for (var i = 0; i < animators.length; i++) {
  4621. zr.animation.addAnimator(animators[i]);
  4622. }
  4623. }
  4624. if (this._clipPath) {
  4625. this._clipPath.addSelfToZr(zr);
  4626. }
  4627. if (this._textContent) {
  4628. this._textContent.addSelfToZr(zr);
  4629. }
  4630. if (this._textGuide) {
  4631. this._textGuide.addSelfToZr(zr);
  4632. }
  4633. };
  4634. Element.prototype.removeSelfFromZr = function (zr) {
  4635. this.__zr = null;
  4636. var animators = this.animators;
  4637. if (animators) {
  4638. for (var i = 0; i < animators.length; i++) {
  4639. zr.animation.removeAnimator(animators[i]);
  4640. }
  4641. }
  4642. if (this._clipPath) {
  4643. this._clipPath.removeSelfFromZr(zr);
  4644. }
  4645. if (this._textContent) {
  4646. this._textContent.removeSelfFromZr(zr);
  4647. }
  4648. if (this._textGuide) {
  4649. this._textGuide.removeSelfFromZr(zr);
  4650. }
  4651. };
  4652. Element.prototype.animate = function (key, loop) {
  4653. var target = key ? this[key] : this;
  4654. if (!target) {
  4655. logError('Property "'
  4656. + key
  4657. + '" is not existed in element '
  4658. + this.id);
  4659. return;
  4660. }
  4661. var animator = new Animator(target, loop);
  4662. this.addAnimator(animator, key);
  4663. return animator;
  4664. };
  4665. Element.prototype.addAnimator = function (animator, key) {
  4666. var zr = this.__zr;
  4667. var el = this;
  4668. animator.during(function () {
  4669. el.updateDuringAnimation(key);
  4670. }).done(function () {
  4671. var animators = el.animators;
  4672. var idx = indexOf(animators, animator);
  4673. if (idx >= 0) {
  4674. animators.splice(idx, 1);
  4675. }
  4676. });
  4677. this.animators.push(animator);
  4678. if (zr) {
  4679. zr.animation.addAnimator(animator);
  4680. }
  4681. zr && zr.wakeUp();
  4682. };
  4683. Element.prototype.updateDuringAnimation = function (key) {
  4684. this.markRedraw();
  4685. };
  4686. Element.prototype.stopAnimation = function (scope, forwardToLast) {
  4687. var animators = this.animators;
  4688. var len = animators.length;
  4689. var leftAnimators = [];
  4690. for (var i = 0; i < len; i++) {
  4691. var animator = animators[i];
  4692. if (!scope || scope === animator.scope) {
  4693. animator.stop(forwardToLast);
  4694. }
  4695. else {
  4696. leftAnimators.push(animator);
  4697. }
  4698. }
  4699. this.animators = leftAnimators;
  4700. return this;
  4701. };
  4702. Element.prototype.animateTo = function (target, cfg, animationProps) {
  4703. animateTo(this, target, cfg, animationProps);
  4704. };
  4705. Element.prototype.animateFrom = function (target, cfg, animationProps) {
  4706. animateTo(this, target, cfg, animationProps, true);
  4707. };
  4708. Element.prototype._transitionState = function (stateName, target, cfg, animationProps) {
  4709. var animators = animateTo(this, target, cfg, animationProps);
  4710. for (var i = 0; i < animators.length; i++) {
  4711. animators[i].__fromStateTransition = stateName;
  4712. }
  4713. };
  4714. Element.prototype.getBoundingRect = function () {
  4715. return null;
  4716. };
  4717. Element.prototype.getPaintRect = function () {
  4718. return null;
  4719. };
  4720. Element.REDARAW_BIT = 1;
  4721. Element.initDefaultProps = (function () {
  4722. var elProto = Element.prototype;
  4723. elProto.type = 'element';
  4724. elProto.name = '';
  4725. elProto.ignore = false;
  4726. elProto.silent = false;
  4727. elProto.isGroup = false;
  4728. elProto.draggable = false;
  4729. elProto.dragging = false;
  4730. elProto.ignoreClip = false;
  4731. elProto.__inHover = false;
  4732. elProto.__dirty = Element.REDARAW_BIT;
  4733. var logs = {};
  4734. function logDeprecatedError(key, xKey, yKey) {
  4735. if (!logs[key + xKey + yKey]) {
  4736. console.warn("DEPRECATED: '" + key + "' has been deprecated. use '" + xKey + "', '" + yKey + "' instead");
  4737. logs[key + xKey + yKey] = true;
  4738. }
  4739. }
  4740. function createLegacyProperty(key, privateKey, xKey, yKey) {
  4741. Object.defineProperty(elProto, key, {
  4742. get: function () {
  4743. logDeprecatedError(key, xKey, yKey);
  4744. if (!this[privateKey]) {
  4745. var pos = this[privateKey] = [];
  4746. enhanceArray(this, pos);
  4747. }
  4748. return this[privateKey];
  4749. },
  4750. set: function (pos) {
  4751. logDeprecatedError(key, xKey, yKey);
  4752. this[xKey] = pos[0];
  4753. this[yKey] = pos[1];
  4754. this[privateKey] = pos;
  4755. enhanceArray(this, pos);
  4756. }
  4757. });
  4758. function enhanceArray(self, pos) {
  4759. Object.defineProperty(pos, 0, {
  4760. get: function () {
  4761. return self[xKey];
  4762. },
  4763. set: function (val) {
  4764. self[xKey] = val;
  4765. }
  4766. });
  4767. Object.defineProperty(pos, 1, {
  4768. get: function () {
  4769. return self[yKey];
  4770. },
  4771. set: function (val) {
  4772. self[yKey] = val;
  4773. }
  4774. });
  4775. }
  4776. }
  4777. if (Object.defineProperty && (!env.browser.ie || env.browser.version > 8)) {
  4778. createLegacyProperty('position', '_legacyPos', 'x', 'y');
  4779. createLegacyProperty('scale', '_legacyScale', 'scaleX', 'scaleY');
  4780. createLegacyProperty('origin', '_legacyOrigin', 'originX', 'originY');
  4781. }
  4782. })();
  4783. return Element;
  4784. }());
  4785. mixin(Element, Eventful);
  4786. mixin(Element, Transformable);
  4787. function animateTo(animatable, target, cfg, animationProps, reverse) {
  4788. cfg = cfg || {};
  4789. var animators = [];
  4790. animateToShallow(animatable, '', animatable, target, cfg, animationProps, animators, reverse);
  4791. var finishCount = animators.length;
  4792. var doneHappened = false;
  4793. var cfgDone = cfg.done;
  4794. var cfgAborted = cfg.aborted;
  4795. var doneCb = function () {
  4796. doneHappened = true;
  4797. finishCount--;
  4798. if (finishCount <= 0) {
  4799. doneHappened
  4800. ? (cfgDone && cfgDone())
  4801. : (cfgAborted && cfgAborted());
  4802. }
  4803. };
  4804. var abortedCb = function () {
  4805. finishCount--;
  4806. if (finishCount <= 0) {
  4807. doneHappened
  4808. ? (cfgDone && cfgDone())
  4809. : (cfgAborted && cfgAborted());
  4810. }
  4811. };
  4812. if (!finishCount) {
  4813. cfgDone && cfgDone();
  4814. }
  4815. if (animators.length > 0 && cfg.during) {
  4816. animators[0].during(function (target, percent) {
  4817. cfg.during(percent);
  4818. });
  4819. }
  4820. for (var i = 0; i < animators.length; i++) {
  4821. var animator = animators[i];
  4822. if (doneCb) {
  4823. animator.done(doneCb);
  4824. }
  4825. if (abortedCb) {
  4826. animator.aborted(abortedCb);
  4827. }
  4828. animator.start(cfg.easing, cfg.force);
  4829. }
  4830. return animators;
  4831. }
  4832. function copyArrShallow(source, target, len) {
  4833. for (var i = 0; i < len; i++) {
  4834. source[i] = target[i];
  4835. }
  4836. }
  4837. function is2DArray(value) {
  4838. return isArrayLike(value[0]);
  4839. }
  4840. function copyValue(target, source, key) {
  4841. if (isArrayLike(source[key])) {
  4842. if (!isArrayLike(target[key])) {
  4843. target[key] = [];
  4844. }
  4845. if (isTypedArray(source[key])) {
  4846. var len = source[key].length;
  4847. if (target[key].length !== len) {
  4848. target[key] = new (source[key].constructor)(len);
  4849. copyArrShallow(target[key], source[key], len);
  4850. }
  4851. }
  4852. else {
  4853. var sourceArr = source[key];
  4854. var targetArr = target[key];
  4855. var len0 = sourceArr.length;
  4856. if (is2DArray(sourceArr)) {
  4857. var len1 = sourceArr[0].length;
  4858. for (var i = 0; i < len0; i++) {
  4859. if (!targetArr[i]) {
  4860. targetArr[i] = Array.prototype.slice.call(sourceArr[i]);
  4861. }
  4862. else {
  4863. copyArrShallow(targetArr[i], sourceArr[i], len1);
  4864. }
  4865. }
  4866. }
  4867. else {
  4868. copyArrShallow(targetArr, sourceArr, len0);
  4869. }
  4870. targetArr.length = sourceArr.length;
  4871. }
  4872. }
  4873. else {
  4874. target[key] = source[key];
  4875. }
  4876. }
  4877. function animateToShallow(animatable, topKey, source, target, cfg, animationProps, animators, reverse) {
  4878. var animatableKeys = [];
  4879. var changedKeys = [];
  4880. var targetKeys = keys(target);
  4881. var duration = cfg.duration;
  4882. var delay = cfg.delay;
  4883. var additive = cfg.additive;
  4884. var setToFinal = cfg.setToFinal;
  4885. var animateAll = !isObject(animationProps);
  4886. for (var k = 0; k < targetKeys.length; k++) {
  4887. var innerKey = targetKeys[k];
  4888. if (source[innerKey] != null
  4889. && target[innerKey] != null
  4890. && (animateAll || animationProps[innerKey])) {
  4891. if (isObject(target[innerKey]) && !isArrayLike(target[innerKey])) {
  4892. if (topKey) {
  4893. if (!reverse) {
  4894. source[innerKey] = target[innerKey];
  4895. animatable.updateDuringAnimation(topKey);
  4896. }
  4897. continue;
  4898. }
  4899. animateToShallow(animatable, innerKey, source[innerKey], target[innerKey], cfg, animationProps && animationProps[innerKey], animators, reverse);
  4900. }
  4901. else {
  4902. animatableKeys.push(innerKey);
  4903. changedKeys.push(innerKey);
  4904. }
  4905. }
  4906. else if (!reverse) {
  4907. source[innerKey] = target[innerKey];
  4908. animatable.updateDuringAnimation(topKey);
  4909. changedKeys.push(innerKey);
  4910. }
  4911. }
  4912. var keyLen = animatableKeys.length;
  4913. if (keyLen > 0
  4914. || (cfg.force && !animators.length)) {
  4915. var existsAnimators = animatable.animators;
  4916. var existsAnimatorsOnSameTarget = [];
  4917. for (var i = 0; i < existsAnimators.length; i++) {
  4918. if (existsAnimators[i].targetName === topKey) {
  4919. existsAnimatorsOnSameTarget.push(existsAnimators[i]);
  4920. }
  4921. }
  4922. if (!additive && existsAnimatorsOnSameTarget.length) {
  4923. for (var i = 0; i < existsAnimatorsOnSameTarget.length; i++) {
  4924. var allAborted = existsAnimatorsOnSameTarget[i].stopTracks(changedKeys);
  4925. if (allAborted) {
  4926. var idx = indexOf(existsAnimators, existsAnimatorsOnSameTarget[i]);
  4927. existsAnimators.splice(idx, 1);
  4928. }
  4929. }
  4930. }
  4931. var revertedSource = void 0;
  4932. var reversedTarget = void 0;
  4933. var sourceClone = void 0;
  4934. if (reverse) {
  4935. reversedTarget = {};
  4936. if (setToFinal) {
  4937. revertedSource = {};
  4938. }
  4939. for (var i = 0; i < keyLen; i++) {
  4940. var innerKey = animatableKeys[i];
  4941. reversedTarget[innerKey] = source[innerKey];
  4942. if (setToFinal) {
  4943. revertedSource[innerKey] = target[innerKey];
  4944. }
  4945. else {
  4946. source[innerKey] = target[innerKey];
  4947. }
  4948. }
  4949. }
  4950. else if (setToFinal) {
  4951. sourceClone = {};
  4952. for (var i = 0; i < keyLen; i++) {
  4953. var innerKey = animatableKeys[i];
  4954. sourceClone[innerKey] = cloneValue(source[innerKey]);
  4955. copyValue(source, target, innerKey);
  4956. }
  4957. }
  4958. var animator = new Animator(source, false, additive ? existsAnimatorsOnSameTarget : null);
  4959. animator.targetName = topKey;
  4960. if (cfg.scope) {
  4961. animator.scope = cfg.scope;
  4962. }
  4963. if (setToFinal && revertedSource) {
  4964. animator.whenWithKeys(0, revertedSource, animatableKeys);
  4965. }
  4966. if (sourceClone) {
  4967. animator.whenWithKeys(0, sourceClone, animatableKeys);
  4968. }
  4969. animator.whenWithKeys(duration == null ? 500 : duration, reverse ? reversedTarget : target, animatableKeys).delay(delay || 0);
  4970. animatable.addAnimator(animator, topKey);
  4971. animators.push(animator);
  4972. }
  4973. }
  4974. var DEFAULT_MIN_MERGE = 32;
  4975. var DEFAULT_MIN_GALLOPING = 7;
  4976. function minRunLength(n) {
  4977. var r = 0;
  4978. while (n >= DEFAULT_MIN_MERGE) {
  4979. r |= n & 1;
  4980. n >>= 1;
  4981. }
  4982. return n + r;
  4983. }
  4984. function makeAscendingRun(array, lo, hi, compare) {
  4985. var runHi = lo + 1;
  4986. if (runHi === hi) {
  4987. return 1;
  4988. }
  4989. if (compare(array[runHi++], array[lo]) < 0) {
  4990. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4991. runHi++;
  4992. }
  4993. reverseRun(array, lo, runHi);
  4994. }
  4995. else {
  4996. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4997. runHi++;
  4998. }
  4999. }
  5000. return runHi - lo;
  5001. }
  5002. function reverseRun(array, lo, hi) {
  5003. hi--;
  5004. while (lo < hi) {
  5005. var t = array[lo];
  5006. array[lo++] = array[hi];
  5007. array[hi--] = t;
  5008. }
  5009. }
  5010. function binaryInsertionSort(array, lo, hi, start, compare) {
  5011. if (start === lo) {
  5012. start++;
  5013. }
  5014. for (; start < hi; start++) {
  5015. var pivot = array[start];
  5016. var left = lo;
  5017. var right = start;
  5018. var mid;
  5019. while (left < right) {
  5020. mid = left + right >>> 1;
  5021. if (compare(pivot, array[mid]) < 0) {
  5022. right = mid;
  5023. }
  5024. else {
  5025. left = mid + 1;
  5026. }
  5027. }
  5028. var n = start - left;
  5029. switch (n) {
  5030. case 3:
  5031. array[left + 3] = array[left + 2];
  5032. case 2:
  5033. array[left + 2] = array[left + 1];
  5034. case 1:
  5035. array[left + 1] = array[left];
  5036. break;
  5037. default:
  5038. while (n > 0) {
  5039. array[left + n] = array[left + n - 1];
  5040. n--;
  5041. }
  5042. }
  5043. array[left] = pivot;
  5044. }
  5045. }
  5046. function gallopLeft(value, array, start, length, hint, compare) {
  5047. var lastOffset = 0;
  5048. var maxOffset = 0;
  5049. var offset = 1;
  5050. if (compare(value, array[start + hint]) > 0) {
  5051. maxOffset = length - hint;
  5052. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5053. lastOffset = offset;
  5054. offset = (offset << 1) + 1;
  5055. if (offset <= 0) {
  5056. offset = maxOffset;
  5057. }
  5058. }
  5059. if (offset > maxOffset) {
  5060. offset = maxOffset;
  5061. }
  5062. lastOffset += hint;
  5063. offset += hint;
  5064. }
  5065. else {
  5066. maxOffset = hint + 1;
  5067. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5068. lastOffset = offset;
  5069. offset = (offset << 1) + 1;
  5070. if (offset <= 0) {
  5071. offset = maxOffset;
  5072. }
  5073. }
  5074. if (offset > maxOffset) {
  5075. offset = maxOffset;
  5076. }
  5077. var tmp = lastOffset;
  5078. lastOffset = hint - offset;
  5079. offset = hint - tmp;
  5080. }
  5081. lastOffset++;
  5082. while (lastOffset < offset) {
  5083. var m = lastOffset + (offset - lastOffset >>> 1);
  5084. if (compare(value, array[start + m]) > 0) {
  5085. lastOffset = m + 1;
  5086. }
  5087. else {
  5088. offset = m;
  5089. }
  5090. }
  5091. return offset;
  5092. }
  5093. function gallopRight(value, array, start, length, hint, compare) {
  5094. var lastOffset = 0;
  5095. var maxOffset = 0;
  5096. var offset = 1;
  5097. if (compare(value, array[start + hint]) < 0) {
  5098. maxOffset = hint + 1;
  5099. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5100. lastOffset = offset;
  5101. offset = (offset << 1) + 1;
  5102. if (offset <= 0) {
  5103. offset = maxOffset;
  5104. }
  5105. }
  5106. if (offset > maxOffset) {
  5107. offset = maxOffset;
  5108. }
  5109. var tmp = lastOffset;
  5110. lastOffset = hint - offset;
  5111. offset = hint - tmp;
  5112. }
  5113. else {
  5114. maxOffset = length - hint;
  5115. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5116. lastOffset = offset;
  5117. offset = (offset << 1) + 1;
  5118. if (offset <= 0) {
  5119. offset = maxOffset;
  5120. }
  5121. }
  5122. if (offset > maxOffset) {
  5123. offset = maxOffset;
  5124. }
  5125. lastOffset += hint;
  5126. offset += hint;
  5127. }
  5128. lastOffset++;
  5129. while (lastOffset < offset) {
  5130. var m = lastOffset + (offset - lastOffset >>> 1);
  5131. if (compare(value, array[start + m]) < 0) {
  5132. offset = m;
  5133. }
  5134. else {
  5135. lastOffset = m + 1;
  5136. }
  5137. }
  5138. return offset;
  5139. }
  5140. function TimSort(array, compare) {
  5141. var minGallop = DEFAULT_MIN_GALLOPING;
  5142. var length = 0;
  5143. var runStart;
  5144. var runLength;
  5145. var stackSize = 0;
  5146. length = array.length;
  5147. var tmp = [];
  5148. runStart = [];
  5149. runLength = [];
  5150. function pushRun(_runStart, _runLength) {
  5151. runStart[stackSize] = _runStart;
  5152. runLength[stackSize] = _runLength;
  5153. stackSize += 1;
  5154. }
  5155. function mergeRuns() {
  5156. while (stackSize > 1) {
  5157. var n = stackSize - 2;
  5158. if ((n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1])
  5159. || (n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1])) {
  5160. if (runLength[n - 1] < runLength[n + 1]) {
  5161. n--;
  5162. }
  5163. }
  5164. else if (runLength[n] > runLength[n + 1]) {
  5165. break;
  5166. }
  5167. mergeAt(n);
  5168. }
  5169. }
  5170. function forceMergeRuns() {
  5171. while (stackSize > 1) {
  5172. var n = stackSize - 2;
  5173. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5174. n--;
  5175. }
  5176. mergeAt(n);
  5177. }
  5178. }
  5179. function mergeAt(i) {
  5180. var start1 = runStart[i];
  5181. var length1 = runLength[i];
  5182. var start2 = runStart[i + 1];
  5183. var length2 = runLength[i + 1];
  5184. runLength[i] = length1 + length2;
  5185. if (i === stackSize - 3) {
  5186. runStart[i + 1] = runStart[i + 2];
  5187. runLength[i + 1] = runLength[i + 2];
  5188. }
  5189. stackSize--;
  5190. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5191. start1 += k;
  5192. length1 -= k;
  5193. if (length1 === 0) {
  5194. return;
  5195. }
  5196. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5197. if (length2 === 0) {
  5198. return;
  5199. }
  5200. if (length1 <= length2) {
  5201. mergeLow(start1, length1, start2, length2);
  5202. }
  5203. else {
  5204. mergeHigh(start1, length1, start2, length2);
  5205. }
  5206. }
  5207. function mergeLow(start1, length1, start2, length2) {
  5208. var i = 0;
  5209. for (i = 0; i < length1; i++) {
  5210. tmp[i] = array[start1 + i];
  5211. }
  5212. var cursor1 = 0;
  5213. var cursor2 = start2;
  5214. var dest = start1;
  5215. array[dest++] = array[cursor2++];
  5216. if (--length2 === 0) {
  5217. for (i = 0; i < length1; i++) {
  5218. array[dest + i] = tmp[cursor1 + i];
  5219. }
  5220. return;
  5221. }
  5222. if (length1 === 1) {
  5223. for (i = 0; i < length2; i++) {
  5224. array[dest + i] = array[cursor2 + i];
  5225. }
  5226. array[dest + length2] = tmp[cursor1];
  5227. return;
  5228. }
  5229. var _minGallop = minGallop;
  5230. var count1;
  5231. var count2;
  5232. var exit;
  5233. while (1) {
  5234. count1 = 0;
  5235. count2 = 0;
  5236. exit = false;
  5237. do {
  5238. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5239. array[dest++] = array[cursor2++];
  5240. count2++;
  5241. count1 = 0;
  5242. if (--length2 === 0) {
  5243. exit = true;
  5244. break;
  5245. }
  5246. }
  5247. else {
  5248. array[dest++] = tmp[cursor1++];
  5249. count1++;
  5250. count2 = 0;
  5251. if (--length1 === 1) {
  5252. exit = true;
  5253. break;
  5254. }
  5255. }
  5256. } while ((count1 | count2) < _minGallop);
  5257. if (exit) {
  5258. break;
  5259. }
  5260. do {
  5261. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5262. if (count1 !== 0) {
  5263. for (i = 0; i < count1; i++) {
  5264. array[dest + i] = tmp[cursor1 + i];
  5265. }
  5266. dest += count1;
  5267. cursor1 += count1;
  5268. length1 -= count1;
  5269. if (length1 <= 1) {
  5270. exit = true;
  5271. break;
  5272. }
  5273. }
  5274. array[dest++] = array[cursor2++];
  5275. if (--length2 === 0) {
  5276. exit = true;
  5277. break;
  5278. }
  5279. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5280. if (count2 !== 0) {
  5281. for (i = 0; i < count2; i++) {
  5282. array[dest + i] = array[cursor2 + i];
  5283. }
  5284. dest += count2;
  5285. cursor2 += count2;
  5286. length2 -= count2;
  5287. if (length2 === 0) {
  5288. exit = true;
  5289. break;
  5290. }
  5291. }
  5292. array[dest++] = tmp[cursor1++];
  5293. if (--length1 === 1) {
  5294. exit = true;
  5295. break;
  5296. }
  5297. _minGallop--;
  5298. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5299. if (exit) {
  5300. break;
  5301. }
  5302. if (_minGallop < 0) {
  5303. _minGallop = 0;
  5304. }
  5305. _minGallop += 2;
  5306. }
  5307. minGallop = _minGallop;
  5308. minGallop < 1 && (minGallop = 1);
  5309. if (length1 === 1) {
  5310. for (i = 0; i < length2; i++) {
  5311. array[dest + i] = array[cursor2 + i];
  5312. }
  5313. array[dest + length2] = tmp[cursor1];
  5314. }
  5315. else if (length1 === 0) {
  5316. throw new Error();
  5317. }
  5318. else {
  5319. for (i = 0; i < length1; i++) {
  5320. array[dest + i] = tmp[cursor1 + i];
  5321. }
  5322. }
  5323. }
  5324. function mergeHigh(start1, length1, start2, length2) {
  5325. var i = 0;
  5326. for (i = 0; i < length2; i++) {
  5327. tmp[i] = array[start2 + i];
  5328. }
  5329. var cursor1 = start1 + length1 - 1;
  5330. var cursor2 = length2 - 1;
  5331. var dest = start2 + length2 - 1;
  5332. var customCursor = 0;
  5333. var customDest = 0;
  5334. array[dest--] = array[cursor1--];
  5335. if (--length1 === 0) {
  5336. customCursor = dest - (length2 - 1);
  5337. for (i = 0; i < length2; i++) {
  5338. array[customCursor + i] = tmp[i];
  5339. }
  5340. return;
  5341. }
  5342. if (length2 === 1) {
  5343. dest -= length1;
  5344. cursor1 -= length1;
  5345. customDest = dest + 1;
  5346. customCursor = cursor1 + 1;
  5347. for (i = length1 - 1; i >= 0; i--) {
  5348. array[customDest + i] = array[customCursor + i];
  5349. }
  5350. array[dest] = tmp[cursor2];
  5351. return;
  5352. }
  5353. var _minGallop = minGallop;
  5354. while (true) {
  5355. var count1 = 0;
  5356. var count2 = 0;
  5357. var exit = false;
  5358. do {
  5359. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5360. array[dest--] = array[cursor1--];
  5361. count1++;
  5362. count2 = 0;
  5363. if (--length1 === 0) {
  5364. exit = true;
  5365. break;
  5366. }
  5367. }
  5368. else {
  5369. array[dest--] = tmp[cursor2--];
  5370. count2++;
  5371. count1 = 0;
  5372. if (--length2 === 1) {
  5373. exit = true;
  5374. break;
  5375. }
  5376. }
  5377. } while ((count1 | count2) < _minGallop);
  5378. if (exit) {
  5379. break;
  5380. }
  5381. do {
  5382. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5383. if (count1 !== 0) {
  5384. dest -= count1;
  5385. cursor1 -= count1;
  5386. length1 -= count1;
  5387. customDest = dest + 1;
  5388. customCursor = cursor1 + 1;
  5389. for (i = count1 - 1; i >= 0; i--) {
  5390. array[customDest + i] = array[customCursor + i];
  5391. }
  5392. if (length1 === 0) {
  5393. exit = true;
  5394. break;
  5395. }
  5396. }
  5397. array[dest--] = tmp[cursor2--];
  5398. if (--length2 === 1) {
  5399. exit = true;
  5400. break;
  5401. }
  5402. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5403. if (count2 !== 0) {
  5404. dest -= count2;
  5405. cursor2 -= count2;
  5406. length2 -= count2;
  5407. customDest = dest + 1;
  5408. customCursor = cursor2 + 1;
  5409. for (i = 0; i < count2; i++) {
  5410. array[customDest + i] = tmp[customCursor + i];
  5411. }
  5412. if (length2 <= 1) {
  5413. exit = true;
  5414. break;
  5415. }
  5416. }
  5417. array[dest--] = array[cursor1--];
  5418. if (--length1 === 0) {
  5419. exit = true;
  5420. break;
  5421. }
  5422. _minGallop--;
  5423. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5424. if (exit) {
  5425. break;
  5426. }
  5427. if (_minGallop < 0) {
  5428. _minGallop = 0;
  5429. }
  5430. _minGallop += 2;
  5431. }
  5432. minGallop = _minGallop;
  5433. if (minGallop < 1) {
  5434. minGallop = 1;
  5435. }
  5436. if (length2 === 1) {
  5437. dest -= length1;
  5438. cursor1 -= length1;
  5439. customDest = dest + 1;
  5440. customCursor = cursor1 + 1;
  5441. for (i = length1 - 1; i >= 0; i--) {
  5442. array[customDest + i] = array[customCursor + i];
  5443. }
  5444. array[dest] = tmp[cursor2];
  5445. }
  5446. else if (length2 === 0) {
  5447. throw new Error();
  5448. }
  5449. else {
  5450. customCursor = dest - (length2 - 1);
  5451. for (i = 0; i < length2; i++) {
  5452. array[customCursor + i] = tmp[i];
  5453. }
  5454. }
  5455. }
  5456. return {
  5457. mergeRuns: mergeRuns,
  5458. forceMergeRuns: forceMergeRuns,
  5459. pushRun: pushRun
  5460. };
  5461. }
  5462. function sort(array, compare, lo, hi) {
  5463. if (!lo) {
  5464. lo = 0;
  5465. }
  5466. if (!hi) {
  5467. hi = array.length;
  5468. }
  5469. var remaining = hi - lo;
  5470. if (remaining < 2) {
  5471. return;
  5472. }
  5473. var runLength = 0;
  5474. if (remaining < DEFAULT_MIN_MERGE) {
  5475. runLength = makeAscendingRun(array, lo, hi, compare);
  5476. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5477. return;
  5478. }
  5479. var ts = TimSort(array, compare);
  5480. var minRun = minRunLength(remaining);
  5481. do {
  5482. runLength = makeAscendingRun(array, lo, hi, compare);
  5483. if (runLength < minRun) {
  5484. var force = remaining;
  5485. if (force > minRun) {
  5486. force = minRun;
  5487. }
  5488. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5489. runLength = force;
  5490. }
  5491. ts.pushRun(lo, runLength);
  5492. ts.mergeRuns();
  5493. remaining -= runLength;
  5494. lo += runLength;
  5495. } while (remaining !== 0);
  5496. ts.forceMergeRuns();
  5497. }
  5498. var invalidZErrorLogged = false;
  5499. function logInvalidZError() {
  5500. if (invalidZErrorLogged) {
  5501. return;
  5502. }
  5503. invalidZErrorLogged = true;
  5504. console.warn('z / z2 / zlevel of displayable is invalid, which may cause unexpected errors');
  5505. }
  5506. function shapeCompareFunc(a, b) {
  5507. if (a.zlevel === b.zlevel) {
  5508. if (a.z === b.z) {
  5509. return a.z2 - b.z2;
  5510. }
  5511. return a.z - b.z;
  5512. }
  5513. return a.zlevel - b.zlevel;
  5514. }
  5515. var Storage = (function () {
  5516. function Storage() {
  5517. this._roots = [];
  5518. this._displayList = [];
  5519. this._displayListLen = 0;
  5520. this.displayableSortFunc = shapeCompareFunc;
  5521. }
  5522. Storage.prototype.traverse = function (cb, context) {
  5523. for (var i = 0; i < this._roots.length; i++) {
  5524. this._roots[i].traverse(cb, context);
  5525. }
  5526. };
  5527. Storage.prototype.getDisplayList = function (update, includeIgnore) {
  5528. includeIgnore = includeIgnore || false;
  5529. var displayList = this._displayList;
  5530. if (update || !displayList.length) {
  5531. this.updateDisplayList(includeIgnore);
  5532. }
  5533. return displayList;
  5534. };
  5535. Storage.prototype.updateDisplayList = function (includeIgnore) {
  5536. this._displayListLen = 0;
  5537. var roots = this._roots;
  5538. var displayList = this._displayList;
  5539. for (var i = 0, len = roots.length; i < len; i++) {
  5540. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5541. }
  5542. displayList.length = this._displayListLen;
  5543. env.canvasSupported && sort(displayList, shapeCompareFunc);
  5544. };
  5545. Storage.prototype._updateAndAddDisplayable = function (el, clipPaths, includeIgnore) {
  5546. if (el.ignore && !includeIgnore) {
  5547. return;
  5548. }
  5549. el.beforeUpdate();
  5550. el.update();
  5551. el.afterUpdate();
  5552. var userSetClipPath = el.getClipPath();
  5553. if (el.ignoreClip) {
  5554. clipPaths = null;
  5555. }
  5556. else if (userSetClipPath) {
  5557. if (clipPaths) {
  5558. clipPaths = clipPaths.slice();
  5559. }
  5560. else {
  5561. clipPaths = [];
  5562. }
  5563. var currentClipPath = userSetClipPath;
  5564. var parentClipPath = el;
  5565. while (currentClipPath) {
  5566. currentClipPath.parent = parentClipPath;
  5567. currentClipPath.updateTransform();
  5568. clipPaths.push(currentClipPath);
  5569. parentClipPath = currentClipPath;
  5570. currentClipPath = currentClipPath.getClipPath();
  5571. }
  5572. }
  5573. if (el.childrenRef) {
  5574. var children = el.childrenRef();
  5575. for (var i = 0; i < children.length; i++) {
  5576. var child = children[i];
  5577. if (el.__dirty) {
  5578. child.__dirty |= Element.REDARAW_BIT;
  5579. }
  5580. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5581. }
  5582. el.__dirty = 0;
  5583. }
  5584. else {
  5585. var disp = el;
  5586. if (clipPaths && clipPaths.length) {
  5587. disp.__clipPaths = clipPaths;
  5588. }
  5589. else if (disp.__clipPaths && disp.__clipPaths.length > 0) {
  5590. disp.__clipPaths = [];
  5591. }
  5592. if (isNaN(disp.z)) {
  5593. logInvalidZError();
  5594. disp.z = 0;
  5595. }
  5596. if (isNaN(disp.z2)) {
  5597. logInvalidZError();
  5598. disp.z2 = 0;
  5599. }
  5600. if (isNaN(disp.zlevel)) {
  5601. logInvalidZError();
  5602. disp.zlevel = 0;
  5603. }
  5604. this._displayList[this._displayListLen++] = disp;
  5605. }
  5606. var decalEl = el.getDecalElement && el.getDecalElement();
  5607. if (decalEl) {
  5608. this._updateAndAddDisplayable(decalEl, clipPaths, includeIgnore);
  5609. }
  5610. var textGuide = el.getTextGuideLine();
  5611. if (textGuide) {
  5612. this._updateAndAddDisplayable(textGuide, clipPaths, includeIgnore);
  5613. }
  5614. var textEl = el.getTextContent();
  5615. if (textEl) {
  5616. this._updateAndAddDisplayable(textEl, clipPaths, includeIgnore);
  5617. }
  5618. };
  5619. Storage.prototype.addRoot = function (el) {
  5620. if (el.__zr && el.__zr.storage === this) {
  5621. return;
  5622. }
  5623. this._roots.push(el);
  5624. };
  5625. Storage.prototype.delRoot = function (el) {
  5626. if (el instanceof Array) {
  5627. for (var i = 0, l = el.length; i < l; i++) {
  5628. this.delRoot(el[i]);
  5629. }
  5630. return;
  5631. }
  5632. var idx = indexOf(this._roots, el);
  5633. if (idx >= 0) {
  5634. this._roots.splice(idx, 1);
  5635. }
  5636. };
  5637. Storage.prototype.delAllRoots = function () {
  5638. this._roots = [];
  5639. this._displayList = [];
  5640. this._displayListLen = 0;
  5641. return;
  5642. };
  5643. Storage.prototype.getRoots = function () {
  5644. return this._roots;
  5645. };
  5646. Storage.prototype.dispose = function () {
  5647. this._displayList = null;
  5648. this._roots = null;
  5649. };
  5650. return Storage;
  5651. }());
  5652. var requestAnimationFrame;
  5653. requestAnimationFrame = (typeof window !== 'undefined'
  5654. && ((window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5655. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5656. || window.mozRequestAnimationFrame
  5657. || window.webkitRequestAnimationFrame)) || function (func) {
  5658. return setTimeout(func, 16);
  5659. };
  5660. var requestAnimationFrame$1 = requestAnimationFrame;
  5661. var Animation = (function (_super) {
  5662. __extends(Animation, _super);
  5663. function Animation(opts) {
  5664. var _this = _super.call(this) || this;
  5665. _this._running = false;
  5666. _this._time = 0;
  5667. _this._pausedTime = 0;
  5668. _this._pauseStart = 0;
  5669. _this._paused = false;
  5670. opts = opts || {};
  5671. _this.stage = opts.stage || {};
  5672. _this.onframe = opts.onframe || function () { };
  5673. return _this;
  5674. }
  5675. Animation.prototype.addClip = function (clip) {
  5676. if (clip.animation) {
  5677. this.removeClip(clip);
  5678. }
  5679. if (!this._clipsHead) {
  5680. this._clipsHead = this._clipsTail = clip;
  5681. }
  5682. else {
  5683. this._clipsTail.next = clip;
  5684. clip.prev = this._clipsTail;
  5685. clip.next = null;
  5686. this._clipsTail = clip;
  5687. }
  5688. clip.animation = this;
  5689. };
  5690. Animation.prototype.addAnimator = function (animator) {
  5691. animator.animation = this;
  5692. var clip = animator.getClip();
  5693. if (clip) {
  5694. this.addClip(clip);
  5695. }
  5696. };
  5697. Animation.prototype.removeClip = function (clip) {
  5698. if (!clip.animation) {
  5699. return;
  5700. }
  5701. var prev = clip.prev;
  5702. var next = clip.next;
  5703. if (prev) {
  5704. prev.next = next;
  5705. }
  5706. else {
  5707. this._clipsHead = next;
  5708. }
  5709. if (next) {
  5710. next.prev = prev;
  5711. }
  5712. else {
  5713. this._clipsTail = prev;
  5714. }
  5715. clip.next = clip.prev = clip.animation = null;
  5716. };
  5717. Animation.prototype.removeAnimator = function (animator) {
  5718. var clip = animator.getClip();
  5719. if (clip) {
  5720. this.removeClip(clip);
  5721. }
  5722. animator.animation = null;
  5723. };
  5724. Animation.prototype.update = function (notTriggerFrameAndStageUpdate) {
  5725. var time = new Date().getTime() - this._pausedTime;
  5726. var delta = time - this._time;
  5727. var clip = this._clipsHead;
  5728. while (clip) {
  5729. var nextClip = clip.next;
  5730. var finished = clip.step(time, delta);
  5731. if (finished) {
  5732. clip.ondestroy && clip.ondestroy();
  5733. this.removeClip(clip);
  5734. clip = nextClip;
  5735. }
  5736. else {
  5737. clip = nextClip;
  5738. }
  5739. }
  5740. this._time = time;
  5741. if (!notTriggerFrameAndStageUpdate) {
  5742. this.onframe(delta);
  5743. this.trigger('frame', delta);
  5744. this.stage.update && this.stage.update();
  5745. }
  5746. };
  5747. Animation.prototype._startLoop = function () {
  5748. var self = this;
  5749. this._running = true;
  5750. function step() {
  5751. if (self._running) {
  5752. requestAnimationFrame$1(step);
  5753. !self._paused && self.update();
  5754. }
  5755. }
  5756. requestAnimationFrame$1(step);
  5757. };
  5758. Animation.prototype.start = function () {
  5759. if (this._running) {
  5760. return;
  5761. }
  5762. this._time = new Date().getTime();
  5763. this._pausedTime = 0;
  5764. this._startLoop();
  5765. };
  5766. Animation.prototype.stop = function () {
  5767. this._running = false;
  5768. };
  5769. Animation.prototype.pause = function () {
  5770. if (!this._paused) {
  5771. this._pauseStart = new Date().getTime();
  5772. this._paused = true;
  5773. }
  5774. };
  5775. Animation.prototype.resume = function () {
  5776. if (this._paused) {
  5777. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  5778. this._paused = false;
  5779. }
  5780. };
  5781. Animation.prototype.clear = function () {
  5782. var clip = this._clipsHead;
  5783. while (clip) {
  5784. var nextClip = clip.next;
  5785. clip.prev = clip.next = clip.animation = null;
  5786. clip = nextClip;
  5787. }
  5788. this._clipsHead = this._clipsTail = null;
  5789. };
  5790. Animation.prototype.isFinished = function () {
  5791. return this._clipsHead == null;
  5792. };
  5793. Animation.prototype.animate = function (target, options) {
  5794. options = options || {};
  5795. this.start();
  5796. var animator = new Animator(target, options.loop);
  5797. this.addAnimator(animator);
  5798. return animator;
  5799. };
  5800. return Animation;
  5801. }(Eventful));
  5802. var TOUCH_CLICK_DELAY = 300;
  5803. var globalEventSupported = env.domSupported;
  5804. var localNativeListenerNames = (function () {
  5805. var mouseHandlerNames = [
  5806. 'click', 'dblclick', 'mousewheel', 'wheel', 'mouseout',
  5807. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  5808. ];
  5809. var touchHandlerNames = [
  5810. 'touchstart', 'touchend', 'touchmove'
  5811. ];
  5812. var pointerEventNameMap = {
  5813. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  5814. };
  5815. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  5816. var nm = name.replace('mouse', 'pointer');
  5817. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  5818. });
  5819. return {
  5820. mouse: mouseHandlerNames,
  5821. touch: touchHandlerNames,
  5822. pointer: pointerHandlerNames
  5823. };
  5824. })();
  5825. var globalNativeListenerNames = {
  5826. mouse: ['mousemove', 'mouseup'],
  5827. pointer: ['pointermove', 'pointerup']
  5828. };
  5829. var wheelEventSupported = false;
  5830. function isPointerFromTouch(event) {
  5831. var pointerType = event.pointerType;
  5832. return pointerType === 'pen' || pointerType === 'touch';
  5833. }
  5834. function setTouchTimer(scope) {
  5835. scope.touching = true;
  5836. if (scope.touchTimer != null) {
  5837. clearTimeout(scope.touchTimer);
  5838. scope.touchTimer = null;
  5839. }
  5840. scope.touchTimer = setTimeout(function () {
  5841. scope.touching = false;
  5842. scope.touchTimer = null;
  5843. }, 700);
  5844. }
  5845. function markTouch(event) {
  5846. event && (event.zrByTouch = true);
  5847. }
  5848. function normalizeGlobalEvent(instance, event) {
  5849. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  5850. }
  5851. function isLocalEl(instance, el) {
  5852. var elTmp = el;
  5853. var isLocal = false;
  5854. while (elTmp && elTmp.nodeType !== 9
  5855. && !(isLocal = elTmp.domBelongToZr
  5856. || (elTmp !== el && elTmp === instance.painterRoot))) {
  5857. elTmp = elTmp.parentNode;
  5858. }
  5859. return isLocal;
  5860. }
  5861. var FakeGlobalEvent = (function () {
  5862. function FakeGlobalEvent(instance, event) {
  5863. this.stopPropagation = noop;
  5864. this.stopImmediatePropagation = noop;
  5865. this.preventDefault = noop;
  5866. this.type = event.type;
  5867. this.target = this.currentTarget = instance.dom;
  5868. this.pointerType = event.pointerType;
  5869. this.clientX = event.clientX;
  5870. this.clientY = event.clientY;
  5871. }
  5872. return FakeGlobalEvent;
  5873. }());
  5874. var localDOMHandlers = {
  5875. mousedown: function (event) {
  5876. event = normalizeEvent(this.dom, event);
  5877. this.__mayPointerCapture = [event.zrX, event.zrY];
  5878. this.trigger('mousedown', event);
  5879. },
  5880. mousemove: function (event) {
  5881. event = normalizeEvent(this.dom, event);
  5882. var downPoint = this.__mayPointerCapture;
  5883. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  5884. this.__togglePointerCapture(true);
  5885. }
  5886. this.trigger('mousemove', event);
  5887. },
  5888. mouseup: function (event) {
  5889. event = normalizeEvent(this.dom, event);
  5890. this.__togglePointerCapture(false);
  5891. this.trigger('mouseup', event);
  5892. },
  5893. mouseout: function (event) {
  5894. event = normalizeEvent(this.dom, event);
  5895. var element = event.toElement || event.relatedTarget;
  5896. if (!isLocalEl(this, element)) {
  5897. if (this.__pointerCapturing) {
  5898. event.zrEventControl = 'no_globalout';
  5899. }
  5900. this.trigger('mouseout', event);
  5901. }
  5902. },
  5903. wheel: function (event) {
  5904. wheelEventSupported = true;
  5905. event = normalizeEvent(this.dom, event);
  5906. this.trigger('mousewheel', event);
  5907. },
  5908. mousewheel: function (event) {
  5909. if (wheelEventSupported) {
  5910. return;
  5911. }
  5912. event = normalizeEvent(this.dom, event);
  5913. this.trigger('mousewheel', event);
  5914. },
  5915. touchstart: function (event) {
  5916. event = normalizeEvent(this.dom, event);
  5917. markTouch(event);
  5918. this.__lastTouchMoment = new Date();
  5919. this.handler.processGesture(event, 'start');
  5920. localDOMHandlers.mousemove.call(this, event);
  5921. localDOMHandlers.mousedown.call(this, event);
  5922. },
  5923. touchmove: function (event) {
  5924. event = normalizeEvent(this.dom, event);
  5925. markTouch(event);
  5926. this.handler.processGesture(event, 'change');
  5927. localDOMHandlers.mousemove.call(this, event);
  5928. },
  5929. touchend: function (event) {
  5930. event = normalizeEvent(this.dom, event);
  5931. markTouch(event);
  5932. this.handler.processGesture(event, 'end');
  5933. localDOMHandlers.mouseup.call(this, event);
  5934. if (+new Date() - (+this.__lastTouchMoment) < TOUCH_CLICK_DELAY) {
  5935. localDOMHandlers.click.call(this, event);
  5936. }
  5937. },
  5938. pointerdown: function (event) {
  5939. localDOMHandlers.mousedown.call(this, event);
  5940. },
  5941. pointermove: function (event) {
  5942. if (!isPointerFromTouch(event)) {
  5943. localDOMHandlers.mousemove.call(this, event);
  5944. }
  5945. },
  5946. pointerup: function (event) {
  5947. localDOMHandlers.mouseup.call(this, event);
  5948. },
  5949. pointerout: function (event) {
  5950. if (!isPointerFromTouch(event)) {
  5951. localDOMHandlers.mouseout.call(this, event);
  5952. }
  5953. }
  5954. };
  5955. each(['click', 'dblclick', 'contextmenu'], function (name) {
  5956. localDOMHandlers[name] = function (event) {
  5957. event = normalizeEvent(this.dom, event);
  5958. this.trigger(name, event);
  5959. };
  5960. });
  5961. var globalDOMHandlers = {
  5962. pointermove: function (event) {
  5963. if (!isPointerFromTouch(event)) {
  5964. globalDOMHandlers.mousemove.call(this, event);
  5965. }
  5966. },
  5967. pointerup: function (event) {
  5968. globalDOMHandlers.mouseup.call(this, event);
  5969. },
  5970. mousemove: function (event) {
  5971. this.trigger('mousemove', event);
  5972. },
  5973. mouseup: function (event) {
  5974. var pointerCaptureReleasing = this.__pointerCapturing;
  5975. this.__togglePointerCapture(false);
  5976. this.trigger('mouseup', event);
  5977. if (pointerCaptureReleasing) {
  5978. event.zrEventControl = 'only_globalout';
  5979. this.trigger('mouseout', event);
  5980. }
  5981. }
  5982. };
  5983. function mountLocalDOMEventListeners(instance, scope) {
  5984. var domHandlers = scope.domHandlers;
  5985. if (env.pointerEventsSupported) {
  5986. each(localNativeListenerNames.pointer, function (nativeEventName) {
  5987. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5988. domHandlers[nativeEventName].call(instance, event);
  5989. });
  5990. });
  5991. }
  5992. else {
  5993. if (env.touchEventsSupported) {
  5994. each(localNativeListenerNames.touch, function (nativeEventName) {
  5995. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  5996. domHandlers[nativeEventName].call(instance, event);
  5997. setTouchTimer(scope);
  5998. });
  5999. });
  6000. }
  6001. each(localNativeListenerNames.mouse, function (nativeEventName) {
  6002. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  6003. event = getNativeEvent(event);
  6004. if (!scope.touching) {
  6005. domHandlers[nativeEventName].call(instance, event);
  6006. }
  6007. });
  6008. });
  6009. }
  6010. }
  6011. function mountGlobalDOMEventListeners(instance, scope) {
  6012. if (env.pointerEventsSupported) {
  6013. each(globalNativeListenerNames.pointer, mount);
  6014. }
  6015. else if (!env.touchEventsSupported) {
  6016. each(globalNativeListenerNames.mouse, mount);
  6017. }
  6018. function mount(nativeEventName) {
  6019. function nativeEventListener(event) {
  6020. event = getNativeEvent(event);
  6021. if (!isLocalEl(instance, event.target)) {
  6022. event = normalizeGlobalEvent(instance, event);
  6023. scope.domHandlers[nativeEventName].call(instance, event);
  6024. }
  6025. }
  6026. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, { capture: true });
  6027. }
  6028. }
  6029. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  6030. scope.mounted[nativeEventName] = listener;
  6031. scope.listenerOpts[nativeEventName] = opt;
  6032. addEventListener(scope.domTarget, nativeEventName, listener, opt);
  6033. }
  6034. function unmountDOMEventListeners(scope) {
  6035. var mounted = scope.mounted;
  6036. for (var nativeEventName in mounted) {
  6037. if (mounted.hasOwnProperty(nativeEventName)) {
  6038. removeEventListener(scope.domTarget, nativeEventName, mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  6039. }
  6040. }
  6041. scope.mounted = {};
  6042. }
  6043. var DOMHandlerScope = (function () {
  6044. function DOMHandlerScope(domTarget, domHandlers) {
  6045. this.mounted = {};
  6046. this.listenerOpts = {};
  6047. this.touching = false;
  6048. this.domTarget = domTarget;
  6049. this.domHandlers = domHandlers;
  6050. }
  6051. return DOMHandlerScope;
  6052. }());
  6053. var HandlerDomProxy = (function (_super) {
  6054. __extends(HandlerDomProxy, _super);
  6055. function HandlerDomProxy(dom, painterRoot) {
  6056. var _this = _super.call(this) || this;
  6057. _this.__pointerCapturing = false;
  6058. _this.dom = dom;
  6059. _this.painterRoot = painterRoot;
  6060. _this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  6061. if (globalEventSupported) {
  6062. _this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  6063. }
  6064. mountLocalDOMEventListeners(_this, _this._localHandlerScope);
  6065. return _this;
  6066. }
  6067. HandlerDomProxy.prototype.dispose = function () {
  6068. unmountDOMEventListeners(this._localHandlerScope);
  6069. if (globalEventSupported) {
  6070. unmountDOMEventListeners(this._globalHandlerScope);
  6071. }
  6072. };
  6073. HandlerDomProxy.prototype.setCursor = function (cursorStyle) {
  6074. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  6075. };
  6076. HandlerDomProxy.prototype.__togglePointerCapture = function (isPointerCapturing) {
  6077. this.__mayPointerCapture = null;
  6078. if (globalEventSupported
  6079. && ((+this.__pointerCapturing) ^ (+isPointerCapturing))) {
  6080. this.__pointerCapturing = isPointerCapturing;
  6081. var globalHandlerScope = this._globalHandlerScope;
  6082. isPointerCapturing
  6083. ? mountGlobalDOMEventListeners(this, globalHandlerScope)
  6084. : unmountDOMEventListeners(globalHandlerScope);
  6085. }
  6086. };
  6087. return HandlerDomProxy;
  6088. }(Eventful));
  6089. var Group = (function (_super) {
  6090. __extends(Group, _super);
  6091. function Group(opts) {
  6092. var _this = _super.call(this) || this;
  6093. _this.isGroup = true;
  6094. _this._children = [];
  6095. _this.attr(opts);
  6096. return _this;
  6097. }
  6098. Group.prototype.childrenRef = function () {
  6099. return this._children;
  6100. };
  6101. Group.prototype.children = function () {
  6102. return this._children.slice();
  6103. };
  6104. Group.prototype.childAt = function (idx) {
  6105. return this._children[idx];
  6106. };
  6107. Group.prototype.childOfName = function (name) {
  6108. var children = this._children;
  6109. for (var i = 0; i < children.length; i++) {
  6110. if (children[i].name === name) {
  6111. return children[i];
  6112. }
  6113. }
  6114. };
  6115. Group.prototype.childCount = function () {
  6116. return this._children.length;
  6117. };
  6118. Group.prototype.add = function (child) {
  6119. if (child) {
  6120. if (child !== this && child.parent !== this) {
  6121. this._children.push(child);
  6122. this._doAdd(child);
  6123. }
  6124. if (child.__hostTarget) {
  6125. throw 'This elemenet has been used as an attachment';
  6126. }
  6127. }
  6128. return this;
  6129. };
  6130. Group.prototype.addBefore = function (child, nextSibling) {
  6131. if (child && child !== this && child.parent !== this
  6132. && nextSibling && nextSibling.parent === this) {
  6133. var children = this._children;
  6134. var idx = children.indexOf(nextSibling);
  6135. if (idx >= 0) {
  6136. children.splice(idx, 0, child);
  6137. this._doAdd(child);
  6138. }
  6139. }
  6140. return this;
  6141. };
  6142. Group.prototype.replaceAt = function (child, index) {
  6143. var children = this._children;
  6144. var old = children[index];
  6145. if (child && child !== this && child.parent !== this && child !== old) {
  6146. children[index] = child;
  6147. old.parent = null;
  6148. var zr = this.__zr;
  6149. if (zr) {
  6150. old.removeSelfFromZr(zr);
  6151. }
  6152. this._doAdd(child);
  6153. }
  6154. return this;
  6155. };
  6156. Group.prototype._doAdd = function (child) {
  6157. if (child.parent) {
  6158. child.parent.remove(child);
  6159. }
  6160. child.parent = this;
  6161. var zr = this.__zr;
  6162. if (zr && zr !== child.__zr) {
  6163. child.addSelfToZr(zr);
  6164. }
  6165. zr && zr.refresh();
  6166. };
  6167. Group.prototype.remove = function (child) {
  6168. var zr = this.__zr;
  6169. var children = this._children;
  6170. var idx = indexOf(children, child);
  6171. if (idx < 0) {
  6172. return this;
  6173. }
  6174. children.splice(idx, 1);
  6175. child.parent = null;
  6176. if (zr) {
  6177. child.removeSelfFromZr(zr);
  6178. }
  6179. zr && zr.refresh();
  6180. return this;
  6181. };
  6182. Group.prototype.removeAll = function () {
  6183. var children = this._children;
  6184. var zr = this.__zr;
  6185. for (var i = 0; i < children.length; i++) {
  6186. var child = children[i];
  6187. if (zr) {
  6188. child.removeSelfFromZr(zr);
  6189. }
  6190. child.parent = null;
  6191. }
  6192. children.length = 0;
  6193. return this;
  6194. };
  6195. Group.prototype.eachChild = function (cb, context) {
  6196. var children = this._children;
  6197. for (var i = 0; i < children.length; i++) {
  6198. var child = children[i];
  6199. cb.call(context, child, i);
  6200. }
  6201. return this;
  6202. };
  6203. Group.prototype.traverse = function (cb, context) {
  6204. for (var i = 0; i < this._children.length; i++) {
  6205. var child = this._children[i];
  6206. var stopped = cb.call(context, child);
  6207. if (child.isGroup && !stopped) {
  6208. child.traverse(cb, context);
  6209. }
  6210. }
  6211. return this;
  6212. };
  6213. Group.prototype.addSelfToZr = function (zr) {
  6214. _super.prototype.addSelfToZr.call(this, zr);
  6215. for (var i = 0; i < this._children.length; i++) {
  6216. var child = this._children[i];
  6217. child.addSelfToZr(zr);
  6218. }
  6219. };
  6220. Group.prototype.removeSelfFromZr = function (zr) {
  6221. _super.prototype.removeSelfFromZr.call(this, zr);
  6222. for (var i = 0; i < this._children.length; i++) {
  6223. var child = this._children[i];
  6224. child.removeSelfFromZr(zr);
  6225. }
  6226. };
  6227. Group.prototype.getBoundingRect = function (includeChildren) {
  6228. var tmpRect = new BoundingRect(0, 0, 0, 0);
  6229. var children = includeChildren || this._children;
  6230. var tmpMat = [];
  6231. var rect = null;
  6232. for (var i = 0; i < children.length; i++) {
  6233. var child = children[i];
  6234. if (child.ignore || child.invisible) {
  6235. continue;
  6236. }
  6237. var childRect = child.getBoundingRect();
  6238. var transform = child.getLocalTransform(tmpMat);
  6239. if (transform) {
  6240. BoundingRect.applyTransform(tmpRect, childRect, transform);
  6241. rect = rect || tmpRect.clone();
  6242. rect.union(tmpRect);
  6243. }
  6244. else {
  6245. rect = rect || childRect.clone();
  6246. rect.union(childRect);
  6247. }
  6248. }
  6249. return rect || tmpRect;
  6250. };
  6251. return Group;
  6252. }(Element));
  6253. Group.prototype.type = 'group';
  6254. /*!
  6255. * ZRender, a high performance 2d drawing library.
  6256. *
  6257. * Copyright (c) 2013, Baidu Inc.
  6258. * All rights reserved.
  6259. *
  6260. * LICENSE
  6261. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  6262. */
  6263. var useVML = !env.canvasSupported;
  6264. var painterCtors = {};
  6265. var instances = {};
  6266. function delInstance(id) {
  6267. delete instances[id];
  6268. }
  6269. function isDarkMode(backgroundColor) {
  6270. if (!backgroundColor) {
  6271. return false;
  6272. }
  6273. if (typeof backgroundColor === 'string') {
  6274. return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
  6275. }
  6276. else if (backgroundColor.colorStops) {
  6277. var colorStops = backgroundColor.colorStops;
  6278. var totalLum = 0;
  6279. var len = colorStops.length;
  6280. for (var i = 0; i < len; i++) {
  6281. totalLum += lum(colorStops[i].color, 1);
  6282. }
  6283. totalLum /= len;
  6284. return totalLum < DARK_MODE_THRESHOLD;
  6285. }
  6286. return false;
  6287. }
  6288. var ZRender = (function () {
  6289. function ZRender(id, dom, opts) {
  6290. var _this = this;
  6291. this._sleepAfterStill = 10;
  6292. this._stillFrameAccum = 0;
  6293. this._needsRefresh = true;
  6294. this._needsRefreshHover = true;
  6295. this._darkMode = false;
  6296. opts = opts || {};
  6297. this.dom = dom;
  6298. this.id = id;
  6299. var storage = new Storage();
  6300. var rendererType = opts.renderer || 'canvas';
  6301. if (useVML) {
  6302. throw new Error('IE8 support has been dropped since 5.0');
  6303. }
  6304. if (!painterCtors[rendererType]) {
  6305. rendererType = keys(painterCtors)[0];
  6306. }
  6307. if (!painterCtors[rendererType]) {
  6308. throw new Error("Renderer '" + rendererType + "' is not imported. Please import it first.");
  6309. }
  6310. opts.useDirtyRect = opts.useDirtyRect == null
  6311. ? false
  6312. : opts.useDirtyRect;
  6313. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  6314. this.storage = storage;
  6315. this.painter = painter;
  6316. var handerProxy = (!env.node && !env.worker)
  6317. ? new HandlerDomProxy(painter.getViewportRoot(), painter.root)
  6318. : null;
  6319. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  6320. this.animation = new Animation({
  6321. stage: {
  6322. update: function () { return _this._flush(true); }
  6323. }
  6324. });
  6325. this.animation.start();
  6326. }
  6327. ZRender.prototype.add = function (el) {
  6328. if (!el) {
  6329. return;
  6330. }
  6331. this.storage.addRoot(el);
  6332. el.addSelfToZr(this);
  6333. this.refresh();
  6334. };
  6335. ZRender.prototype.remove = function (el) {
  6336. if (!el) {
  6337. return;
  6338. }
  6339. this.storage.delRoot(el);
  6340. el.removeSelfFromZr(this);
  6341. this.refresh();
  6342. };
  6343. ZRender.prototype.configLayer = function (zLevel, config) {
  6344. if (this.painter.configLayer) {
  6345. this.painter.configLayer(zLevel, config);
  6346. }
  6347. this.refresh();
  6348. };
  6349. ZRender.prototype.setBackgroundColor = function (backgroundColor) {
  6350. if (this.painter.setBackgroundColor) {
  6351. this.painter.setBackgroundColor(backgroundColor);
  6352. }
  6353. this.refresh();
  6354. this._backgroundColor = backgroundColor;
  6355. this._darkMode = isDarkMode(backgroundColor);
  6356. };
  6357. ZRender.prototype.getBackgroundColor = function () {
  6358. return this._backgroundColor;
  6359. };
  6360. ZRender.prototype.setDarkMode = function (darkMode) {
  6361. this._darkMode = darkMode;
  6362. };
  6363. ZRender.prototype.isDarkMode = function () {
  6364. return this._darkMode;
  6365. };
  6366. ZRender.prototype.refreshImmediately = function (fromInside) {
  6367. if (!fromInside) {
  6368. this.animation.update(true);
  6369. }
  6370. this._needsRefresh = false;
  6371. this.painter.refresh();
  6372. this._needsRefresh = false;
  6373. };
  6374. ZRender.prototype.refresh = function () {
  6375. this._needsRefresh = true;
  6376. this.animation.start();
  6377. };
  6378. ZRender.prototype.flush = function () {
  6379. this._flush(false);
  6380. };
  6381. ZRender.prototype._flush = function (fromInside) {
  6382. var triggerRendered;
  6383. var start = new Date().getTime();
  6384. if (this._needsRefresh) {
  6385. triggerRendered = true;
  6386. this.refreshImmediately(fromInside);
  6387. }
  6388. if (this._needsRefreshHover) {
  6389. triggerRendered = true;
  6390. this.refreshHoverImmediately();
  6391. }
  6392. var end = new Date().getTime();
  6393. if (triggerRendered) {
  6394. this._stillFrameAccum = 0;
  6395. this.trigger('rendered', {
  6396. elapsedTime: end - start
  6397. });
  6398. }
  6399. else if (this._sleepAfterStill > 0) {
  6400. this._stillFrameAccum++;
  6401. if (this._stillFrameAccum > this._sleepAfterStill) {
  6402. this.animation.stop();
  6403. }
  6404. }
  6405. };
  6406. ZRender.prototype.setSleepAfterStill = function (stillFramesCount) {
  6407. this._sleepAfterStill = stillFramesCount;
  6408. };
  6409. ZRender.prototype.wakeUp = function () {
  6410. this.animation.start();
  6411. this._stillFrameAccum = 0;
  6412. };
  6413. ZRender.prototype.addHover = function (el) {
  6414. };
  6415. ZRender.prototype.removeHover = function (el) {
  6416. };
  6417. ZRender.prototype.clearHover = function () {
  6418. };
  6419. ZRender.prototype.refreshHover = function () {
  6420. this._needsRefreshHover = true;
  6421. };
  6422. ZRender.prototype.refreshHoverImmediately = function () {
  6423. this._needsRefreshHover = false;
  6424. if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
  6425. this.painter.refreshHover();
  6426. }
  6427. };
  6428. ZRender.prototype.resize = function (opts) {
  6429. opts = opts || {};
  6430. this.painter.resize(opts.width, opts.height);
  6431. this.handler.resize();
  6432. };
  6433. ZRender.prototype.clearAnimation = function () {
  6434. this.animation.clear();
  6435. };
  6436. ZRender.prototype.getWidth = function () {
  6437. return this.painter.getWidth();
  6438. };
  6439. ZRender.prototype.getHeight = function () {
  6440. return this.painter.getHeight();
  6441. };
  6442. ZRender.prototype.pathToImage = function (e, dpr) {
  6443. if (this.painter.pathToImage) {
  6444. return this.painter.pathToImage(e, dpr);
  6445. }
  6446. };
  6447. ZRender.prototype.setCursorStyle = function (cursorStyle) {
  6448. this.handler.setCursorStyle(cursorStyle);
  6449. };
  6450. ZRender.prototype.findHover = function (x, y) {
  6451. return this.handler.findHover(x, y);
  6452. };
  6453. ZRender.prototype.on = function (eventName, eventHandler, context) {
  6454. this.handler.on(eventName, eventHandler, context);
  6455. return this;
  6456. };
  6457. ZRender.prototype.off = function (eventName, eventHandler) {
  6458. this.handler.off(eventName, eventHandler);
  6459. };
  6460. ZRender.prototype.trigger = function (eventName, event) {
  6461. this.handler.trigger(eventName, event);
  6462. };
  6463. ZRender.prototype.clear = function () {
  6464. var roots = this.storage.getRoots();
  6465. for (var i = 0; i < roots.length; i++) {
  6466. if (roots[i] instanceof Group) {
  6467. roots[i].removeSelfFromZr(this);
  6468. }
  6469. }
  6470. this.storage.delAllRoots();
  6471. this.painter.clear();
  6472. };
  6473. ZRender.prototype.dispose = function () {
  6474. this.animation.stop();
  6475. this.clear();
  6476. this.storage.dispose();
  6477. this.painter.dispose();
  6478. this.handler.dispose();
  6479. this.animation =
  6480. this.storage =
  6481. this.painter =
  6482. this.handler = null;
  6483. delInstance(this.id);
  6484. };
  6485. return ZRender;
  6486. }());
  6487. function init(dom, opts) {
  6488. var zr = new ZRender(guid(), dom, opts);
  6489. instances[zr.id] = zr;
  6490. return zr;
  6491. }
  6492. function dispose(zr) {
  6493. zr.dispose();
  6494. }
  6495. function disposeAll() {
  6496. for (var key in instances) {
  6497. if (instances.hasOwnProperty(key)) {
  6498. instances[key].dispose();
  6499. }
  6500. }
  6501. instances = {};
  6502. }
  6503. function getInstance(id) {
  6504. return instances[id];
  6505. }
  6506. function registerPainter(name, Ctor) {
  6507. painterCtors[name] = Ctor;
  6508. }
  6509. var version = '5.0.4';
  6510. var zrender = /*#__PURE__*/Object.freeze({
  6511. __proto__: null,
  6512. init: init,
  6513. dispose: dispose,
  6514. disposeAll: disposeAll,
  6515. getInstance: getInstance,
  6516. registerPainter: registerPainter,
  6517. version: version
  6518. });
  6519. var RADIAN_EPSILON = 1e-4;
  6520. function _trim(str) {
  6521. return str.replace(/^\s+|\s+$/g, '');
  6522. }
  6523. /**
  6524. * Linear mapping a value from domain to range
  6525. * @param val
  6526. * @param domain Domain extent domain[0] can be bigger than domain[1]
  6527. * @param range Range extent range[0] can be bigger than range[1]
  6528. * @param clamp Default to be false
  6529. */
  6530. function linearMap(val, domain, range, clamp) {
  6531. var subDomain = domain[1] - domain[0];
  6532. var subRange = range[1] - range[0];
  6533. if (subDomain === 0) {
  6534. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  6535. } // Avoid accuracy problem in edge, such as
  6536. // 146.39 - 62.83 === 83.55999999999999.
  6537. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  6538. // It is a little verbose for efficiency considering this method
  6539. // is a hotspot.
  6540. if (clamp) {
  6541. if (subDomain > 0) {
  6542. if (val <= domain[0]) {
  6543. return range[0];
  6544. } else if (val >= domain[1]) {
  6545. return range[1];
  6546. }
  6547. } else {
  6548. if (val >= domain[0]) {
  6549. return range[0];
  6550. } else if (val <= domain[1]) {
  6551. return range[1];
  6552. }
  6553. }
  6554. } else {
  6555. if (val === domain[0]) {
  6556. return range[0];
  6557. }
  6558. if (val === domain[1]) {
  6559. return range[1];
  6560. }
  6561. }
  6562. return (val - domain[0]) / subDomain * subRange + range[0];
  6563. }
  6564. /**
  6565. * Convert a percent string to absolute number.
  6566. * Returns NaN if percent is not a valid string or number
  6567. */
  6568. function parsePercent$1(percent, all) {
  6569. switch (percent) {
  6570. case 'center':
  6571. case 'middle':
  6572. percent = '50%';
  6573. break;
  6574. case 'left':
  6575. case 'top':
  6576. percent = '0%';
  6577. break;
  6578. case 'right':
  6579. case 'bottom':
  6580. percent = '100%';
  6581. break;
  6582. }
  6583. if (typeof percent === 'string') {
  6584. if (_trim(percent).match(/%$/)) {
  6585. return parseFloat(percent) / 100 * all;
  6586. }
  6587. return parseFloat(percent);
  6588. }
  6589. return percent == null ? NaN : +percent;
  6590. }
  6591. function round(x, precision, returnStr) {
  6592. if (precision == null) {
  6593. precision = 10;
  6594. } // Avoid range error
  6595. precision = Math.min(Math.max(0, precision), 20);
  6596. x = (+x).toFixed(precision);
  6597. return returnStr ? x : +x;
  6598. }
  6599. /**
  6600. * Inplacd asc sort arr.
  6601. * The input arr will be modified.
  6602. */
  6603. function asc(arr) {
  6604. arr.sort(function (a, b) {
  6605. return a - b;
  6606. });
  6607. return arr;
  6608. }
  6609. /**
  6610. * Get precision
  6611. */
  6612. function getPrecision(val) {
  6613. val = +val;
  6614. if (isNaN(val)) {
  6615. return 0;
  6616. } // It is much faster than methods converting number to string as follows
  6617. // let tmp = val.toString();
  6618. // return tmp.length - 1 - tmp.indexOf('.');
  6619. // especially when precision is low
  6620. var e = 1;
  6621. var count = 0;
  6622. while (Math.round(val * e) / e !== val) {
  6623. e *= 10;
  6624. count++;
  6625. }
  6626. return count;
  6627. }
  6628. /**
  6629. * Get precision with slow but safe method
  6630. */
  6631. function getPrecisionSafe(val) {
  6632. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  6633. var eIndex = str.indexOf('e');
  6634. if (eIndex > 0) {
  6635. var precision = +str.slice(eIndex + 1);
  6636. return precision < 0 ? -precision : 0;
  6637. } else {
  6638. var dotIndex = str.indexOf('.');
  6639. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  6640. }
  6641. }
  6642. /**
  6643. * Minimal dicernible data precisioin according to a single pixel.
  6644. */
  6645. function getPixelPrecision(dataExtent, pixelExtent) {
  6646. var log = Math.log;
  6647. var LN10 = Math.LN10;
  6648. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  6649. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  6650. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  6651. return !isFinite(precision) ? 20 : precision;
  6652. }
  6653. /**
  6654. * Get a data of given precision, assuring the sum of percentages
  6655. * in valueList is 1.
  6656. * The largest remainer method is used.
  6657. * https://en.wikipedia.org/wiki/Largest_remainder_method
  6658. *
  6659. * @param valueList a list of all data
  6660. * @param idx index of the data to be processed in valueList
  6661. * @param precision integer number showing digits of precision
  6662. * @return percent ranging from 0 to 100
  6663. */
  6664. function getPercentWithPrecision(valueList, idx, precision) {
  6665. if (!valueList[idx]) {
  6666. return 0;
  6667. }
  6668. var sum = reduce(valueList, function (acc, val) {
  6669. return acc + (isNaN(val) ? 0 : val);
  6670. }, 0);
  6671. if (sum === 0) {
  6672. return 0;
  6673. }
  6674. var digits = Math.pow(10, precision);
  6675. var votesPerQuota = map(valueList, function (val) {
  6676. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  6677. });
  6678. var targetSeats = digits * 100;
  6679. var seats = map(votesPerQuota, function (votes) {
  6680. // Assign automatic seats.
  6681. return Math.floor(votes);
  6682. });
  6683. var currentSum = reduce(seats, function (acc, val) {
  6684. return acc + val;
  6685. }, 0);
  6686. var remainder = map(votesPerQuota, function (votes, idx) {
  6687. return votes - seats[idx];
  6688. }); // Has remainding votes.
  6689. while (currentSum < targetSeats) {
  6690. // Find next largest remainder.
  6691. var max = Number.NEGATIVE_INFINITY;
  6692. var maxId = null;
  6693. for (var i = 0, len = remainder.length; i < len; ++i) {
  6694. if (remainder[i] > max) {
  6695. max = remainder[i];
  6696. maxId = i;
  6697. }
  6698. } // Add a vote to max remainder.
  6699. ++seats[maxId];
  6700. remainder[maxId] = 0;
  6701. ++currentSum;
  6702. }
  6703. return seats[idx] / digits;
  6704. } // Number.MAX_SAFE_INTEGER, ie do not support.
  6705. var MAX_SAFE_INTEGER = 9007199254740991;
  6706. /**
  6707. * To 0 - 2 * PI, considering negative radian.
  6708. */
  6709. function remRadian(radian) {
  6710. var pi2 = Math.PI * 2;
  6711. return (radian % pi2 + pi2) % pi2;
  6712. }
  6713. /**
  6714. * @param {type} radian
  6715. * @return {boolean}
  6716. */
  6717. function isRadianAroundZero(val) {
  6718. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  6719. } // eslint-disable-next-line
  6720. 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
  6721. /**
  6722. * @param value valid type: number | string | Date, otherwise return `new Date(NaN)`
  6723. * These values can be accepted:
  6724. * + An instance of Date, represent a time in its own time zone.
  6725. * + Or string in a subset of ISO 8601, only including:
  6726. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  6727. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  6728. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  6729. * all of which will be treated as local time if time zone is not specified
  6730. * (see <https://momentjs.com/>).
  6731. * + Or other string format, including (all of which will be treated as loacal time):
  6732. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  6733. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  6734. * + a timestamp, which represent a time in UTC.
  6735. * @return date Never be null/undefined. If invalid, return `new Date(NaN)`.
  6736. */
  6737. function parseDate(value) {
  6738. if (value instanceof Date) {
  6739. return value;
  6740. } else if (typeof value === 'string') {
  6741. // Different browsers parse date in different way, so we parse it manually.
  6742. // Some other issues:
  6743. // new Date('1970-01-01') is UTC,
  6744. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  6745. // See issue #3623
  6746. var match = TIME_REG.exec(value);
  6747. if (!match) {
  6748. // return Invalid Date.
  6749. return new Date(NaN);
  6750. } // Use local time when no timezone offset specifed.
  6751. if (!match[8]) {
  6752. // match[n] can only be string or undefined.
  6753. // But take care of '12' + 1 => '121'.
  6754. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  6755. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  6756. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  6757. // For example, system timezone is set as "Time Zone: America/Toronto",
  6758. // then these code will get different result:
  6759. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  6760. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  6761. // So we should not use `new Date`, but use `Date.UTC`.
  6762. else {
  6763. var hour = +match[4] || 0;
  6764. if (match[8].toUpperCase() !== 'Z') {
  6765. hour -= +match[8].slice(0, 3);
  6766. }
  6767. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  6768. }
  6769. } else if (value == null) {
  6770. return new Date(NaN);
  6771. }
  6772. return new Date(Math.round(value));
  6773. }
  6774. /**
  6775. * Quantity of a number. e.g. 0.1, 1, 10, 100
  6776. *
  6777. * @param val
  6778. * @return
  6779. */
  6780. function quantity(val) {
  6781. return Math.pow(10, quantityExponent(val));
  6782. }
  6783. /**
  6784. * Exponent of the quantity of a number
  6785. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  6786. *
  6787. * @param val non-negative value
  6788. * @return
  6789. */
  6790. function quantityExponent(val) {
  6791. if (val === 0) {
  6792. return 0;
  6793. }
  6794. var exp = Math.floor(Math.log(val) / Math.LN10);
  6795. /**
  6796. * exp is expected to be the rounded-down result of the base-10 log of val.
  6797. * But due to the precision loss with Math.log(val), we need to restore it
  6798. * using 10^exp to make sure we can get val back from exp. #11249
  6799. */
  6800. if (val / Math.pow(10, exp) >= 10) {
  6801. exp++;
  6802. }
  6803. return exp;
  6804. }
  6805. /**
  6806. * find a “nice” number approximately equal to x. Round the number if round = true,
  6807. * take ceiling if round = false. The primary observation is that the “nicest”
  6808. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  6809. *
  6810. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  6811. *
  6812. * @param val Non-negative value.
  6813. * @param round
  6814. * @return Niced number
  6815. */
  6816. function nice(val, round) {
  6817. var exponent = quantityExponent(val);
  6818. var exp10 = Math.pow(10, exponent);
  6819. var f = val / exp10; // 1 <= f < 10
  6820. var nf;
  6821. if (round) {
  6822. if (f < 1.5) {
  6823. nf = 1;
  6824. } else if (f < 2.5) {
  6825. nf = 2;
  6826. } else if (f < 4) {
  6827. nf = 3;
  6828. } else if (f < 7) {
  6829. nf = 5;
  6830. } else {
  6831. nf = 10;
  6832. }
  6833. } else {
  6834. if (f < 1) {
  6835. nf = 1;
  6836. } else if (f < 2) {
  6837. nf = 2;
  6838. } else if (f < 3) {
  6839. nf = 3;
  6840. } else if (f < 5) {
  6841. nf = 5;
  6842. } else {
  6843. nf = 10;
  6844. }
  6845. }
  6846. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  6847. // 20 is the uppper bound of toFixed.
  6848. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  6849. }
  6850. /**
  6851. * This code was copied from "d3.js"
  6852. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  6853. * See the license statement at the head of this file.
  6854. * @param ascArr
  6855. */
  6856. function quantile(ascArr, p) {
  6857. var H = (ascArr.length - 1) * p + 1;
  6858. var h = Math.floor(H);
  6859. var v = +ascArr[h - 1];
  6860. var e = H - h;
  6861. return e ? v + e * (ascArr[h] - v) : v;
  6862. }
  6863. /**
  6864. * Order intervals asc, and split them when overlap.
  6865. * expect(numberUtil.reformIntervals([
  6866. * {interval: [18, 62], close: [1, 1]},
  6867. * {interval: [-Infinity, -70], close: [0, 0]},
  6868. * {interval: [-70, -26], close: [1, 1]},
  6869. * {interval: [-26, 18], close: [1, 1]},
  6870. * {interval: [62, 150], close: [1, 1]},
  6871. * {interval: [106, 150], close: [1, 1]},
  6872. * {interval: [150, Infinity], close: [0, 0]}
  6873. * ])).toEqual([
  6874. * {interval: [-Infinity, -70], close: [0, 0]},
  6875. * {interval: [-70, -26], close: [1, 1]},
  6876. * {interval: [-26, 18], close: [0, 1]},
  6877. * {interval: [18, 62], close: [0, 1]},
  6878. * {interval: [62, 150], close: [0, 1]},
  6879. * {interval: [150, Infinity], close: [0, 0]}
  6880. * ]);
  6881. * @param list, where `close` mean open or close
  6882. * of the interval, and Infinity can be used.
  6883. * @return The origin list, which has been reformed.
  6884. */
  6885. function reformIntervals(list) {
  6886. list.sort(function (a, b) {
  6887. return littleThan(a, b, 0) ? -1 : 1;
  6888. });
  6889. var curr = -Infinity;
  6890. var currClose = 1;
  6891. for (var i = 0; i < list.length;) {
  6892. var interval = list[i].interval;
  6893. var close_1 = list[i].close;
  6894. for (var lg = 0; lg < 2; lg++) {
  6895. if (interval[lg] <= curr) {
  6896. interval[lg] = curr;
  6897. close_1[lg] = !lg ? 1 - currClose : 1;
  6898. }
  6899. curr = interval[lg];
  6900. currClose = close_1[lg];
  6901. }
  6902. if (interval[0] === interval[1] && close_1[0] * close_1[1] !== 1) {
  6903. list.splice(i, 1);
  6904. } else {
  6905. i++;
  6906. }
  6907. }
  6908. return list;
  6909. function littleThan(a, b, lg) {
  6910. 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));
  6911. }
  6912. }
  6913. /**
  6914. * [Numberic is defined as]:
  6915. * `parseFloat(val) == val`
  6916. * For example:
  6917. * numeric:
  6918. * typeof number except NaN, '-123', '123', '2e3', '-2e3', '011', 'Infinity', Infinity,
  6919. * and they rounded by white-spaces or line-terminal like ' -123 \n ' (see es spec)
  6920. * not-numeric:
  6921. * null, undefined, [], {}, true, false, 'NaN', NaN, '123ab',
  6922. * empty string, string with only white-spaces or line-terminal (see es spec),
  6923. * 0x12, '0x12', '-0x12', 012, '012', '-012',
  6924. * non-string, ...
  6925. *
  6926. * @test See full test cases in `test/ut/spec/util/number.js`.
  6927. * @return Must be a typeof number. If not numeric, return NaN.
  6928. */
  6929. function numericToNumber(val) {
  6930. var valFloat = parseFloat(val);
  6931. return valFloat == val // eslint-disable-line eqeqeq
  6932. && (valFloat !== 0 || typeof val !== 'string' || val.indexOf('x') <= 0) // For case ' 0x0 '.
  6933. ? valFloat : NaN;
  6934. }
  6935. /**
  6936. * Definition of "numeric": see `numericToNumber`.
  6937. */
  6938. function isNumeric(val) {
  6939. return !isNaN(numericToNumber(val));
  6940. }
  6941. /**
  6942. * Use random base to prevent users hard code depending on
  6943. * this auto generated marker id.
  6944. * @return An positive integer.
  6945. */
  6946. function getRandomIdBase() {
  6947. return Math.round(Math.random() * 9);
  6948. }
  6949. /**
  6950. * Get the greatest common dividor
  6951. *
  6952. * @param {number} a one number
  6953. * @param {number} b the other number
  6954. */
  6955. function getGreatestCommonDividor(a, b) {
  6956. if (b === 0) {
  6957. return a;
  6958. }
  6959. return getGreatestCommonDividor(b, a % b);
  6960. }
  6961. /**
  6962. * Get the least common multiple
  6963. *
  6964. * @param {number} a one number
  6965. * @param {number} b the other number
  6966. */
  6967. function getLeastCommonMultiple(a, b) {
  6968. if (a == null) {
  6969. return b;
  6970. }
  6971. if (b == null) {
  6972. return a;
  6973. }
  6974. return a * b / getGreatestCommonDividor(a, b);
  6975. }
  6976. var ECHARTS_PREFIX = '[ECharts] ';
  6977. var storedLogs = {};
  6978. var hasConsole = typeof console !== 'undefined' // eslint-disable-next-line
  6979. && console.warn && console.log;
  6980. function warn(str) {
  6981. if (hasConsole) {
  6982. console.warn(ECHARTS_PREFIX + str);
  6983. }
  6984. }
  6985. function error(str) {
  6986. if (hasConsole) {
  6987. console.error(ECHARTS_PREFIX + str);
  6988. }
  6989. }
  6990. function deprecateLog(str) {
  6991. if ("development" !== 'production') {
  6992. if (storedLogs[str]) {
  6993. // Not display duplicate message.
  6994. return;
  6995. }
  6996. if (hasConsole) {
  6997. storedLogs[str] = true;
  6998. console.warn(ECHARTS_PREFIX + 'DEPRECATED: ' + str);
  6999. }
  7000. }
  7001. }
  7002. function deprecateReplaceLog(oldOpt, newOpt, scope) {
  7003. if ("development" !== 'production') {
  7004. deprecateLog((scope ? "[" + scope + "]" : '') + (oldOpt + " is deprecated, use " + newOpt + " instead."));
  7005. }
  7006. }
  7007. function consoleLog() {
  7008. var args = [];
  7009. for (var _i = 0; _i < arguments.length; _i++) {
  7010. args[_i] = arguments[_i];
  7011. }
  7012. if ("development" !== 'production') {
  7013. /* eslint-disable no-console */
  7014. if (typeof console !== 'undefined' && console.log) {
  7015. console.log.apply(console, args);
  7016. }
  7017. /* eslint-enable no-console */
  7018. }
  7019. }
  7020. /**
  7021. * If in __DEV__ environment, get console printable message for users hint.
  7022. * Parameters are separated by ' '.
  7023. * @usuage
  7024. * makePrintable('This is an error on', someVar, someObj);
  7025. *
  7026. * @param hintInfo anything about the current execution context to hint users.
  7027. * @throws Error
  7028. */
  7029. function makePrintable() {
  7030. var hintInfo = [];
  7031. for (var _i = 0; _i < arguments.length; _i++) {
  7032. hintInfo[_i] = arguments[_i];
  7033. }
  7034. var msg = '';
  7035. if ("development" !== 'production') {
  7036. // Fuzzy stringify for print.
  7037. // This code only exist in dev environment.
  7038. var makePrintableStringIfPossible_1 = function (val) {
  7039. 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;
  7040. };
  7041. msg = map(hintInfo, function (arg) {
  7042. if (isString(arg)) {
  7043. // Print without quotation mark for some statement.
  7044. return arg;
  7045. } else {
  7046. var printableStr = makePrintableStringIfPossible_1(arg);
  7047. if (printableStr != null) {
  7048. return printableStr;
  7049. } else if (typeof JSON !== 'undefined' && JSON.stringify) {
  7050. try {
  7051. return JSON.stringify(arg, function (n, val) {
  7052. var printableStr = makePrintableStringIfPossible_1(val);
  7053. return printableStr == null ? val : printableStr;
  7054. }); // In most cases the info object is small, so do not line break.
  7055. } catch (err) {
  7056. return '?';
  7057. }
  7058. } else {
  7059. return '?';
  7060. }
  7061. }
  7062. }).join(' ');
  7063. }
  7064. return msg;
  7065. }
  7066. /**
  7067. * @throws Error
  7068. */
  7069. function throwError(msg) {
  7070. throw new Error(msg);
  7071. }
  7072. /**
  7073. * Make the name displayable. But we should
  7074. * make sure it is not duplicated with user
  7075. * specified name, so use '\0';
  7076. */
  7077. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  7078. var INTERNAL_COMPONENT_ID_PREFIX = '\0_ec_\0';
  7079. /**
  7080. * If value is not array, then translate it to array.
  7081. * @param {*} value
  7082. * @return {Array} [value] or value
  7083. */
  7084. function normalizeToArray(value) {
  7085. return value instanceof Array ? value : value == null ? [] : [value];
  7086. }
  7087. /**
  7088. * Sync default option between normal and emphasis like `position` and `show`
  7089. * In case some one will write code like
  7090. * label: {
  7091. * show: false,
  7092. * position: 'outside',
  7093. * fontSize: 18
  7094. * },
  7095. * emphasis: {
  7096. * label: { show: true }
  7097. * }
  7098. */
  7099. function defaultEmphasis(opt, key, subOpts) {
  7100. // Caution: performance sensitive.
  7101. if (opt) {
  7102. opt[key] = opt[key] || {};
  7103. opt.emphasis = opt.emphasis || {};
  7104. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  7105. for (var i = 0, len = subOpts.length; i < len; i++) {
  7106. var subOptName = subOpts[i];
  7107. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  7108. opt.emphasis[key][subOptName] = opt[key][subOptName];
  7109. }
  7110. }
  7111. }
  7112. }
  7113. 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([
  7114. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  7115. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  7116. // // FIXME: deprecated, check and remove it.
  7117. // 'textStyle'
  7118. // ]);
  7119. /**
  7120. * The method do not ensure performance.
  7121. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7122. * This helper method retieves value from data.
  7123. */
  7124. function getDataItemValue(dataItem) {
  7125. return isObject(dataItem) && !isArray(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  7126. }
  7127. /**
  7128. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  7129. * This helper method determine if dataItem has extra option besides value
  7130. */
  7131. function isDataItemOption(dataItem) {
  7132. return isObject(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  7133. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  7134. }
  7135. /**
  7136. * Mapping to existings for merge.
  7137. *
  7138. * Mode "normalMege":
  7139. * The mapping result (merge result) will keep the order of the existing
  7140. * component, rather than the order of new option. Because we should ensure
  7141. * some specified index reference (like xAxisIndex) keep work.
  7142. * And in most cases, "merge option" is used to update partial option but not
  7143. * be expected to change the order.
  7144. *
  7145. * Mode "replaceMege":
  7146. * (1) Only the id mapped components will be merged.
  7147. * (2) Other existing components (except internal compoonets) will be removed.
  7148. * (3) Other new options will be used to create new component.
  7149. * (4) The index of the existing compoents will not be modified.
  7150. * That means their might be "hole" after the removal.
  7151. * The new components are created first at those available index.
  7152. *
  7153. * Mode "replaceAll":
  7154. * This mode try to support that reproduce an echarts instance from another
  7155. * echarts instance (via `getOption`) in some simple cases.
  7156. * In this senario, the `result` index are exactly the consistent with the `newCmptOptions`,
  7157. * which ensures the compoennt index referring (like `xAxisIndex: ?`) corrent. That is,
  7158. * the "hole" in `newCmptOptions` will also be kept.
  7159. * On the contrary, other modes try best to eliminate holes.
  7160. * PENDING: This is an experimental mode yet.
  7161. *
  7162. * @return See the comment of <MappingResult>.
  7163. */
  7164. function mappingToExists(existings, newCmptOptions, mode) {
  7165. var isNormalMergeMode = mode === 'normalMerge';
  7166. var isReplaceMergeMode = mode === 'replaceMerge';
  7167. var isReplaceAllMode = mode === 'replaceAll';
  7168. existings = existings || [];
  7169. newCmptOptions = (newCmptOptions || []).slice();
  7170. var existingIdIdxMap = createHashMap(); // Validate id and name on user input option.
  7171. each(newCmptOptions, function (cmptOption, index) {
  7172. if (!isObject(cmptOption)) {
  7173. newCmptOptions[index] = null;
  7174. return;
  7175. }
  7176. if ("development" !== 'production') {
  7177. // There is some legacy case that name is set as `false`.
  7178. // But should work normally rather than throw error.
  7179. if (cmptOption.id != null && !isValidIdOrName(cmptOption.id)) {
  7180. warnInvalidateIdOrName(cmptOption.id);
  7181. }
  7182. if (cmptOption.name != null && !isValidIdOrName(cmptOption.name)) {
  7183. warnInvalidateIdOrName(cmptOption.name);
  7184. }
  7185. }
  7186. });
  7187. var result = prepareResult(existings, existingIdIdxMap, mode);
  7188. if (isNormalMergeMode || isReplaceMergeMode) {
  7189. mappingById(result, existings, existingIdIdxMap, newCmptOptions);
  7190. }
  7191. if (isNormalMergeMode) {
  7192. mappingByName(result, newCmptOptions);
  7193. }
  7194. if (isNormalMergeMode || isReplaceMergeMode) {
  7195. mappingByIndex(result, newCmptOptions, isReplaceMergeMode);
  7196. } else if (isReplaceAllMode) {
  7197. mappingInReplaceAllMode(result, newCmptOptions);
  7198. }
  7199. makeIdAndName(result); // The array `result` MUST NOT contain elided items, otherwise the
  7200. // forEach will ommit those items and result in incorrect result.
  7201. return result;
  7202. }
  7203. function prepareResult(existings, existingIdIdxMap, mode) {
  7204. var result = [];
  7205. if (mode === 'replaceAll') {
  7206. return result;
  7207. } // Do not use native `map` to in case that the array `existings`
  7208. // contains elided items, which will be ommited.
  7209. for (var index = 0; index < existings.length; index++) {
  7210. var existing = existings[index]; // Because of replaceMerge, `existing` may be null/undefined.
  7211. if (existing && existing.id != null) {
  7212. existingIdIdxMap.set(existing.id, index);
  7213. } // For non-internal-componnets:
  7214. // Mode "normalMerge": all existings kept.
  7215. // Mode "replaceMerge": all existing removed unless mapped by id.
  7216. // For internal-components:
  7217. // go with "replaceMerge" approach in both mode.
  7218. result.push({
  7219. existing: mode === 'replaceMerge' || isComponentIdInternal(existing) ? null : existing,
  7220. newOption: null,
  7221. keyInfo: null,
  7222. brandNew: null
  7223. });
  7224. }
  7225. return result;
  7226. }
  7227. function mappingById(result, existings, existingIdIdxMap, newCmptOptions) {
  7228. // Mapping by id if specified.
  7229. each(newCmptOptions, function (cmptOption, index) {
  7230. if (!cmptOption || cmptOption.id == null) {
  7231. return;
  7232. }
  7233. var optionId = makeComparableKey(cmptOption.id);
  7234. var existingIdx = existingIdIdxMap.get(optionId);
  7235. if (existingIdx != null) {
  7236. var resultItem = result[existingIdx];
  7237. assert(!resultItem.newOption, 'Duplicated option on id "' + optionId + '".');
  7238. resultItem.newOption = cmptOption; // In both mode, if id matched, new option will be merged to
  7239. // the existings rather than creating new component model.
  7240. resultItem.existing = existings[existingIdx];
  7241. newCmptOptions[index] = null;
  7242. }
  7243. });
  7244. }
  7245. function mappingByName(result, newCmptOptions) {
  7246. // Mapping by name if specified.
  7247. each(newCmptOptions, function (cmptOption, index) {
  7248. if (!cmptOption || cmptOption.name == null) {
  7249. return;
  7250. }
  7251. for (var i = 0; i < result.length; i++) {
  7252. var existing = result[i].existing;
  7253. if (!result[i].newOption // Consider name: two map to one.
  7254. // Can not match when both ids existing but different.
  7255. && existing && (existing.id == null || cmptOption.id == null) && !isComponentIdInternal(cmptOption) && !isComponentIdInternal(existing) && keyExistAndEqual('name', existing, cmptOption)) {
  7256. result[i].newOption = cmptOption;
  7257. newCmptOptions[index] = null;
  7258. return;
  7259. }
  7260. }
  7261. });
  7262. }
  7263. function mappingByIndex(result, newCmptOptions, brandNew) {
  7264. each(newCmptOptions, function (cmptOption) {
  7265. if (!cmptOption) {
  7266. return;
  7267. } // Find the first place that not mapped by id and not internal component (consider the "hole").
  7268. var resultItem;
  7269. var nextIdx = 0;
  7270. while ( // Be `!resultItem` only when `nextIdx >= result.length`.
  7271. (resultItem = result[nextIdx]) && ( // (1) Existing models that already have id should be able to mapped to. Because
  7272. // after mapping performed, model will always be assigned with an id if user not given.
  7273. // After that all models have id.
  7274. // (2) If new option has id, it can only set to a hole or append to the last. It should
  7275. // not be merged to the existings with different id. Because id should not be overwritten.
  7276. // (3) Name can be overwritten, because axis use name as 'show label text'.
  7277. resultItem.newOption || isComponentIdInternal(resultItem.existing) || // In mode "replaceMerge", here no not-mapped-non-internal-existing.
  7278. resultItem.existing && cmptOption.id != null && !keyExistAndEqual('id', cmptOption, resultItem.existing))) {
  7279. nextIdx++;
  7280. }
  7281. if (resultItem) {
  7282. resultItem.newOption = cmptOption;
  7283. resultItem.brandNew = brandNew;
  7284. } else {
  7285. result.push({
  7286. newOption: cmptOption,
  7287. brandNew: brandNew,
  7288. existing: null,
  7289. keyInfo: null
  7290. });
  7291. }
  7292. nextIdx++;
  7293. });
  7294. }
  7295. function mappingInReplaceAllMode(result, newCmptOptions) {
  7296. each(newCmptOptions, function (cmptOption) {
  7297. // The feature "reproduce" requires "hole" will also reproduced
  7298. // in case that compoennt index referring are broken.
  7299. result.push({
  7300. newOption: cmptOption,
  7301. brandNew: true,
  7302. existing: null,
  7303. keyInfo: null
  7304. });
  7305. });
  7306. }
  7307. /**
  7308. * Make id and name for mapping result (result of mappingToExists)
  7309. * into `keyInfo` field.
  7310. */
  7311. function makeIdAndName(mapResult) {
  7312. // We use this id to hash component models and view instances
  7313. // in echarts. id can be specified by user, or auto generated.
  7314. // The id generation rule ensures new view instance are able
  7315. // to mapped to old instance when setOption are called in
  7316. // no-merge mode. So we generate model id by name and plus
  7317. // type in view id.
  7318. // name can be duplicated among components, which is convenient
  7319. // to specify multi components (like series) by one name.
  7320. // Ensure that each id is distinct.
  7321. var idMap = createHashMap();
  7322. each(mapResult, function (item) {
  7323. var existing = item.existing;
  7324. existing && idMap.set(existing.id, item);
  7325. });
  7326. each(mapResult, function (item) {
  7327. var opt = item.newOption; // Force ensure id not duplicated.
  7328. assert(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  7329. opt && opt.id != null && idMap.set(opt.id, item);
  7330. !item.keyInfo && (item.keyInfo = {});
  7331. }); // Make name and id.
  7332. each(mapResult, function (item, index) {
  7333. var existing = item.existing;
  7334. var opt = item.newOption;
  7335. var keyInfo = item.keyInfo;
  7336. if (!isObject(opt)) {
  7337. return;
  7338. } // name can be overwitten. Consider case: axis.name = '20km'.
  7339. // But id generated by name will not be changed, which affect
  7340. // only in that case: setOption with 'not merge mode' and view
  7341. // instance will be recreated, which can be accepted.
  7342. keyInfo.name = opt.name != null ? makeComparableKey(opt.name) : existing ? existing.name // Avoid diffferent series has the same name,
  7343. // because name may be used like in color pallet.
  7344. : DUMMY_COMPONENT_NAME_PREFIX + index;
  7345. if (existing) {
  7346. keyInfo.id = makeComparableKey(existing.id);
  7347. } else if (opt.id != null) {
  7348. keyInfo.id = makeComparableKey(opt.id);
  7349. } else {
  7350. // Consider this situatoin:
  7351. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  7352. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  7353. // Series with the same name between optionA and optionB
  7354. // should be mapped.
  7355. var idNum = 0;
  7356. do {
  7357. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  7358. } while (idMap.get(keyInfo.id));
  7359. }
  7360. idMap.set(keyInfo.id, item);
  7361. });
  7362. }
  7363. function keyExistAndEqual(attr, obj1, obj2) {
  7364. var key1 = convertOptionIdName(obj1[attr], null);
  7365. var key2 = convertOptionIdName(obj2[attr], null); // See `MappingExistingItem`. `id` and `name` trade string equals to number.
  7366. return key1 != null && key2 != null && key1 === key2;
  7367. }
  7368. /**
  7369. * @return return null if not exist.
  7370. */
  7371. function makeComparableKey(val) {
  7372. if ("development" !== 'production') {
  7373. if (val == null) {
  7374. throw new Error();
  7375. }
  7376. }
  7377. return convertOptionIdName(val, '');
  7378. }
  7379. function convertOptionIdName(idOrName, defaultValue) {
  7380. if (idOrName == null) {
  7381. return defaultValue;
  7382. }
  7383. var type = typeof idOrName;
  7384. return type === 'string' ? idOrName : type === 'number' || isStringSafe(idOrName) ? idOrName + '' : defaultValue;
  7385. }
  7386. function warnInvalidateIdOrName(idOrName) {
  7387. if ("development" !== 'production') {
  7388. warn('`' + idOrName + '` is invalid id or name. Must be a string or number.');
  7389. }
  7390. }
  7391. function isValidIdOrName(idOrName) {
  7392. return isStringSafe(idOrName) || isNumeric(idOrName);
  7393. }
  7394. function isNameSpecified(componentModel) {
  7395. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  7396. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  7397. }
  7398. /**
  7399. * @public
  7400. * @param {Object} cmptOption
  7401. * @return {boolean}
  7402. */
  7403. function isComponentIdInternal(cmptOption) {
  7404. return cmptOption && cmptOption.id != null && makeComparableKey(cmptOption.id).indexOf(INTERNAL_COMPONENT_ID_PREFIX) === 0;
  7405. }
  7406. function makeInternalComponentId(idSuffix) {
  7407. return INTERNAL_COMPONENT_ID_PREFIX + idSuffix;
  7408. }
  7409. function setComponentTypeToKeyInfo(mappingResult, mainType, componentModelCtor) {
  7410. // Set mainType and complete subType.
  7411. each(mappingResult, function (item) {
  7412. var newOption = item.newOption;
  7413. if (isObject(newOption)) {
  7414. item.keyInfo.mainType = mainType;
  7415. item.keyInfo.subType = determineSubType(mainType, newOption, item.existing, componentModelCtor);
  7416. }
  7417. });
  7418. }
  7419. function determineSubType(mainType, newCmptOption, existComponent, componentModelCtor) {
  7420. var subType = newCmptOption.type ? newCmptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  7421. : componentModelCtor.determineSubType(mainType, newCmptOption); // tooltip, markline, markpoint may always has no subType
  7422. return subType;
  7423. }
  7424. /**
  7425. * A helper for removing duplicate items between batchA and batchB,
  7426. * and in themselves, and categorize by series.
  7427. *
  7428. * @param batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  7429. * @param batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  7430. * @return result: [resultBatchA, resultBatchB]
  7431. */
  7432. function compressBatches(batchA, batchB) {
  7433. var mapA = {};
  7434. var mapB = {};
  7435. makeMap(batchA || [], mapA);
  7436. makeMap(batchB || [], mapB, mapA);
  7437. return [mapToArray(mapA), mapToArray(mapB)];
  7438. function makeMap(sourceBatch, map, otherMap) {
  7439. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  7440. var seriesId = convertOptionIdName(sourceBatch[i].seriesId, null);
  7441. if (seriesId == null) {
  7442. return;
  7443. }
  7444. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  7445. var otherDataIndices = otherMap && otherMap[seriesId];
  7446. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  7447. var dataIndex = dataIndices[j];
  7448. if (otherDataIndices && otherDataIndices[dataIndex]) {
  7449. otherDataIndices[dataIndex] = null;
  7450. } else {
  7451. (map[seriesId] || (map[seriesId] = {}))[dataIndex] = 1;
  7452. }
  7453. }
  7454. }
  7455. }
  7456. function mapToArray(map, isData) {
  7457. var result = [];
  7458. for (var i in map) {
  7459. if (map.hasOwnProperty(i) && map[i] != null) {
  7460. if (isData) {
  7461. result.push(+i);
  7462. } else {
  7463. var dataIndices = mapToArray(map[i], true);
  7464. dataIndices.length && result.push({
  7465. seriesId: i,
  7466. dataIndex: dataIndices
  7467. });
  7468. }
  7469. }
  7470. }
  7471. return result;
  7472. }
  7473. }
  7474. /**
  7475. * @param payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  7476. * each of which can be Array or primary type.
  7477. * @return dataIndex If not found, return undefined/null.
  7478. */
  7479. function queryDataIndex(data, payload) {
  7480. if (payload.dataIndexInside != null) {
  7481. return payload.dataIndexInside;
  7482. } else if (payload.dataIndex != null) {
  7483. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  7484. return data.indexOfRawIndex(value);
  7485. }) : data.indexOfRawIndex(payload.dataIndex);
  7486. } else if (payload.name != null) {
  7487. return isArray(payload.name) ? map(payload.name, function (value) {
  7488. return data.indexOfName(value);
  7489. }) : data.indexOfName(payload.name);
  7490. }
  7491. }
  7492. /**
  7493. * Enable property storage to any host object.
  7494. * Notice: Serialization is not supported.
  7495. *
  7496. * For example:
  7497. * let inner = zrUitl.makeInner();
  7498. *
  7499. * function some1(hostObj) {
  7500. * inner(hostObj).someProperty = 1212;
  7501. * ...
  7502. * }
  7503. * function some2() {
  7504. * let fields = inner(this);
  7505. * fields.someProperty1 = 1212;
  7506. * fields.someProperty2 = 'xx';
  7507. * ...
  7508. * }
  7509. *
  7510. * @return {Function}
  7511. */
  7512. function makeInner() {
  7513. var key = '__ec_inner_' + innerUniqueIndex++;
  7514. return function (hostObj) {
  7515. return hostObj[key] || (hostObj[key] = {});
  7516. };
  7517. }
  7518. var innerUniqueIndex = getRandomIdBase();
  7519. /**
  7520. * The same behavior as `component.getReferringComponents`.
  7521. */
  7522. function parseFinder(ecModel, finderInput, opt) {
  7523. var finder;
  7524. if (isString(finderInput)) {
  7525. var obj = {};
  7526. obj[finderInput + 'Index'] = 0;
  7527. finder = obj;
  7528. } else {
  7529. finder = finderInput;
  7530. }
  7531. var queryOptionMap = createHashMap();
  7532. var result = {};
  7533. var mainTypeSpecified = false;
  7534. each(finder, function (value, key) {
  7535. // Exclude 'dataIndex' and other illgal keys.
  7536. if (key === 'dataIndex' || key === 'dataIndexInside') {
  7537. result[key] = value;
  7538. return;
  7539. }
  7540. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  7541. var mainType = parsedKey[1];
  7542. var queryType = (parsedKey[2] || '').toLowerCase();
  7543. if (!mainType || !queryType || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  7544. return;
  7545. }
  7546. mainTypeSpecified = mainTypeSpecified || !!mainType;
  7547. var queryOption = queryOptionMap.get(mainType) || queryOptionMap.set(mainType, {});
  7548. queryOption[queryType] = value;
  7549. });
  7550. var defaultMainType = opt ? opt.defaultMainType : null;
  7551. if (!mainTypeSpecified && defaultMainType) {
  7552. queryOptionMap.set(defaultMainType, {});
  7553. }
  7554. queryOptionMap.each(function (queryOption, mainType) {
  7555. var queryResult = queryReferringComponents(ecModel, mainType, queryOption, {
  7556. useDefault: defaultMainType === mainType,
  7557. enableAll: opt && opt.enableAll != null ? opt.enableAll : true,
  7558. enableNone: opt && opt.enableNone != null ? opt.enableNone : true
  7559. });
  7560. result[mainType + 'Models'] = queryResult.models;
  7561. result[mainType + 'Model'] = queryResult.models[0];
  7562. });
  7563. return result;
  7564. }
  7565. var SINGLE_REFERRING = {
  7566. useDefault: true,
  7567. enableAll: false,
  7568. enableNone: false
  7569. };
  7570. var MULTIPLE_REFERRING = {
  7571. useDefault: false,
  7572. enableAll: true,
  7573. enableNone: true
  7574. };
  7575. function queryReferringComponents(ecModel, mainType, userOption, opt) {
  7576. opt = opt || SINGLE_REFERRING;
  7577. var indexOption = userOption.index;
  7578. var idOption = userOption.id;
  7579. var nameOption = userOption.name;
  7580. var result = {
  7581. models: null,
  7582. specified: indexOption != null || idOption != null || nameOption != null
  7583. };
  7584. if (!result.specified) {
  7585. // Use the first as default if `useDefault`.
  7586. var firstCmpt = void 0;
  7587. result.models = opt.useDefault && (firstCmpt = ecModel.getComponent(mainType)) ? [firstCmpt] : [];
  7588. return result;
  7589. }
  7590. if (indexOption === 'none' || indexOption === false) {
  7591. assert(opt.enableNone, '`"none"` or `false` is not a valid value on index option.');
  7592. result.models = [];
  7593. return result;
  7594. } // `queryComponents` will return all components if
  7595. // both all of index/id/name are null/undefined.
  7596. if (indexOption === 'all') {
  7597. assert(opt.enableAll, '`"all"` is not a valid value on index option.');
  7598. indexOption = idOption = nameOption = null;
  7599. }
  7600. result.models = ecModel.queryComponents({
  7601. mainType: mainType,
  7602. index: indexOption,
  7603. id: idOption,
  7604. name: nameOption
  7605. });
  7606. return result;
  7607. }
  7608. function setAttribute(dom, key, value) {
  7609. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  7610. }
  7611. function getAttribute(dom, key) {
  7612. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  7613. }
  7614. function getTooltipRenderMode(renderModeOption) {
  7615. if (renderModeOption === 'auto') {
  7616. // Using html when `document` exists, use richText otherwise
  7617. return env.domSupported ? 'html' : 'richText';
  7618. } else {
  7619. return renderModeOption || 'html';
  7620. }
  7621. }
  7622. /**
  7623. * Group a list by key.
  7624. */
  7625. function groupData(array, getKey // return key
  7626. ) {
  7627. var buckets = createHashMap();
  7628. var keys = [];
  7629. each(array, function (item) {
  7630. var key = getKey(item);
  7631. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  7632. });
  7633. return {
  7634. keys: keys,
  7635. buckets: buckets
  7636. };
  7637. }
  7638. /**
  7639. * Interpolate raw values of a series with percent
  7640. *
  7641. * @param data data
  7642. * @param labelModel label model of the text element
  7643. * @param sourceValue start value. May be null/undefined when init.
  7644. * @param targetValue end value
  7645. * @param percent 0~1 percentage; 0 uses start value while 1 uses end value
  7646. * @return interpolated values
  7647. * If `sourceValue` and `targetValue` are `number`, return `number`.
  7648. * If `sourceValue` and `targetValue` are `string`, return `string`.
  7649. * If `sourceValue` and `targetValue` are `(string | number)[]`, return `(string | number)[]`.
  7650. * Other cases do not supported.
  7651. */
  7652. function interpolateRawValues(data, precision, sourceValue, targetValue, percent) {
  7653. var isAutoPrecision = precision == null || precision === 'auto';
  7654. if (targetValue == null) {
  7655. return targetValue;
  7656. }
  7657. if (typeof targetValue === 'number') {
  7658. var value = interpolateNumber(sourceValue || 0, targetValue, percent);
  7659. return round(value, isAutoPrecision ? Math.max(getPrecisionSafe(sourceValue || 0), getPrecisionSafe(targetValue)) : precision);
  7660. } else if (typeof targetValue === 'string') {
  7661. return percent < 1 ? sourceValue : targetValue;
  7662. } else {
  7663. var interpolated = [];
  7664. var leftArr = sourceValue;
  7665. var rightArr = targetValue;
  7666. var length_1 = Math.max(leftArr ? leftArr.length : 0, rightArr.length);
  7667. for (var i = 0; i < length_1; ++i) {
  7668. var info = data.getDimensionInfo(i); // Don't interpolate ordinal dims
  7669. if (info.type === 'ordinal') {
  7670. // In init, there is no `sourceValue`, but should better not to get undefined result.
  7671. interpolated[i] = (percent < 1 && leftArr ? leftArr : rightArr)[i];
  7672. } else {
  7673. var leftVal = leftArr && leftArr[i] ? leftArr[i] : 0;
  7674. var rightVal = rightArr[i];
  7675. var value = interpolateNumber(leftVal, rightVal, percent);
  7676. interpolated[i] = round(value, isAutoPrecision ? Math.max(getPrecisionSafe(leftVal), getPrecisionSafe(rightVal)) : precision);
  7677. }
  7678. }
  7679. return interpolated;
  7680. }
  7681. }
  7682. var TYPE_DELIMITER = '.';
  7683. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  7684. var IS_EXTENDED_CLASS = '___EC__EXTENDED_CLASS___';
  7685. /**
  7686. * Notice, parseClassType('') should returns {main: '', sub: ''}
  7687. * @public
  7688. */
  7689. function parseClassType(componentType) {
  7690. var ret = {
  7691. main: '',
  7692. sub: ''
  7693. };
  7694. if (componentType) {
  7695. var typeArr = componentType.split(TYPE_DELIMITER);
  7696. ret.main = typeArr[0] || '';
  7697. ret.sub = typeArr[1] || '';
  7698. }
  7699. return ret;
  7700. }
  7701. /**
  7702. * @public
  7703. */
  7704. function checkClassType(componentType) {
  7705. assert(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  7706. }
  7707. function isExtendedClass(clz) {
  7708. return !!(clz && clz[IS_EXTENDED_CLASS]);
  7709. }
  7710. /**
  7711. * Implements `ExtendableConstructor` for `rootClz`.
  7712. *
  7713. * @usage
  7714. * ```ts
  7715. * class Xxx {}
  7716. * type XxxConstructor = typeof Xxx & ExtendableConstructor
  7717. * enableClassExtend(Xxx as XxxConstructor);
  7718. * ```
  7719. */
  7720. function enableClassExtend(rootClz, mandatoryMethods) {
  7721. rootClz.$constructor = rootClz; // FIXME: not necessary?
  7722. rootClz.extend = function (proto) {
  7723. if ("development" !== 'production') {
  7724. each(mandatoryMethods, function (method) {
  7725. if (!proto[method]) {
  7726. console.warn('Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.');
  7727. }
  7728. });
  7729. }
  7730. var superClass = this; // For backward compat, we both support ts class inheritance and this
  7731. // "extend" approach.
  7732. // The constructor should keep the same behavior as ts class inheritance:
  7733. // If this constructor/$constructor is not declared, auto invoke the super
  7734. // constructor.
  7735. // If this constructor/$constructor is declared, it is responsible for
  7736. // calling the super constructor.
  7737. function ExtendedClass() {
  7738. var args = [];
  7739. for (var _i = 0; _i < arguments.length; _i++) {
  7740. args[_i] = arguments[_i];
  7741. }
  7742. if (!proto.$constructor) {
  7743. if (!isESClass(superClass)) {
  7744. // Will throw error if superClass is an es6 native class.
  7745. superClass.apply(this, arguments);
  7746. } else {
  7747. var ins = createObject( // @ts-ignore
  7748. ExtendedClass.prototype, new (superClass.bind.apply(superClass, __spreadArrays([void 0], args)))());
  7749. return ins;
  7750. }
  7751. } else {
  7752. proto.$constructor.apply(this, arguments);
  7753. }
  7754. }
  7755. ExtendedClass[IS_EXTENDED_CLASS] = true;
  7756. extend(ExtendedClass.prototype, proto);
  7757. ExtendedClass.extend = this.extend;
  7758. ExtendedClass.superCall = superCall;
  7759. ExtendedClass.superApply = superApply;
  7760. inherits(ExtendedClass, this);
  7761. ExtendedClass.superClass = superClass;
  7762. return ExtendedClass;
  7763. };
  7764. }
  7765. function isESClass(fn) {
  7766. return typeof fn === 'function' && /^class\s/.test(Function.prototype.toString.call(fn));
  7767. }
  7768. /**
  7769. * A work around to both support ts extend and this extend mechanism.
  7770. * on sub-class.
  7771. * @usage
  7772. * ```ts
  7773. * class Component { ... }
  7774. * classUtil.enableClassExtend(Component);
  7775. * classUtil.enableClassManagement(Component, {registerWhenExtend: true});
  7776. *
  7777. * class Series extends Component { ... }
  7778. * // Without calling `markExtend`, `registerWhenExtend` will not work.
  7779. * Component.markExtend(Series);
  7780. * ```
  7781. */
  7782. function mountExtend(SubClz, SupperClz) {
  7783. SubClz.extend = SupperClz.extend;
  7784. } // A random offset.
  7785. var classBase = Math.round(Math.random() * 10);
  7786. /**
  7787. * Implements `CheckableConstructor` for `target`.
  7788. * Can not use instanceof, consider different scope by
  7789. * cross domain or es module import in ec extensions.
  7790. * Mount a method "isInstance()" to Clz.
  7791. *
  7792. * @usage
  7793. * ```ts
  7794. * class Xxx {}
  7795. * type XxxConstructor = typeof Xxx & CheckableConstructor;
  7796. * enableClassCheck(Xxx as XxxConstructor)
  7797. * ```
  7798. */
  7799. function enableClassCheck(target) {
  7800. var classAttr = ['__\0is_clz', classBase++].join('_');
  7801. target.prototype[classAttr] = true;
  7802. if ("development" !== 'production') {
  7803. assert(!target.isInstance, 'The method "is" can not be defined.');
  7804. }
  7805. target.isInstance = function (obj) {
  7806. return !!(obj && obj[classAttr]);
  7807. };
  7808. } // superCall should have class info, which can not be fetch from 'this'.
  7809. // Consider this case:
  7810. // class A has method f,
  7811. // class B inherits class A, overrides method f, f call superApply('f'),
  7812. // class C inherits class B, do not overrides method f,
  7813. // then when method of class C is called, dead loop occured.
  7814. function superCall(context, methodName) {
  7815. var args = [];
  7816. for (var _i = 2; _i < arguments.length; _i++) {
  7817. args[_i - 2] = arguments[_i];
  7818. }
  7819. return this.superClass.prototype[methodName].apply(context, args);
  7820. }
  7821. function superApply(context, methodName, args) {
  7822. return this.superClass.prototype[methodName].apply(context, args);
  7823. }
  7824. /**
  7825. * Implements `ClassManager` for `target`
  7826. *
  7827. * @usage
  7828. * ```ts
  7829. * class Xxx {}
  7830. * type XxxConstructor = typeof Xxx & ClassManager
  7831. * enableClassManagement(Xxx as XxxConstructor);
  7832. * ```
  7833. */
  7834. function enableClassManagement(target) {
  7835. /**
  7836. * Component model classes
  7837. * key: componentType,
  7838. * value:
  7839. * componentClass, when componentType is 'xxx'
  7840. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  7841. */
  7842. var storage = {};
  7843. target.registerClass = function (clz) {
  7844. // `type` should not be a "instance memeber".
  7845. // If using TS class, should better declared as `static type = 'series.pie'`.
  7846. // otherwise users have to mount `type` on prototype manually.
  7847. // For backward compat and enable instance visit type via `this.type`,
  7848. // we stil support fetch `type` from prototype.
  7849. var componentFullType = clz.type || clz.prototype.type;
  7850. if (componentFullType) {
  7851. checkClassType(componentFullType); // If only static type declared, we assign it to prototype mandatorily.
  7852. clz.prototype.type = componentFullType;
  7853. var componentTypeInfo = parseClassType(componentFullType);
  7854. if (!componentTypeInfo.sub) {
  7855. if ("development" !== 'production') {
  7856. if (storage[componentTypeInfo.main]) {
  7857. console.warn(componentTypeInfo.main + ' exists.');
  7858. }
  7859. }
  7860. storage[componentTypeInfo.main] = clz;
  7861. } else if (componentTypeInfo.sub !== IS_CONTAINER) {
  7862. var container = makeContainer(componentTypeInfo);
  7863. container[componentTypeInfo.sub] = clz;
  7864. }
  7865. }
  7866. return clz;
  7867. };
  7868. target.getClass = function (mainType, subType, throwWhenNotFound) {
  7869. var clz = storage[mainType];
  7870. if (clz && clz[IS_CONTAINER]) {
  7871. clz = subType ? clz[subType] : null;
  7872. }
  7873. if (throwWhenNotFound && !clz) {
  7874. throw new Error(!subType ? mainType + '.' + 'type should be specified.' : 'Component ' + mainType + '.' + (subType || '') + ' not exists. Load it first.');
  7875. }
  7876. return clz;
  7877. };
  7878. target.getClassesByMainType = function (componentType) {
  7879. var componentTypeInfo = parseClassType(componentType);
  7880. var result = [];
  7881. var obj = storage[componentTypeInfo.main];
  7882. if (obj && obj[IS_CONTAINER]) {
  7883. each(obj, function (o, type) {
  7884. type !== IS_CONTAINER && result.push(o);
  7885. });
  7886. } else {
  7887. result.push(obj);
  7888. }
  7889. return result;
  7890. };
  7891. target.hasClass = function (componentType) {
  7892. // Just consider componentType.main.
  7893. var componentTypeInfo = parseClassType(componentType);
  7894. return !!storage[componentTypeInfo.main];
  7895. };
  7896. /**
  7897. * @return Like ['aa', 'bb'], but can not be ['aa.xx']
  7898. */
  7899. target.getAllClassMainTypes = function () {
  7900. var types = [];
  7901. each(storage, function (obj, type) {
  7902. types.push(type);
  7903. });
  7904. return types;
  7905. };
  7906. /**
  7907. * If a main type is container and has sub types
  7908. */
  7909. target.hasSubTypes = function (componentType) {
  7910. var componentTypeInfo = parseClassType(componentType);
  7911. var obj = storage[componentTypeInfo.main];
  7912. return obj && obj[IS_CONTAINER];
  7913. };
  7914. function makeContainer(componentTypeInfo) {
  7915. var container = storage[componentTypeInfo.main];
  7916. if (!container || !container[IS_CONTAINER]) {
  7917. container = storage[componentTypeInfo.main] = {};
  7918. container[IS_CONTAINER] = true;
  7919. }
  7920. return container;
  7921. }
  7922. } // /**
  7923. // * @param {string|Array.<string>} properties
  7924. // */
  7925. // export function setReadOnly(obj, properties) {
  7926. // FIXME It seems broken in IE8 simulation of IE11
  7927. // if (!zrUtil.isArray(properties)) {
  7928. // properties = properties != null ? [properties] : [];
  7929. // }
  7930. // zrUtil.each(properties, function (prop) {
  7931. // let value = obj[prop];
  7932. // Object.defineProperty
  7933. // && Object.defineProperty(obj, prop, {
  7934. // value: value, writable: false
  7935. // });
  7936. // zrUtil.isArray(obj[prop])
  7937. // && Object.freeze
  7938. // && Object.freeze(obj[prop]);
  7939. // });
  7940. // }
  7941. function makeStyleMapper(properties, ignoreParent) {
  7942. // Normalize
  7943. for (var i = 0; i < properties.length; i++) {
  7944. if (!properties[i][1]) {
  7945. properties[i][1] = properties[i][0];
  7946. }
  7947. }
  7948. ignoreParent = ignoreParent || false;
  7949. return function (model, excludes, includes) {
  7950. var style = {};
  7951. for (var i = 0; i < properties.length; i++) {
  7952. var propName = properties[i][1];
  7953. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  7954. continue;
  7955. }
  7956. var val = model.getShallow(propName, ignoreParent);
  7957. if (val != null) {
  7958. style[properties[i][0]] = val;
  7959. }
  7960. } // TODO Text or image?
  7961. return style;
  7962. };
  7963. }
  7964. var AREA_STYLE_KEY_MAP = [['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  7965. // So do not transfer decal directly.
  7966. ];
  7967. var getAreaStyle = makeStyleMapper(AREA_STYLE_KEY_MAP);
  7968. var AreaStyleMixin =
  7969. /** @class */
  7970. function () {
  7971. function AreaStyleMixin() {}
  7972. AreaStyleMixin.prototype.getAreaStyle = function (excludes, includes) {
  7973. return getAreaStyle(this, excludes, includes);
  7974. };
  7975. return AreaStyleMixin;
  7976. }();
  7977. var globalImageCache = new LRU(50);
  7978. function findExistImage(newImageOrSrc) {
  7979. if (typeof newImageOrSrc === 'string') {
  7980. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7981. return cachedImgObj && cachedImgObj.image;
  7982. }
  7983. else {
  7984. return newImageOrSrc;
  7985. }
  7986. }
  7987. function createOrUpdateImage(newImageOrSrc, image, hostEl, onload, cbPayload) {
  7988. if (!newImageOrSrc) {
  7989. return image;
  7990. }
  7991. else if (typeof newImageOrSrc === 'string') {
  7992. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  7993. return image;
  7994. }
  7995. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  7996. var pendingWrap = { hostEl: hostEl, cb: onload, cbPayload: cbPayload };
  7997. if (cachedImgObj) {
  7998. image = cachedImgObj.image;
  7999. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  8000. }
  8001. else {
  8002. image = new Image();
  8003. image.onload = image.onerror = imageOnLoad;
  8004. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  8005. image: image,
  8006. pending: [pendingWrap]
  8007. });
  8008. image.src = image.__zrImageSrc = newImageOrSrc;
  8009. }
  8010. return image;
  8011. }
  8012. else {
  8013. return newImageOrSrc;
  8014. }
  8015. }
  8016. function imageOnLoad() {
  8017. var cachedImgObj = this.__cachedImgObj;
  8018. this.onload = this.onerror = this.__cachedImgObj = null;
  8019. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  8020. var pendingWrap = cachedImgObj.pending[i];
  8021. var cb = pendingWrap.cb;
  8022. cb && cb(this, pendingWrap.cbPayload);
  8023. pendingWrap.hostEl.dirty();
  8024. }
  8025. cachedImgObj.pending.length = 0;
  8026. }
  8027. function isImageReady(image) {
  8028. return image && image.width && image.height;
  8029. }
  8030. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  8031. function truncateText(text, containerWidth, font, ellipsis, options) {
  8032. if (!containerWidth) {
  8033. return '';
  8034. }
  8035. var textLines = (text + '').split('\n');
  8036. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  8037. for (var i = 0, len = textLines.length; i < len; i++) {
  8038. textLines[i] = truncateSingleLine(textLines[i], options);
  8039. }
  8040. return textLines.join('\n');
  8041. }
  8042. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  8043. options = options || {};
  8044. var preparedOpts = extend({}, options);
  8045. preparedOpts.font = font;
  8046. ellipsis = retrieve2(ellipsis, '...');
  8047. preparedOpts.maxIterations = retrieve2(options.maxIterations, 2);
  8048. var minChar = preparedOpts.minChar = retrieve2(options.minChar, 0);
  8049. preparedOpts.cnCharWidth = getWidth('国', font);
  8050. var ascCharWidth = preparedOpts.ascCharWidth = getWidth('a', font);
  8051. preparedOpts.placeholder = retrieve2(options.placeholder, '');
  8052. var contentWidth = containerWidth = Math.max(0, containerWidth - 1);
  8053. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  8054. contentWidth -= ascCharWidth;
  8055. }
  8056. var ellipsisWidth = getWidth(ellipsis, font);
  8057. if (ellipsisWidth > contentWidth) {
  8058. ellipsis = '';
  8059. ellipsisWidth = 0;
  8060. }
  8061. contentWidth = containerWidth - ellipsisWidth;
  8062. preparedOpts.ellipsis = ellipsis;
  8063. preparedOpts.ellipsisWidth = ellipsisWidth;
  8064. preparedOpts.contentWidth = contentWidth;
  8065. preparedOpts.containerWidth = containerWidth;
  8066. return preparedOpts;
  8067. }
  8068. function truncateSingleLine(textLine, options) {
  8069. var containerWidth = options.containerWidth;
  8070. var font = options.font;
  8071. var contentWidth = options.contentWidth;
  8072. if (!containerWidth) {
  8073. return '';
  8074. }
  8075. var lineWidth = getWidth(textLine, font);
  8076. if (lineWidth <= containerWidth) {
  8077. return textLine;
  8078. }
  8079. for (var j = 0;; j++) {
  8080. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  8081. textLine += options.ellipsis;
  8082. break;
  8083. }
  8084. var subLength = j === 0
  8085. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  8086. : lineWidth > 0
  8087. ? Math.floor(textLine.length * contentWidth / lineWidth)
  8088. : 0;
  8089. textLine = textLine.substr(0, subLength);
  8090. lineWidth = getWidth(textLine, font);
  8091. }
  8092. if (textLine === '') {
  8093. textLine = options.placeholder;
  8094. }
  8095. return textLine;
  8096. }
  8097. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  8098. var width = 0;
  8099. var i = 0;
  8100. for (var len = text.length; i < len && width < contentWidth; i++) {
  8101. var charCode = text.charCodeAt(i);
  8102. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  8103. }
  8104. return i;
  8105. }
  8106. function parsePlainText(text, style) {
  8107. text != null && (text += '');
  8108. var overflow = style.overflow;
  8109. var padding = style.padding;
  8110. var font = style.font;
  8111. var truncate = overflow === 'truncate';
  8112. var calculatedLineHeight = getLineHeight(font);
  8113. var lineHeight = retrieve2(style.lineHeight, calculatedLineHeight);
  8114. var truncateLineOverflow = style.lineOverflow === 'truncate';
  8115. var width = style.width;
  8116. var lines;
  8117. if (width != null && overflow === 'break' || overflow === 'breakAll') {
  8118. lines = text ? wrapText(text, style.font, width, overflow === 'breakAll', 0).lines : [];
  8119. }
  8120. else {
  8121. lines = text ? text.split('\n') : [];
  8122. }
  8123. var contentHeight = lines.length * lineHeight;
  8124. var height = retrieve2(style.height, contentHeight);
  8125. if (contentHeight > height && truncateLineOverflow) {
  8126. var lineCount = Math.floor(height / lineHeight);
  8127. lines = lines.slice(0, lineCount);
  8128. }
  8129. var outerHeight = height;
  8130. var outerWidth = width;
  8131. if (padding) {
  8132. outerHeight += padding[0] + padding[2];
  8133. if (outerWidth != null) {
  8134. outerWidth += padding[1] + padding[3];
  8135. }
  8136. }
  8137. if (text && truncate && outerWidth != null) {
  8138. var options = prepareTruncateOptions(width, font, style.ellipsis, {
  8139. minChar: style.truncateMinChar,
  8140. placeholder: style.placeholder
  8141. });
  8142. for (var i = 0; i < lines.length; i++) {
  8143. lines[i] = truncateSingleLine(lines[i], options);
  8144. }
  8145. }
  8146. if (width == null) {
  8147. var maxWidth = 0;
  8148. for (var i = 0; i < lines.length; i++) {
  8149. maxWidth = Math.max(getWidth(lines[i], font), maxWidth);
  8150. }
  8151. width = maxWidth;
  8152. }
  8153. return {
  8154. lines: lines,
  8155. height: height,
  8156. outerHeight: outerHeight,
  8157. lineHeight: lineHeight,
  8158. calculatedLineHeight: calculatedLineHeight,
  8159. contentHeight: contentHeight,
  8160. width: width
  8161. };
  8162. }
  8163. var RichTextToken = (function () {
  8164. function RichTextToken() {
  8165. }
  8166. return RichTextToken;
  8167. }());
  8168. var RichTextLine = (function () {
  8169. function RichTextLine(tokens) {
  8170. this.tokens = [];
  8171. if (tokens) {
  8172. this.tokens = tokens;
  8173. }
  8174. }
  8175. return RichTextLine;
  8176. }());
  8177. var RichTextContentBlock = (function () {
  8178. function RichTextContentBlock() {
  8179. this.width = 0;
  8180. this.height = 0;
  8181. this.contentWidth = 0;
  8182. this.contentHeight = 0;
  8183. this.outerWidth = 0;
  8184. this.outerHeight = 0;
  8185. this.lines = [];
  8186. }
  8187. return RichTextContentBlock;
  8188. }());
  8189. function parseRichText(text, style) {
  8190. var contentBlock = new RichTextContentBlock();
  8191. text != null && (text += '');
  8192. if (!text) {
  8193. return contentBlock;
  8194. }
  8195. var topWidth = style.width;
  8196. var topHeight = style.height;
  8197. var overflow = style.overflow;
  8198. var wrapInfo = (overflow === 'break' || overflow === 'breakAll') && topWidth != null
  8199. ? { width: topWidth, accumWidth: 0, breakAll: overflow === 'breakAll' }
  8200. : null;
  8201. var lastIndex = STYLE_REG.lastIndex = 0;
  8202. var result;
  8203. while ((result = STYLE_REG.exec(text)) != null) {
  8204. var matchedIndex = result.index;
  8205. if (matchedIndex > lastIndex) {
  8206. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex), style, wrapInfo);
  8207. }
  8208. pushTokens(contentBlock, result[2], style, wrapInfo, result[1]);
  8209. lastIndex = STYLE_REG.lastIndex;
  8210. }
  8211. if (lastIndex < text.length) {
  8212. pushTokens(contentBlock, text.substring(lastIndex, text.length), style, wrapInfo);
  8213. }
  8214. var pendingList = [];
  8215. var calculatedHeight = 0;
  8216. var calculatedWidth = 0;
  8217. var stlPadding = style.padding;
  8218. var truncate = overflow === 'truncate';
  8219. var truncateLine = style.lineOverflow === 'truncate';
  8220. function finishLine(line, lineWidth, lineHeight) {
  8221. line.width = lineWidth;
  8222. line.lineHeight = lineHeight;
  8223. calculatedHeight += lineHeight;
  8224. calculatedWidth = Math.max(calculatedWidth, lineWidth);
  8225. }
  8226. outer: for (var i = 0; i < contentBlock.lines.length; i++) {
  8227. var line = contentBlock.lines[i];
  8228. var lineHeight = 0;
  8229. var lineWidth = 0;
  8230. for (var j = 0; j < line.tokens.length; j++) {
  8231. var token = line.tokens[j];
  8232. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  8233. var textPadding = token.textPadding = tokenStyle.padding;
  8234. var paddingH = textPadding ? textPadding[1] + textPadding[3] : 0;
  8235. var font = token.font = tokenStyle.font || style.font;
  8236. token.contentHeight = getLineHeight(font);
  8237. var tokenHeight = retrieve2(tokenStyle.height, token.contentHeight);
  8238. token.innerHeight = tokenHeight;
  8239. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  8240. token.height = tokenHeight;
  8241. token.lineHeight = retrieve3(tokenStyle.lineHeight, style.lineHeight, tokenHeight);
  8242. token.align = tokenStyle && tokenStyle.align || style.align;
  8243. token.verticalAlign = tokenStyle && tokenStyle.verticalAlign || 'middle';
  8244. if (truncateLine && topHeight != null && calculatedHeight + token.lineHeight > topHeight) {
  8245. if (j > 0) {
  8246. line.tokens = line.tokens.slice(0, j);
  8247. finishLine(line, lineWidth, lineHeight);
  8248. contentBlock.lines = contentBlock.lines.slice(0, i + 1);
  8249. }
  8250. else {
  8251. contentBlock.lines = contentBlock.lines.slice(0, i);
  8252. }
  8253. break outer;
  8254. }
  8255. var styleTokenWidth = tokenStyle.width;
  8256. var tokenWidthNotSpecified = styleTokenWidth == null || styleTokenWidth === 'auto';
  8257. if (typeof styleTokenWidth === 'string' && styleTokenWidth.charAt(styleTokenWidth.length - 1) === '%') {
  8258. token.percentWidth = styleTokenWidth;
  8259. pendingList.push(token);
  8260. token.contentWidth = getWidth(token.text, font);
  8261. }
  8262. else {
  8263. if (tokenWidthNotSpecified) {
  8264. var textBackgroundColor = tokenStyle.backgroundColor;
  8265. var bgImg = textBackgroundColor && textBackgroundColor.image;
  8266. if (bgImg) {
  8267. bgImg = findExistImage(bgImg);
  8268. if (isImageReady(bgImg)) {
  8269. token.width = Math.max(token.width, bgImg.width * tokenHeight / bgImg.height);
  8270. }
  8271. }
  8272. }
  8273. var remainTruncWidth = truncate && topWidth != null
  8274. ? topWidth - lineWidth : null;
  8275. if (remainTruncWidth != null && remainTruncWidth < token.width) {
  8276. if (!tokenWidthNotSpecified || remainTruncWidth < paddingH) {
  8277. token.text = '';
  8278. token.width = token.contentWidth = 0;
  8279. }
  8280. else {
  8281. token.text = truncateText(token.text, remainTruncWidth - paddingH, font, style.ellipsis, { minChar: style.truncateMinChar });
  8282. token.width = token.contentWidth = getWidth(token.text, font);
  8283. }
  8284. }
  8285. else {
  8286. token.contentWidth = getWidth(token.text, font);
  8287. }
  8288. }
  8289. token.width += paddingH;
  8290. lineWidth += token.width;
  8291. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  8292. }
  8293. finishLine(line, lineWidth, lineHeight);
  8294. }
  8295. contentBlock.outerWidth = contentBlock.width = retrieve2(topWidth, calculatedWidth);
  8296. contentBlock.outerHeight = contentBlock.height = retrieve2(topHeight, calculatedHeight);
  8297. contentBlock.contentHeight = calculatedHeight;
  8298. contentBlock.contentWidth = calculatedWidth;
  8299. if (stlPadding) {
  8300. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  8301. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  8302. }
  8303. for (var i = 0; i < pendingList.length; i++) {
  8304. var token = pendingList[i];
  8305. var percentWidth = token.percentWidth;
  8306. token.width = parseInt(percentWidth, 10) / 100 * contentBlock.width;
  8307. }
  8308. return contentBlock;
  8309. }
  8310. function pushTokens(block, str, style, wrapInfo, styleName) {
  8311. var isEmptyStr = str === '';
  8312. var tokenStyle = styleName && style.rich[styleName] || {};
  8313. var lines = block.lines;
  8314. var font = tokenStyle.font || style.font;
  8315. var newLine = false;
  8316. var strLines;
  8317. var linesWidths;
  8318. if (wrapInfo) {
  8319. var tokenPadding = tokenStyle.padding;
  8320. var tokenPaddingH = tokenPadding ? tokenPadding[1] + tokenPadding[3] : 0;
  8321. if (tokenStyle.width != null && tokenStyle.width !== 'auto') {
  8322. var outerWidth_1 = parsePercent$2(tokenStyle.width, wrapInfo.width) + tokenPaddingH;
  8323. if (lines.length > 0) {
  8324. if (outerWidth_1 + wrapInfo.accumWidth > wrapInfo.width) {
  8325. strLines = str.split('\n');
  8326. newLine = true;
  8327. }
  8328. }
  8329. wrapInfo.accumWidth = outerWidth_1;
  8330. }
  8331. else {
  8332. var res = wrapText(str, font, wrapInfo.width, wrapInfo.breakAll, wrapInfo.accumWidth);
  8333. wrapInfo.accumWidth = res.accumWidth + tokenPaddingH;
  8334. linesWidths = res.linesWidths;
  8335. strLines = res.lines;
  8336. }
  8337. }
  8338. else {
  8339. strLines = str.split('\n');
  8340. }
  8341. for (var i = 0; i < strLines.length; i++) {
  8342. var text = strLines[i];
  8343. var token = new RichTextToken();
  8344. token.styleName = styleName;
  8345. token.text = text;
  8346. token.isLineHolder = !text && !isEmptyStr;
  8347. if (typeof tokenStyle.width === 'number') {
  8348. token.width = tokenStyle.width;
  8349. }
  8350. else {
  8351. token.width = linesWidths
  8352. ? linesWidths[i]
  8353. : getWidth(text, font);
  8354. }
  8355. if (!i && !newLine) {
  8356. var tokens = (lines[lines.length - 1] || (lines[0] = new RichTextLine())).tokens;
  8357. var tokensLen = tokens.length;
  8358. (tokensLen === 1 && tokens[0].isLineHolder)
  8359. ? (tokens[0] = token)
  8360. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  8361. }
  8362. else {
  8363. lines.push(new RichTextLine([token]));
  8364. }
  8365. }
  8366. }
  8367. function isLatin(ch) {
  8368. var code = ch.charCodeAt(0);
  8369. return code >= 0x21 && code <= 0xFF;
  8370. }
  8371. var breakCharMap = reduce(',&?/;] '.split(''), function (obj, ch) {
  8372. obj[ch] = true;
  8373. return obj;
  8374. }, {});
  8375. function isWordBreakChar(ch) {
  8376. if (isLatin(ch)) {
  8377. if (breakCharMap[ch]) {
  8378. return true;
  8379. }
  8380. return false;
  8381. }
  8382. return true;
  8383. }
  8384. function wrapText(text, font, lineWidth, isBreakAll, lastAccumWidth) {
  8385. var lines = [];
  8386. var linesWidths = [];
  8387. var line = '';
  8388. var currentWord = '';
  8389. var currentWordWidth = 0;
  8390. var accumWidth = 0;
  8391. for (var i = 0; i < text.length; i++) {
  8392. var ch = text.charAt(i);
  8393. if (ch === '\n') {
  8394. if (currentWord) {
  8395. line += currentWord;
  8396. accumWidth += currentWordWidth;
  8397. }
  8398. lines.push(line);
  8399. linesWidths.push(accumWidth);
  8400. line = '';
  8401. currentWord = '';
  8402. currentWordWidth = 0;
  8403. accumWidth = 0;
  8404. continue;
  8405. }
  8406. var chWidth = getWidth(ch, font);
  8407. var inWord = isBreakAll ? false : !isWordBreakChar(ch);
  8408. if (!lines.length
  8409. ? lastAccumWidth + accumWidth + chWidth > lineWidth
  8410. : accumWidth + chWidth > lineWidth) {
  8411. if (!accumWidth) {
  8412. if (inWord) {
  8413. lines.push(currentWord);
  8414. linesWidths.push(currentWordWidth);
  8415. currentWord = ch;
  8416. currentWordWidth = chWidth;
  8417. }
  8418. else {
  8419. lines.push(ch);
  8420. linesWidths.push(chWidth);
  8421. }
  8422. }
  8423. else if (line || currentWord) {
  8424. if (inWord) {
  8425. if (!line) {
  8426. line = currentWord;
  8427. currentWord = '';
  8428. currentWordWidth = 0;
  8429. accumWidth = currentWordWidth;
  8430. }
  8431. lines.push(line);
  8432. linesWidths.push(accumWidth - currentWordWidth);
  8433. currentWord += ch;
  8434. currentWordWidth += chWidth;
  8435. line = '';
  8436. accumWidth = currentWordWidth;
  8437. }
  8438. else {
  8439. if (currentWord) {
  8440. line += currentWord;
  8441. accumWidth += currentWordWidth;
  8442. currentWord = '';
  8443. currentWordWidth = 0;
  8444. }
  8445. lines.push(line);
  8446. linesWidths.push(accumWidth);
  8447. line = ch;
  8448. accumWidth = chWidth;
  8449. }
  8450. }
  8451. continue;
  8452. }
  8453. accumWidth += chWidth;
  8454. if (inWord) {
  8455. currentWord += ch;
  8456. currentWordWidth += chWidth;
  8457. }
  8458. else {
  8459. if (currentWord) {
  8460. line += currentWord;
  8461. currentWord = '';
  8462. currentWordWidth = 0;
  8463. }
  8464. line += ch;
  8465. }
  8466. }
  8467. if (!lines.length && !line) {
  8468. line = text;
  8469. currentWord = '';
  8470. currentWordWidth = 0;
  8471. }
  8472. if (currentWord) {
  8473. line += currentWord;
  8474. }
  8475. if (line) {
  8476. lines.push(line);
  8477. linesWidths.push(accumWidth);
  8478. }
  8479. if (lines.length === 1) {
  8480. accumWidth += lastAccumWidth;
  8481. }
  8482. return {
  8483. accumWidth: accumWidth,
  8484. lines: lines,
  8485. linesWidths: linesWidths
  8486. };
  8487. }
  8488. function parsePercent$2(value, maxValue) {
  8489. if (typeof value === 'string') {
  8490. if (value.lastIndexOf('%') >= 0) {
  8491. return parseFloat(value) / 100 * maxValue;
  8492. }
  8493. return parseFloat(value);
  8494. }
  8495. return value;
  8496. }
  8497. var STYLE_MAGIC_KEY = '__zr_style_' + Math.round((Math.random() * 10));
  8498. var DEFAULT_COMMON_STYLE = {
  8499. shadowBlur: 0,
  8500. shadowOffsetX: 0,
  8501. shadowOffsetY: 0,
  8502. shadowColor: '#000',
  8503. opacity: 1,
  8504. blend: 'source-over'
  8505. };
  8506. var DEFAULT_COMMON_ANIMATION_PROPS = {
  8507. style: {
  8508. shadowBlur: true,
  8509. shadowOffsetX: true,
  8510. shadowOffsetY: true,
  8511. shadowColor: true,
  8512. opacity: true
  8513. }
  8514. };
  8515. DEFAULT_COMMON_STYLE[STYLE_MAGIC_KEY] = true;
  8516. var PRIMARY_STATES_KEYS$1 = ['z', 'z2', 'invisible'];
  8517. var Displayable = (function (_super) {
  8518. __extends(Displayable, _super);
  8519. function Displayable(props) {
  8520. return _super.call(this, props) || this;
  8521. }
  8522. Displayable.prototype._init = function (props) {
  8523. var keysArr = keys(props);
  8524. for (var i = 0; i < keysArr.length; i++) {
  8525. var key = keysArr[i];
  8526. if (key === 'style') {
  8527. this.useStyle(props[key]);
  8528. }
  8529. else {
  8530. _super.prototype.attrKV.call(this, key, props[key]);
  8531. }
  8532. }
  8533. if (!this.style) {
  8534. this.useStyle({});
  8535. }
  8536. };
  8537. Displayable.prototype.beforeBrush = function () { };
  8538. Displayable.prototype.afterBrush = function () { };
  8539. Displayable.prototype.innerBeforeBrush = function () { };
  8540. Displayable.prototype.innerAfterBrush = function () { };
  8541. Displayable.prototype.shouldBePainted = function (viewWidth, viewHeight, considerClipPath, considerAncestors) {
  8542. var m = this.transform;
  8543. if (this.ignore
  8544. || this.invisible
  8545. || this.style.opacity === 0
  8546. || (this.culling
  8547. && isDisplayableCulled(this, viewWidth, viewHeight))
  8548. || (m && !m[0] && !m[3])) {
  8549. return false;
  8550. }
  8551. if (considerClipPath && this.__clipPaths) {
  8552. for (var i = 0; i < this.__clipPaths.length; ++i) {
  8553. if (this.__clipPaths[i].isZeroArea()) {
  8554. return false;
  8555. }
  8556. }
  8557. }
  8558. if (considerAncestors && this.parent) {
  8559. var parent_1 = this.parent;
  8560. while (parent_1) {
  8561. if (parent_1.ignore) {
  8562. return false;
  8563. }
  8564. parent_1 = parent_1.parent;
  8565. }
  8566. }
  8567. return true;
  8568. };
  8569. Displayable.prototype.contain = function (x, y) {
  8570. return this.rectContain(x, y);
  8571. };
  8572. Displayable.prototype.traverse = function (cb, context) {
  8573. cb.call(context, this);
  8574. };
  8575. Displayable.prototype.rectContain = function (x, y) {
  8576. var coord = this.transformCoordToLocal(x, y);
  8577. var rect = this.getBoundingRect();
  8578. return rect.contain(coord[0], coord[1]);
  8579. };
  8580. Displayable.prototype.getPaintRect = function () {
  8581. var rect = this._paintRect;
  8582. if (!this._paintRect || this.__dirty) {
  8583. var transform = this.transform;
  8584. var elRect = this.getBoundingRect();
  8585. var style = this.style;
  8586. var shadowSize = style.shadowBlur || 0;
  8587. var shadowOffsetX = style.shadowOffsetX || 0;
  8588. var shadowOffsetY = style.shadowOffsetY || 0;
  8589. rect = this._paintRect || (this._paintRect = new BoundingRect(0, 0, 0, 0));
  8590. if (transform) {
  8591. BoundingRect.applyTransform(rect, elRect, transform);
  8592. }
  8593. else {
  8594. rect.copy(elRect);
  8595. }
  8596. if (shadowSize || shadowOffsetX || shadowOffsetY) {
  8597. rect.width += shadowSize * 2 + Math.abs(shadowOffsetX);
  8598. rect.height += shadowSize * 2 + Math.abs(shadowOffsetY);
  8599. rect.x = Math.min(rect.x, rect.x + shadowOffsetX - shadowSize);
  8600. rect.y = Math.min(rect.y, rect.y + shadowOffsetY - shadowSize);
  8601. }
  8602. var tolerance = this.dirtyRectTolerance;
  8603. if (!rect.isZero()) {
  8604. rect.x = Math.floor(rect.x - tolerance);
  8605. rect.y = Math.floor(rect.y - tolerance);
  8606. rect.width = Math.ceil(rect.width + 1 + tolerance * 2);
  8607. rect.height = Math.ceil(rect.height + 1 + tolerance * 2);
  8608. }
  8609. }
  8610. return rect;
  8611. };
  8612. Displayable.prototype.setPrevPaintRect = function (paintRect) {
  8613. if (paintRect) {
  8614. this._prevPaintRect = this._prevPaintRect || new BoundingRect(0, 0, 0, 0);
  8615. this._prevPaintRect.copy(paintRect);
  8616. }
  8617. else {
  8618. this._prevPaintRect = null;
  8619. }
  8620. };
  8621. Displayable.prototype.getPrevPaintRect = function () {
  8622. return this._prevPaintRect;
  8623. };
  8624. Displayable.prototype.animateStyle = function (loop) {
  8625. return this.animate('style', loop);
  8626. };
  8627. Displayable.prototype.updateDuringAnimation = function (targetKey) {
  8628. if (targetKey === 'style') {
  8629. this.dirtyStyle();
  8630. }
  8631. else {
  8632. this.markRedraw();
  8633. }
  8634. };
  8635. Displayable.prototype.attrKV = function (key, value) {
  8636. if (key !== 'style') {
  8637. _super.prototype.attrKV.call(this, key, value);
  8638. }
  8639. else {
  8640. if (!this.style) {
  8641. this.useStyle(value);
  8642. }
  8643. else {
  8644. this.setStyle(value);
  8645. }
  8646. }
  8647. };
  8648. Displayable.prototype.setStyle = function (keyOrObj, value) {
  8649. if (typeof keyOrObj === 'string') {
  8650. this.style[keyOrObj] = value;
  8651. }
  8652. else {
  8653. extend(this.style, keyOrObj);
  8654. }
  8655. this.dirtyStyle();
  8656. return this;
  8657. };
  8658. Displayable.prototype.dirtyStyle = function () {
  8659. this.markRedraw();
  8660. this.__dirty |= Displayable.STYLE_CHANGED_BIT;
  8661. if (this._rect) {
  8662. this._rect = null;
  8663. }
  8664. };
  8665. Displayable.prototype.dirty = function () {
  8666. this.dirtyStyle();
  8667. };
  8668. Displayable.prototype.styleChanged = function () {
  8669. return !!(this.__dirty & Displayable.STYLE_CHANGED_BIT);
  8670. };
  8671. Displayable.prototype.styleUpdated = function () {
  8672. this.__dirty &= ~Displayable.STYLE_CHANGED_BIT;
  8673. };
  8674. Displayable.prototype.createStyle = function (obj) {
  8675. return createObject(DEFAULT_COMMON_STYLE, obj);
  8676. };
  8677. Displayable.prototype.useStyle = function (obj) {
  8678. if (!obj[STYLE_MAGIC_KEY]) {
  8679. obj = this.createStyle(obj);
  8680. }
  8681. if (this.__inHover) {
  8682. this.__hoverStyle = obj;
  8683. }
  8684. else {
  8685. this.style = obj;
  8686. }
  8687. this.dirtyStyle();
  8688. };
  8689. Displayable.prototype.isStyleObject = function (obj) {
  8690. return obj[STYLE_MAGIC_KEY];
  8691. };
  8692. Displayable.prototype._innerSaveToNormal = function (toState) {
  8693. _super.prototype._innerSaveToNormal.call(this, toState);
  8694. var normalState = this._normalState;
  8695. if (toState.style && !normalState.style) {
  8696. normalState.style = this._mergeStyle(this.createStyle(), this.style);
  8697. }
  8698. this._savePrimaryToNormal(toState, normalState, PRIMARY_STATES_KEYS$1);
  8699. };
  8700. Displayable.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  8701. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  8702. var needsRestoreToNormal = !(state && keepCurrentStates);
  8703. var targetStyle;
  8704. if (state && state.style) {
  8705. if (transition) {
  8706. if (keepCurrentStates) {
  8707. targetStyle = state.style;
  8708. }
  8709. else {
  8710. targetStyle = this._mergeStyle(this.createStyle(), normalState.style);
  8711. this._mergeStyle(targetStyle, state.style);
  8712. }
  8713. }
  8714. else {
  8715. targetStyle = this._mergeStyle(this.createStyle(), keepCurrentStates ? this.style : normalState.style);
  8716. this._mergeStyle(targetStyle, state.style);
  8717. }
  8718. }
  8719. else if (needsRestoreToNormal) {
  8720. targetStyle = normalState.style;
  8721. }
  8722. if (targetStyle) {
  8723. if (transition) {
  8724. var sourceStyle = this.style;
  8725. this.style = this.createStyle(needsRestoreToNormal ? {} : sourceStyle);
  8726. if (needsRestoreToNormal) {
  8727. var changedKeys = keys(sourceStyle);
  8728. for (var i = 0; i < changedKeys.length; i++) {
  8729. var key = changedKeys[i];
  8730. if (key in targetStyle) {
  8731. targetStyle[key] = targetStyle[key];
  8732. this.style[key] = sourceStyle[key];
  8733. }
  8734. }
  8735. }
  8736. var targetKeys = keys(targetStyle);
  8737. for (var i = 0; i < targetKeys.length; i++) {
  8738. var key = targetKeys[i];
  8739. this.style[key] = this.style[key];
  8740. }
  8741. this._transitionState(stateName, {
  8742. style: targetStyle
  8743. }, animationCfg, this.getAnimationStyleProps());
  8744. }
  8745. else {
  8746. this.useStyle(targetStyle);
  8747. }
  8748. }
  8749. for (var i = 0; i < PRIMARY_STATES_KEYS$1.length; i++) {
  8750. var key = PRIMARY_STATES_KEYS$1[i];
  8751. if (state && state[key] != null) {
  8752. this[key] = state[key];
  8753. }
  8754. else if (needsRestoreToNormal) {
  8755. if (normalState[key] != null) {
  8756. this[key] = normalState[key];
  8757. }
  8758. }
  8759. }
  8760. };
  8761. Displayable.prototype._mergeStates = function (states) {
  8762. var mergedState = _super.prototype._mergeStates.call(this, states);
  8763. var mergedStyle;
  8764. for (var i = 0; i < states.length; i++) {
  8765. var state = states[i];
  8766. if (state.style) {
  8767. mergedStyle = mergedStyle || {};
  8768. this._mergeStyle(mergedStyle, state.style);
  8769. }
  8770. }
  8771. if (mergedStyle) {
  8772. mergedState.style = mergedStyle;
  8773. }
  8774. return mergedState;
  8775. };
  8776. Displayable.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  8777. extend(targetStyle, sourceStyle);
  8778. return targetStyle;
  8779. };
  8780. Displayable.prototype.getAnimationStyleProps = function () {
  8781. return DEFAULT_COMMON_ANIMATION_PROPS;
  8782. };
  8783. Displayable.STYLE_CHANGED_BIT = 2;
  8784. Displayable.initDefaultProps = (function () {
  8785. var dispProto = Displayable.prototype;
  8786. dispProto.type = 'displayable';
  8787. dispProto.invisible = false;
  8788. dispProto.z = 0;
  8789. dispProto.z2 = 0;
  8790. dispProto.zlevel = 0;
  8791. dispProto.culling = false;
  8792. dispProto.cursor = 'pointer';
  8793. dispProto.rectHover = false;
  8794. dispProto.incremental = false;
  8795. dispProto._rect = null;
  8796. dispProto.dirtyRectTolerance = 0;
  8797. dispProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT;
  8798. })();
  8799. return Displayable;
  8800. }(Element));
  8801. var tmpRect = new BoundingRect(0, 0, 0, 0);
  8802. var viewRect = new BoundingRect(0, 0, 0, 0);
  8803. function isDisplayableCulled(el, width, height) {
  8804. tmpRect.copy(el.getBoundingRect());
  8805. if (el.transform) {
  8806. tmpRect.applyTransform(el.transform);
  8807. }
  8808. viewRect.width = width;
  8809. viewRect.height = height;
  8810. return !tmpRect.intersect(viewRect);
  8811. }
  8812. var mathPow = Math.pow;
  8813. var mathSqrt = Math.sqrt;
  8814. var EPSILON$1 = 1e-8;
  8815. var EPSILON_NUMERIC = 1e-4;
  8816. var THREE_SQRT = mathSqrt(3);
  8817. var ONE_THIRD = 1 / 3;
  8818. var _v0 = create();
  8819. var _v1 = create();
  8820. var _v2 = create();
  8821. function isAroundZero(val) {
  8822. return val > -EPSILON$1 && val < EPSILON$1;
  8823. }
  8824. function isNotAroundZero$1(val) {
  8825. return val > EPSILON$1 || val < -EPSILON$1;
  8826. }
  8827. function cubicAt(p0, p1, p2, p3, t) {
  8828. var onet = 1 - t;
  8829. return onet * onet * (onet * p0 + 3 * t * p1)
  8830. + t * t * (t * p3 + 3 * onet * p2);
  8831. }
  8832. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  8833. var onet = 1 - t;
  8834. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  8835. + (p3 - p2) * t * t);
  8836. }
  8837. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  8838. var a = p3 + 3 * (p1 - p2) - p0;
  8839. var b = 3 * (p2 - p1 * 2 + p0);
  8840. var c = 3 * (p1 - p0);
  8841. var d = p0 - val;
  8842. var A = b * b - 3 * a * c;
  8843. var B = b * c - 9 * a * d;
  8844. var C = c * c - 3 * b * d;
  8845. var n = 0;
  8846. if (isAroundZero(A) && isAroundZero(B)) {
  8847. if (isAroundZero(b)) {
  8848. roots[0] = 0;
  8849. }
  8850. else {
  8851. var t1 = -c / b;
  8852. if (t1 >= 0 && t1 <= 1) {
  8853. roots[n++] = t1;
  8854. }
  8855. }
  8856. }
  8857. else {
  8858. var disc = B * B - 4 * A * C;
  8859. if (isAroundZero(disc)) {
  8860. var K = B / A;
  8861. var t1 = -b / a + K;
  8862. var t2 = -K / 2;
  8863. if (t1 >= 0 && t1 <= 1) {
  8864. roots[n++] = t1;
  8865. }
  8866. if (t2 >= 0 && t2 <= 1) {
  8867. roots[n++] = t2;
  8868. }
  8869. }
  8870. else if (disc > 0) {
  8871. var discSqrt = mathSqrt(disc);
  8872. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  8873. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  8874. if (Y1 < 0) {
  8875. Y1 = -mathPow(-Y1, ONE_THIRD);
  8876. }
  8877. else {
  8878. Y1 = mathPow(Y1, ONE_THIRD);
  8879. }
  8880. if (Y2 < 0) {
  8881. Y2 = -mathPow(-Y2, ONE_THIRD);
  8882. }
  8883. else {
  8884. Y2 = mathPow(Y2, ONE_THIRD);
  8885. }
  8886. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  8887. if (t1 >= 0 && t1 <= 1) {
  8888. roots[n++] = t1;
  8889. }
  8890. }
  8891. else {
  8892. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt(A * A * A));
  8893. var theta = Math.acos(T) / 3;
  8894. var ASqrt = mathSqrt(A);
  8895. var tmp = Math.cos(theta);
  8896. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  8897. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  8898. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  8899. if (t1 >= 0 && t1 <= 1) {
  8900. roots[n++] = t1;
  8901. }
  8902. if (t2 >= 0 && t2 <= 1) {
  8903. roots[n++] = t2;
  8904. }
  8905. if (t3 >= 0 && t3 <= 1) {
  8906. roots[n++] = t3;
  8907. }
  8908. }
  8909. }
  8910. return n;
  8911. }
  8912. function cubicExtrema(p0, p1, p2, p3, extrema) {
  8913. var b = 6 * p2 - 12 * p1 + 6 * p0;
  8914. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  8915. var c = 3 * p1 - 3 * p0;
  8916. var n = 0;
  8917. if (isAroundZero(a)) {
  8918. if (isNotAroundZero$1(b)) {
  8919. var t1 = -c / b;
  8920. if (t1 >= 0 && t1 <= 1) {
  8921. extrema[n++] = t1;
  8922. }
  8923. }
  8924. }
  8925. else {
  8926. var disc = b * b - 4 * a * c;
  8927. if (isAroundZero(disc)) {
  8928. extrema[0] = -b / (2 * a);
  8929. }
  8930. else if (disc > 0) {
  8931. var discSqrt = mathSqrt(disc);
  8932. var t1 = (-b + discSqrt) / (2 * a);
  8933. var t2 = (-b - discSqrt) / (2 * a);
  8934. if (t1 >= 0 && t1 <= 1) {
  8935. extrema[n++] = t1;
  8936. }
  8937. if (t2 >= 0 && t2 <= 1) {
  8938. extrema[n++] = t2;
  8939. }
  8940. }
  8941. }
  8942. return n;
  8943. }
  8944. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  8945. var p01 = (p1 - p0) * t + p0;
  8946. var p12 = (p2 - p1) * t + p1;
  8947. var p23 = (p3 - p2) * t + p2;
  8948. var p012 = (p12 - p01) * t + p01;
  8949. var p123 = (p23 - p12) * t + p12;
  8950. var p0123 = (p123 - p012) * t + p012;
  8951. out[0] = p0;
  8952. out[1] = p01;
  8953. out[2] = p012;
  8954. out[3] = p0123;
  8955. out[4] = p0123;
  8956. out[5] = p123;
  8957. out[6] = p23;
  8958. out[7] = p3;
  8959. }
  8960. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  8961. var t;
  8962. var interval = 0.005;
  8963. var d = Infinity;
  8964. var prev;
  8965. var next;
  8966. var d1;
  8967. var d2;
  8968. _v0[0] = x;
  8969. _v0[1] = y;
  8970. for (var _t = 0; _t < 1; _t += 0.05) {
  8971. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  8972. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  8973. d1 = distSquare(_v0, _v1);
  8974. if (d1 < d) {
  8975. t = _t;
  8976. d = d1;
  8977. }
  8978. }
  8979. d = Infinity;
  8980. for (var i = 0; i < 32; i++) {
  8981. if (interval < EPSILON_NUMERIC) {
  8982. break;
  8983. }
  8984. prev = t - interval;
  8985. next = t + interval;
  8986. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  8987. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  8988. d1 = distSquare(_v1, _v0);
  8989. if (prev >= 0 && d1 < d) {
  8990. t = prev;
  8991. d = d1;
  8992. }
  8993. else {
  8994. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  8995. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  8996. d2 = distSquare(_v2, _v0);
  8997. if (next <= 1 && d2 < d) {
  8998. t = next;
  8999. d = d2;
  9000. }
  9001. else {
  9002. interval *= 0.5;
  9003. }
  9004. }
  9005. }
  9006. if (out) {
  9007. out[0] = cubicAt(x0, x1, x2, x3, t);
  9008. out[1] = cubicAt(y0, y1, y2, y3, t);
  9009. }
  9010. return mathSqrt(d);
  9011. }
  9012. function cubicLength(x0, y0, x1, y1, x2, y2, x3, y3, iteration) {
  9013. var px = x0;
  9014. var py = y0;
  9015. var d = 0;
  9016. var step = 1 / iteration;
  9017. for (var i = 1; i <= iteration; i++) {
  9018. var t = i * step;
  9019. var x = cubicAt(x0, x1, x2, x3, t);
  9020. var y = cubicAt(y0, y1, y2, y3, t);
  9021. var dx = x - px;
  9022. var dy = y - py;
  9023. d += Math.sqrt(dx * dx + dy * dy);
  9024. px = x;
  9025. py = y;
  9026. }
  9027. return d;
  9028. }
  9029. function quadraticAt(p0, p1, p2, t) {
  9030. var onet = 1 - t;
  9031. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  9032. }
  9033. function quadraticDerivativeAt(p0, p1, p2, t) {
  9034. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  9035. }
  9036. function quadraticRootAt(p0, p1, p2, val, roots) {
  9037. var a = p0 - 2 * p1 + p2;
  9038. var b = 2 * (p1 - p0);
  9039. var c = p0 - val;
  9040. var n = 0;
  9041. if (isAroundZero(a)) {
  9042. if (isNotAroundZero$1(b)) {
  9043. var t1 = -c / b;
  9044. if (t1 >= 0 && t1 <= 1) {
  9045. roots[n++] = t1;
  9046. }
  9047. }
  9048. }
  9049. else {
  9050. var disc = b * b - 4 * a * c;
  9051. if (isAroundZero(disc)) {
  9052. var t1 = -b / (2 * a);
  9053. if (t1 >= 0 && t1 <= 1) {
  9054. roots[n++] = t1;
  9055. }
  9056. }
  9057. else if (disc > 0) {
  9058. var discSqrt = mathSqrt(disc);
  9059. var t1 = (-b + discSqrt) / (2 * a);
  9060. var t2 = (-b - discSqrt) / (2 * a);
  9061. if (t1 >= 0 && t1 <= 1) {
  9062. roots[n++] = t1;
  9063. }
  9064. if (t2 >= 0 && t2 <= 1) {
  9065. roots[n++] = t2;
  9066. }
  9067. }
  9068. }
  9069. return n;
  9070. }
  9071. function quadraticExtremum(p0, p1, p2) {
  9072. var divider = p0 + p2 - 2 * p1;
  9073. if (divider === 0) {
  9074. return 0.5;
  9075. }
  9076. else {
  9077. return (p0 - p1) / divider;
  9078. }
  9079. }
  9080. function quadraticSubdivide(p0, p1, p2, t, out) {
  9081. var p01 = (p1 - p0) * t + p0;
  9082. var p12 = (p2 - p1) * t + p1;
  9083. var p012 = (p12 - p01) * t + p01;
  9084. out[0] = p0;
  9085. out[1] = p01;
  9086. out[2] = p012;
  9087. out[3] = p012;
  9088. out[4] = p12;
  9089. out[5] = p2;
  9090. }
  9091. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  9092. var t;
  9093. var interval = 0.005;
  9094. var d = Infinity;
  9095. _v0[0] = x;
  9096. _v0[1] = y;
  9097. for (var _t = 0; _t < 1; _t += 0.05) {
  9098. _v1[0] = quadraticAt(x0, x1, x2, _t);
  9099. _v1[1] = quadraticAt(y0, y1, y2, _t);
  9100. var d1 = distSquare(_v0, _v1);
  9101. if (d1 < d) {
  9102. t = _t;
  9103. d = d1;
  9104. }
  9105. }
  9106. d = Infinity;
  9107. for (var i = 0; i < 32; i++) {
  9108. if (interval < EPSILON_NUMERIC) {
  9109. break;
  9110. }
  9111. var prev = t - interval;
  9112. var next = t + interval;
  9113. _v1[0] = quadraticAt(x0, x1, x2, prev);
  9114. _v1[1] = quadraticAt(y0, y1, y2, prev);
  9115. var d1 = distSquare(_v1, _v0);
  9116. if (prev >= 0 && d1 < d) {
  9117. t = prev;
  9118. d = d1;
  9119. }
  9120. else {
  9121. _v2[0] = quadraticAt(x0, x1, x2, next);
  9122. _v2[1] = quadraticAt(y0, y1, y2, next);
  9123. var d2 = distSquare(_v2, _v0);
  9124. if (next <= 1 && d2 < d) {
  9125. t = next;
  9126. d = d2;
  9127. }
  9128. else {
  9129. interval *= 0.5;
  9130. }
  9131. }
  9132. }
  9133. if (out) {
  9134. out[0] = quadraticAt(x0, x1, x2, t);
  9135. out[1] = quadraticAt(y0, y1, y2, t);
  9136. }
  9137. return mathSqrt(d);
  9138. }
  9139. function quadraticLength(x0, y0, x1, y1, x2, y2, iteration) {
  9140. var px = x0;
  9141. var py = y0;
  9142. var d = 0;
  9143. var step = 1 / iteration;
  9144. for (var i = 1; i <= iteration; i++) {
  9145. var t = i * step;
  9146. var x = quadraticAt(x0, x1, x2, t);
  9147. var y = quadraticAt(y0, y1, y2, t);
  9148. var dx = x - px;
  9149. var dy = y - py;
  9150. d += Math.sqrt(dx * dx + dy * dy);
  9151. px = x;
  9152. py = y;
  9153. }
  9154. return d;
  9155. }
  9156. var mathMin$1 = Math.min;
  9157. var mathMax$1 = Math.max;
  9158. var mathSin = Math.sin;
  9159. var mathCos = Math.cos;
  9160. var PI2 = Math.PI * 2;
  9161. var start = create();
  9162. var end = create();
  9163. var extremity = create();
  9164. function fromPoints(points, min, max) {
  9165. if (points.length === 0) {
  9166. return;
  9167. }
  9168. var p = points[0];
  9169. var left = p[0];
  9170. var right = p[0];
  9171. var top = p[1];
  9172. var bottom = p[1];
  9173. for (var i = 1; i < points.length; i++) {
  9174. p = points[i];
  9175. left = mathMin$1(left, p[0]);
  9176. right = mathMax$1(right, p[0]);
  9177. top = mathMin$1(top, p[1]);
  9178. bottom = mathMax$1(bottom, p[1]);
  9179. }
  9180. min[0] = left;
  9181. min[1] = top;
  9182. max[0] = right;
  9183. max[1] = bottom;
  9184. }
  9185. function fromLine(x0, y0, x1, y1, min, max) {
  9186. min[0] = mathMin$1(x0, x1);
  9187. min[1] = mathMin$1(y0, y1);
  9188. max[0] = mathMax$1(x0, x1);
  9189. max[1] = mathMax$1(y0, y1);
  9190. }
  9191. var xDim = [];
  9192. var yDim = [];
  9193. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min, max) {
  9194. var cubicExtrema$1 = cubicExtrema;
  9195. var cubicAt$1 = cubicAt;
  9196. var n = cubicExtrema$1(x0, x1, x2, x3, xDim);
  9197. min[0] = Infinity;
  9198. min[1] = Infinity;
  9199. max[0] = -Infinity;
  9200. max[1] = -Infinity;
  9201. for (var i = 0; i < n; i++) {
  9202. var x = cubicAt$1(x0, x1, x2, x3, xDim[i]);
  9203. min[0] = mathMin$1(x, min[0]);
  9204. max[0] = mathMax$1(x, max[0]);
  9205. }
  9206. n = cubicExtrema$1(y0, y1, y2, y3, yDim);
  9207. for (var i = 0; i < n; i++) {
  9208. var y = cubicAt$1(y0, y1, y2, y3, yDim[i]);
  9209. min[1] = mathMin$1(y, min[1]);
  9210. max[1] = mathMax$1(y, max[1]);
  9211. }
  9212. min[0] = mathMin$1(x0, min[0]);
  9213. max[0] = mathMax$1(x0, max[0]);
  9214. min[0] = mathMin$1(x3, min[0]);
  9215. max[0] = mathMax$1(x3, max[0]);
  9216. min[1] = mathMin$1(y0, min[1]);
  9217. max[1] = mathMax$1(y0, max[1]);
  9218. min[1] = mathMin$1(y3, min[1]);
  9219. max[1] = mathMax$1(y3, max[1]);
  9220. }
  9221. function fromQuadratic(x0, y0, x1, y1, x2, y2, min, max) {
  9222. var quadraticExtremum$1 = quadraticExtremum;
  9223. var quadraticAt$1 = quadraticAt;
  9224. var tx = mathMax$1(mathMin$1(quadraticExtremum$1(x0, x1, x2), 1), 0);
  9225. var ty = mathMax$1(mathMin$1(quadraticExtremum$1(y0, y1, y2), 1), 0);
  9226. var x = quadraticAt$1(x0, x1, x2, tx);
  9227. var y = quadraticAt$1(y0, y1, y2, ty);
  9228. min[0] = mathMin$1(x0, x2, x);
  9229. min[1] = mathMin$1(y0, y2, y);
  9230. max[0] = mathMax$1(x0, x2, x);
  9231. max[1] = mathMax$1(y0, y2, y);
  9232. }
  9233. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$1, max$1) {
  9234. var vec2Min = min;
  9235. var vec2Max = max;
  9236. var diff = Math.abs(startAngle - endAngle);
  9237. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  9238. min$1[0] = x - rx;
  9239. min$1[1] = y - ry;
  9240. max$1[0] = x + rx;
  9241. max$1[1] = y + ry;
  9242. return;
  9243. }
  9244. start[0] = mathCos(startAngle) * rx + x;
  9245. start[1] = mathSin(startAngle) * ry + y;
  9246. end[0] = mathCos(endAngle) * rx + x;
  9247. end[1] = mathSin(endAngle) * ry + y;
  9248. vec2Min(min$1, start, end);
  9249. vec2Max(max$1, start, end);
  9250. startAngle = startAngle % (PI2);
  9251. if (startAngle < 0) {
  9252. startAngle = startAngle + PI2;
  9253. }
  9254. endAngle = endAngle % (PI2);
  9255. if (endAngle < 0) {
  9256. endAngle = endAngle + PI2;
  9257. }
  9258. if (startAngle > endAngle && !anticlockwise) {
  9259. endAngle += PI2;
  9260. }
  9261. else if (startAngle < endAngle && anticlockwise) {
  9262. startAngle += PI2;
  9263. }
  9264. if (anticlockwise) {
  9265. var tmp = endAngle;
  9266. endAngle = startAngle;
  9267. startAngle = tmp;
  9268. }
  9269. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  9270. if (angle > startAngle) {
  9271. extremity[0] = mathCos(angle) * rx + x;
  9272. extremity[1] = mathSin(angle) * ry + y;
  9273. vec2Min(min$1, extremity, min$1);
  9274. vec2Max(max$1, extremity, max$1);
  9275. }
  9276. }
  9277. }
  9278. var CMD = {
  9279. M: 1,
  9280. L: 2,
  9281. C: 3,
  9282. Q: 4,
  9283. A: 5,
  9284. Z: 6,
  9285. R: 7
  9286. };
  9287. var tmpOutX = [];
  9288. var tmpOutY = [];
  9289. var min$1 = [];
  9290. var max$1 = [];
  9291. var min2 = [];
  9292. var max2 = [];
  9293. var mathMin$2 = Math.min;
  9294. var mathMax$2 = Math.max;
  9295. var mathCos$1 = Math.cos;
  9296. var mathSin$1 = Math.sin;
  9297. var mathSqrt$1 = Math.sqrt;
  9298. var mathAbs = Math.abs;
  9299. var PI = Math.PI;
  9300. var PI2$1 = PI * 2;
  9301. var hasTypedArray = typeof Float32Array !== 'undefined';
  9302. var tmpAngles = [];
  9303. function modPI2(radian) {
  9304. var n = Math.round(radian / PI * 1e8) / 1e8;
  9305. return (n % 2) * PI;
  9306. }
  9307. function normalizeArcAngles(angles, anticlockwise) {
  9308. var newStartAngle = modPI2(angles[0]);
  9309. if (newStartAngle < 0) {
  9310. newStartAngle += PI2$1;
  9311. }
  9312. var delta = newStartAngle - angles[0];
  9313. var newEndAngle = angles[1];
  9314. newEndAngle += delta;
  9315. if (!anticlockwise && newEndAngle - newStartAngle >= PI2$1) {
  9316. newEndAngle = newStartAngle + PI2$1;
  9317. }
  9318. else if (anticlockwise && newStartAngle - newEndAngle >= PI2$1) {
  9319. newEndAngle = newStartAngle - PI2$1;
  9320. }
  9321. else if (!anticlockwise && newStartAngle > newEndAngle) {
  9322. newEndAngle = newStartAngle +
  9323. (PI2$1 - modPI2(newStartAngle - newEndAngle));
  9324. }
  9325. else if (anticlockwise && newStartAngle < newEndAngle) {
  9326. newEndAngle = newStartAngle -
  9327. (PI2$1 - modPI2(newEndAngle - newStartAngle));
  9328. }
  9329. angles[0] = newStartAngle;
  9330. angles[1] = newEndAngle;
  9331. }
  9332. var PathProxy = (function () {
  9333. function PathProxy(notSaveData) {
  9334. this.dpr = 1;
  9335. this._version = 0;
  9336. this._xi = 0;
  9337. this._yi = 0;
  9338. this._x0 = 0;
  9339. this._y0 = 0;
  9340. this._len = 0;
  9341. if (notSaveData) {
  9342. this._saveData = false;
  9343. }
  9344. if (this._saveData) {
  9345. this.data = [];
  9346. }
  9347. }
  9348. PathProxy.prototype.increaseVersion = function () {
  9349. this._version++;
  9350. };
  9351. PathProxy.prototype.getVersion = function () {
  9352. return this._version;
  9353. };
  9354. PathProxy.prototype.setScale = function (sx, sy, segmentIgnoreThreshold) {
  9355. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  9356. if (segmentIgnoreThreshold > 0) {
  9357. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  9358. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  9359. }
  9360. };
  9361. PathProxy.prototype.setDPR = function (dpr) {
  9362. this.dpr = dpr;
  9363. };
  9364. PathProxy.prototype.setContext = function (ctx) {
  9365. this._ctx = ctx;
  9366. };
  9367. PathProxy.prototype.getContext = function () {
  9368. return this._ctx;
  9369. };
  9370. PathProxy.prototype.beginPath = function () {
  9371. this._ctx && this._ctx.beginPath();
  9372. this.reset();
  9373. return this;
  9374. };
  9375. PathProxy.prototype.reset = function () {
  9376. if (this._saveData) {
  9377. this._len = 0;
  9378. }
  9379. if (this._lineDash) {
  9380. this._lineDash = null;
  9381. this._dashOffset = 0;
  9382. }
  9383. if (this._pathSegLen) {
  9384. this._pathSegLen = null;
  9385. this._pathLen = 0;
  9386. }
  9387. this._version++;
  9388. };
  9389. PathProxy.prototype.moveTo = function (x, y) {
  9390. this.addData(CMD.M, x, y);
  9391. this._ctx && this._ctx.moveTo(x, y);
  9392. this._x0 = x;
  9393. this._y0 = y;
  9394. this._xi = x;
  9395. this._yi = y;
  9396. return this;
  9397. };
  9398. PathProxy.prototype.lineTo = function (x, y) {
  9399. var exceedUnit = mathAbs(x - this._xi) > this._ux
  9400. || mathAbs(y - this._yi) > this._uy
  9401. || this._len < 5;
  9402. this.addData(CMD.L, x, y);
  9403. if (this._ctx && exceedUnit) {
  9404. this._needsDash ? this._dashedLineTo(x, y)
  9405. : this._ctx.lineTo(x, y);
  9406. }
  9407. if (exceedUnit) {
  9408. this._xi = x;
  9409. this._yi = y;
  9410. }
  9411. return this;
  9412. };
  9413. PathProxy.prototype.bezierCurveTo = function (x1, y1, x2, y2, x3, y3) {
  9414. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  9415. if (this._ctx) {
  9416. this._needsDash ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  9417. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9418. }
  9419. this._xi = x3;
  9420. this._yi = y3;
  9421. return this;
  9422. };
  9423. PathProxy.prototype.quadraticCurveTo = function (x1, y1, x2, y2) {
  9424. this.addData(CMD.Q, x1, y1, x2, y2);
  9425. if (this._ctx) {
  9426. this._needsDash ? this._dashedQuadraticTo(x1, y1, x2, y2)
  9427. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  9428. }
  9429. this._xi = x2;
  9430. this._yi = y2;
  9431. return this;
  9432. };
  9433. PathProxy.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  9434. tmpAngles[0] = startAngle;
  9435. tmpAngles[1] = endAngle;
  9436. normalizeArcAngles(tmpAngles, anticlockwise);
  9437. startAngle = tmpAngles[0];
  9438. endAngle = tmpAngles[1];
  9439. var delta = endAngle - startAngle;
  9440. this.addData(CMD.A, cx, cy, r, r, startAngle, delta, 0, anticlockwise ? 0 : 1);
  9441. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9442. this._xi = mathCos$1(endAngle) * r + cx;
  9443. this._yi = mathSin$1(endAngle) * r + cy;
  9444. return this;
  9445. };
  9446. PathProxy.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  9447. if (this._ctx) {
  9448. this._ctx.arcTo(x1, y1, x2, y2, radius);
  9449. }
  9450. return this;
  9451. };
  9452. PathProxy.prototype.rect = function (x, y, w, h) {
  9453. this._ctx && this._ctx.rect(x, y, w, h);
  9454. this.addData(CMD.R, x, y, w, h);
  9455. return this;
  9456. };
  9457. PathProxy.prototype.closePath = function () {
  9458. this.addData(CMD.Z);
  9459. var ctx = this._ctx;
  9460. var x0 = this._x0;
  9461. var y0 = this._y0;
  9462. if (ctx) {
  9463. this._needsDash && this._dashedLineTo(x0, y0);
  9464. ctx.closePath();
  9465. }
  9466. this._xi = x0;
  9467. this._yi = y0;
  9468. return this;
  9469. };
  9470. PathProxy.prototype.fill = function (ctx) {
  9471. ctx && ctx.fill();
  9472. this.toStatic();
  9473. };
  9474. PathProxy.prototype.stroke = function (ctx) {
  9475. ctx && ctx.stroke();
  9476. this.toStatic();
  9477. };
  9478. PathProxy.prototype.setLineDash = function (lineDash) {
  9479. if (lineDash instanceof Array) {
  9480. this._lineDash = lineDash;
  9481. this._dashIdx = 0;
  9482. var lineDashSum = 0;
  9483. for (var i = 0; i < lineDash.length; i++) {
  9484. lineDashSum += lineDash[i];
  9485. }
  9486. this._dashSum = lineDashSum;
  9487. this._needsDash = true;
  9488. }
  9489. else {
  9490. this._lineDash = null;
  9491. this._needsDash = false;
  9492. }
  9493. return this;
  9494. };
  9495. PathProxy.prototype.setLineDashOffset = function (offset) {
  9496. this._dashOffset = offset;
  9497. return this;
  9498. };
  9499. PathProxy.prototype.len = function () {
  9500. return this._len;
  9501. };
  9502. PathProxy.prototype.setData = function (data) {
  9503. var len = data.length;
  9504. if (!(this.data && this.data.length === len) && hasTypedArray) {
  9505. this.data = new Float32Array(len);
  9506. }
  9507. for (var i = 0; i < len; i++) {
  9508. this.data[i] = data[i];
  9509. }
  9510. this._len = len;
  9511. };
  9512. PathProxy.prototype.appendPath = function (path) {
  9513. if (!(path instanceof Array)) {
  9514. path = [path];
  9515. }
  9516. var len = path.length;
  9517. var appendSize = 0;
  9518. var offset = this._len;
  9519. for (var i = 0; i < len; i++) {
  9520. appendSize += path[i].len();
  9521. }
  9522. if (hasTypedArray && (this.data instanceof Float32Array)) {
  9523. this.data = new Float32Array(offset + appendSize);
  9524. }
  9525. for (var i = 0; i < len; i++) {
  9526. var appendPathData = path[i].data;
  9527. for (var k = 0; k < appendPathData.length; k++) {
  9528. this.data[offset++] = appendPathData[k];
  9529. }
  9530. }
  9531. this._len = offset;
  9532. };
  9533. PathProxy.prototype.addData = function (cmd, a, b, c, d, e, f, g, h) {
  9534. if (!this._saveData) {
  9535. return;
  9536. }
  9537. var data = this.data;
  9538. if (this._len + arguments.length > data.length) {
  9539. this._expandData();
  9540. data = this.data;
  9541. }
  9542. for (var i = 0; i < arguments.length; i++) {
  9543. data[this._len++] = arguments[i];
  9544. }
  9545. };
  9546. PathProxy.prototype._expandData = function () {
  9547. if (!(this.data instanceof Array)) {
  9548. var newData = [];
  9549. for (var i = 0; i < this._len; i++) {
  9550. newData[i] = this.data[i];
  9551. }
  9552. this.data = newData;
  9553. }
  9554. };
  9555. PathProxy.prototype._dashedLineTo = function (x1, y1) {
  9556. var dashSum = this._dashSum;
  9557. var lineDash = this._lineDash;
  9558. var ctx = this._ctx;
  9559. var offset = this._dashOffset;
  9560. var x0 = this._xi;
  9561. var y0 = this._yi;
  9562. var dx = x1 - x0;
  9563. var dy = y1 - y0;
  9564. var dist = mathSqrt$1(dx * dx + dy * dy);
  9565. var x = x0;
  9566. var y = y0;
  9567. var nDash = lineDash.length;
  9568. var dash;
  9569. var idx;
  9570. dx /= dist;
  9571. dy /= dist;
  9572. if (offset < 0) {
  9573. offset = dashSum + offset;
  9574. }
  9575. offset %= dashSum;
  9576. x -= offset * dx;
  9577. y -= offset * dy;
  9578. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  9579. || (dx === 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  9580. idx = this._dashIdx;
  9581. dash = lineDash[idx];
  9582. x += dx * dash;
  9583. y += dy * dash;
  9584. this._dashIdx = (idx + 1) % nDash;
  9585. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  9586. continue;
  9587. }
  9588. ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1));
  9589. }
  9590. dx = x - x1;
  9591. dy = y - y1;
  9592. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9593. };
  9594. PathProxy.prototype._dashedBezierTo = function (x1, y1, x2, y2, x3, y3) {
  9595. var ctx = this._ctx;
  9596. var dashSum = this._dashSum;
  9597. var offset = this._dashOffset;
  9598. var lineDash = this._lineDash;
  9599. var x0 = this._xi;
  9600. var y0 = this._yi;
  9601. var bezierLen = 0;
  9602. var idx = this._dashIdx;
  9603. var nDash = lineDash.length;
  9604. var t;
  9605. var dx;
  9606. var dy;
  9607. var x;
  9608. var y;
  9609. var tmpLen = 0;
  9610. if (offset < 0) {
  9611. offset = dashSum + offset;
  9612. }
  9613. offset %= dashSum;
  9614. for (t = 0; t < 1; t += 0.1) {
  9615. dx = cubicAt(x0, x1, x2, x3, t + 0.1)
  9616. - cubicAt(x0, x1, x2, x3, t);
  9617. dy = cubicAt(y0, y1, y2, y3, t + 0.1)
  9618. - cubicAt(y0, y1, y2, y3, t);
  9619. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  9620. }
  9621. for (; idx < nDash; idx++) {
  9622. tmpLen += lineDash[idx];
  9623. if (tmpLen > offset) {
  9624. break;
  9625. }
  9626. }
  9627. t = (tmpLen - offset) / bezierLen;
  9628. while (t <= 1) {
  9629. x = cubicAt(x0, x1, x2, x3, t);
  9630. y = cubicAt(y0, y1, y2, y3, t);
  9631. idx % 2 ? ctx.moveTo(x, y)
  9632. : ctx.lineTo(x, y);
  9633. t += lineDash[idx] / bezierLen;
  9634. idx = (idx + 1) % nDash;
  9635. }
  9636. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  9637. dx = x3 - x;
  9638. dy = y3 - y;
  9639. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  9640. };
  9641. PathProxy.prototype._dashedQuadraticTo = function (x1, y1, x2, y2) {
  9642. var x3 = x2;
  9643. var y3 = y2;
  9644. x2 = (x2 + 2 * x1) / 3;
  9645. y2 = (y2 + 2 * y1) / 3;
  9646. x1 = (this._xi + 2 * x1) / 3;
  9647. y1 = (this._yi + 2 * y1) / 3;
  9648. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  9649. };
  9650. PathProxy.prototype.toStatic = function () {
  9651. if (!this._saveData) {
  9652. return;
  9653. }
  9654. var data = this.data;
  9655. if (data instanceof Array) {
  9656. data.length = this._len;
  9657. if (hasTypedArray && this._len > 11) {
  9658. this.data = new Float32Array(data);
  9659. }
  9660. }
  9661. };
  9662. PathProxy.prototype.getBoundingRect = function () {
  9663. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  9664. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  9665. var data = this.data;
  9666. var xi = 0;
  9667. var yi = 0;
  9668. var x0 = 0;
  9669. var y0 = 0;
  9670. var i;
  9671. for (i = 0; i < this._len;) {
  9672. var cmd = data[i++];
  9673. var isFirst = i === 1;
  9674. if (isFirst) {
  9675. xi = data[i];
  9676. yi = data[i + 1];
  9677. x0 = xi;
  9678. y0 = yi;
  9679. }
  9680. switch (cmd) {
  9681. case CMD.M:
  9682. xi = x0 = data[i++];
  9683. yi = y0 = data[i++];
  9684. min2[0] = x0;
  9685. min2[1] = y0;
  9686. max2[0] = x0;
  9687. max2[1] = y0;
  9688. break;
  9689. case CMD.L:
  9690. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  9691. xi = data[i++];
  9692. yi = data[i++];
  9693. break;
  9694. case CMD.C:
  9695. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9696. xi = data[i++];
  9697. yi = data[i++];
  9698. break;
  9699. case CMD.Q:
  9700. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  9701. xi = data[i++];
  9702. yi = data[i++];
  9703. break;
  9704. case CMD.A:
  9705. var cx = data[i++];
  9706. var cy = data[i++];
  9707. var rx = data[i++];
  9708. var ry = data[i++];
  9709. var startAngle = data[i++];
  9710. var endAngle = data[i++] + startAngle;
  9711. i += 1;
  9712. var anticlockwise = !data[i++];
  9713. if (isFirst) {
  9714. x0 = mathCos$1(startAngle) * rx + cx;
  9715. y0 = mathSin$1(startAngle) * ry + cy;
  9716. }
  9717. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  9718. xi = mathCos$1(endAngle) * rx + cx;
  9719. yi = mathSin$1(endAngle) * ry + cy;
  9720. break;
  9721. case CMD.R:
  9722. x0 = xi = data[i++];
  9723. y0 = yi = data[i++];
  9724. var width = data[i++];
  9725. var height = data[i++];
  9726. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  9727. break;
  9728. case CMD.Z:
  9729. xi = x0;
  9730. yi = y0;
  9731. break;
  9732. }
  9733. min(min$1, min$1, min2);
  9734. max(max$1, max$1, max2);
  9735. }
  9736. if (i === 0) {
  9737. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  9738. }
  9739. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  9740. };
  9741. PathProxy.prototype._calculateLength = function () {
  9742. var data = this.data;
  9743. var len = this._len;
  9744. var ux = this._ux;
  9745. var uy = this._uy;
  9746. var xi = 0;
  9747. var yi = 0;
  9748. var x0 = 0;
  9749. var y0 = 0;
  9750. if (!this._pathSegLen) {
  9751. this._pathSegLen = [];
  9752. }
  9753. var pathSegLen = this._pathSegLen;
  9754. var pathTotalLen = 0;
  9755. var segCount = 0;
  9756. for (var i = 0; i < len;) {
  9757. var cmd = data[i++];
  9758. var isFirst = i === 1;
  9759. if (isFirst) {
  9760. xi = data[i];
  9761. yi = data[i + 1];
  9762. x0 = xi;
  9763. y0 = yi;
  9764. }
  9765. var l = -1;
  9766. switch (cmd) {
  9767. case CMD.M:
  9768. xi = x0 = data[i++];
  9769. yi = y0 = data[i++];
  9770. break;
  9771. case CMD.L: {
  9772. var x2 = data[i++];
  9773. var y2 = data[i++];
  9774. var dx = x2 - xi;
  9775. var dy = y2 - yi;
  9776. if (mathAbs(dx) > ux || mathAbs(dy) > uy || i === len - 1) {
  9777. l = Math.sqrt(dx * dx + dy * dy);
  9778. xi = x2;
  9779. yi = y2;
  9780. }
  9781. break;
  9782. }
  9783. case CMD.C: {
  9784. var x1 = data[i++];
  9785. var y1 = data[i++];
  9786. var x2 = data[i++];
  9787. var y2 = data[i++];
  9788. var x3 = data[i++];
  9789. var y3 = data[i++];
  9790. l = cubicLength(xi, yi, x1, y1, x2, y2, x3, y3, 10);
  9791. xi = x3;
  9792. yi = y3;
  9793. break;
  9794. }
  9795. case CMD.Q: {
  9796. var x1 = data[i++];
  9797. var y1 = data[i++];
  9798. var x2 = data[i++];
  9799. var y2 = data[i++];
  9800. l = quadraticLength(xi, yi, x1, y1, x2, y2, 10);
  9801. xi = x2;
  9802. yi = y2;
  9803. break;
  9804. }
  9805. case CMD.A:
  9806. var cx = data[i++];
  9807. var cy = data[i++];
  9808. var rx = data[i++];
  9809. var ry = data[i++];
  9810. var startAngle = data[i++];
  9811. var delta = data[i++];
  9812. var endAngle = delta + startAngle;
  9813. i += 1;
  9814. var anticlockwise = !data[i++];
  9815. if (isFirst) {
  9816. x0 = mathCos$1(startAngle) * rx + cx;
  9817. y0 = mathSin$1(startAngle) * ry + cy;
  9818. }
  9819. l = mathMax$2(rx, ry) * mathMin$2(PI2$1, Math.abs(delta));
  9820. xi = mathCos$1(endAngle) * rx + cx;
  9821. yi = mathSin$1(endAngle) * ry + cy;
  9822. break;
  9823. case CMD.R: {
  9824. x0 = xi = data[i++];
  9825. y0 = yi = data[i++];
  9826. var width = data[i++];
  9827. var height = data[i++];
  9828. l = width * 2 + height * 2;
  9829. break;
  9830. }
  9831. case CMD.Z: {
  9832. var dx = x0 - xi;
  9833. var dy = y0 - yi;
  9834. l = Math.sqrt(dx * dx + dy * dy);
  9835. xi = x0;
  9836. yi = y0;
  9837. break;
  9838. }
  9839. }
  9840. if (l >= 0) {
  9841. pathSegLen[segCount++] = l;
  9842. pathTotalLen += l;
  9843. }
  9844. }
  9845. this._pathLen = pathTotalLen;
  9846. return pathTotalLen;
  9847. };
  9848. PathProxy.prototype.rebuildPath = function (ctx, percent) {
  9849. var d = this.data;
  9850. var ux = this._ux;
  9851. var uy = this._uy;
  9852. var len = this._len;
  9853. var x0;
  9854. var y0;
  9855. var xi;
  9856. var yi;
  9857. var x;
  9858. var y;
  9859. var drawPart = percent < 1;
  9860. var pathSegLen;
  9861. var pathTotalLen;
  9862. var accumLength = 0;
  9863. var segCount = 0;
  9864. var displayedLength;
  9865. if (drawPart) {
  9866. if (!this._pathSegLen) {
  9867. this._calculateLength();
  9868. }
  9869. pathSegLen = this._pathSegLen;
  9870. pathTotalLen = this._pathLen;
  9871. displayedLength = percent * pathTotalLen;
  9872. if (!displayedLength) {
  9873. return;
  9874. }
  9875. }
  9876. lo: for (var i = 0; i < len;) {
  9877. var cmd = d[i++];
  9878. var isFirst = i === 1;
  9879. if (isFirst) {
  9880. xi = d[i];
  9881. yi = d[i + 1];
  9882. x0 = xi;
  9883. y0 = yi;
  9884. }
  9885. switch (cmd) {
  9886. case CMD.M:
  9887. x0 = xi = d[i++];
  9888. y0 = yi = d[i++];
  9889. ctx.moveTo(xi, yi);
  9890. break;
  9891. case CMD.L: {
  9892. x = d[i++];
  9893. y = d[i++];
  9894. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len - 1) {
  9895. if (drawPart) {
  9896. var l = pathSegLen[segCount++];
  9897. if (accumLength + l > displayedLength) {
  9898. var t = (displayedLength - accumLength) / l;
  9899. ctx.lineTo(xi * (1 - t) + x * t, yi * (1 - t) + y * t);
  9900. break lo;
  9901. }
  9902. accumLength += l;
  9903. }
  9904. ctx.lineTo(x, y);
  9905. xi = x;
  9906. yi = y;
  9907. }
  9908. break;
  9909. }
  9910. case CMD.C: {
  9911. var x1 = d[i++];
  9912. var y1 = d[i++];
  9913. var x2 = d[i++];
  9914. var y2 = d[i++];
  9915. var x3 = d[i++];
  9916. var y3 = d[i++];
  9917. if (drawPart) {
  9918. var l = pathSegLen[segCount++];
  9919. if (accumLength + l > displayedLength) {
  9920. var t = (displayedLength - accumLength) / l;
  9921. cubicSubdivide(xi, x1, x2, x3, t, tmpOutX);
  9922. cubicSubdivide(yi, y1, y2, y3, t, tmpOutY);
  9923. ctx.bezierCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2], tmpOutX[3], tmpOutY[3]);
  9924. break lo;
  9925. }
  9926. accumLength += l;
  9927. }
  9928. ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  9929. xi = x3;
  9930. yi = y3;
  9931. break;
  9932. }
  9933. case CMD.Q: {
  9934. var x1 = d[i++];
  9935. var y1 = d[i++];
  9936. var x2 = d[i++];
  9937. var y2 = d[i++];
  9938. if (drawPart) {
  9939. var l = pathSegLen[segCount++];
  9940. if (accumLength + l > displayedLength) {
  9941. var t = (displayedLength - accumLength) / l;
  9942. quadraticSubdivide(xi, x1, x2, t, tmpOutX);
  9943. quadraticSubdivide(yi, y1, y2, t, tmpOutY);
  9944. ctx.quadraticCurveTo(tmpOutX[1], tmpOutY[1], tmpOutX[2], tmpOutY[2]);
  9945. break lo;
  9946. }
  9947. accumLength += l;
  9948. }
  9949. ctx.quadraticCurveTo(x1, y1, x2, y2);
  9950. xi = x2;
  9951. yi = y2;
  9952. break;
  9953. }
  9954. case CMD.A:
  9955. var cx = d[i++];
  9956. var cy = d[i++];
  9957. var rx = d[i++];
  9958. var ry = d[i++];
  9959. var startAngle = d[i++];
  9960. var delta = d[i++];
  9961. var psi = d[i++];
  9962. var anticlockwise = !d[i++];
  9963. var r = (rx > ry) ? rx : ry;
  9964. var isEllipse = mathAbs(rx - ry) > 1e-3;
  9965. var endAngle = startAngle + delta;
  9966. var breakBuild = false;
  9967. if (drawPart) {
  9968. var l = pathSegLen[segCount++];
  9969. if (accumLength + l > displayedLength) {
  9970. endAngle = startAngle + delta * (displayedLength - accumLength) / l;
  9971. breakBuild = true;
  9972. }
  9973. accumLength += l;
  9974. }
  9975. if (isEllipse && ctx.ellipse) {
  9976. ctx.ellipse(cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise);
  9977. }
  9978. else {
  9979. ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  9980. }
  9981. if (breakBuild) {
  9982. break lo;
  9983. }
  9984. if (isFirst) {
  9985. x0 = mathCos$1(startAngle) * rx + cx;
  9986. y0 = mathSin$1(startAngle) * ry + cy;
  9987. }
  9988. xi = mathCos$1(endAngle) * rx + cx;
  9989. yi = mathSin$1(endAngle) * ry + cy;
  9990. break;
  9991. case CMD.R:
  9992. x0 = xi = d[i];
  9993. y0 = yi = d[i + 1];
  9994. x = d[i++];
  9995. y = d[i++];
  9996. var width = d[i++];
  9997. var height = d[i++];
  9998. if (drawPart) {
  9999. var l = pathSegLen[segCount++];
  10000. if (accumLength + l > displayedLength) {
  10001. var d_1 = displayedLength - accumLength;
  10002. ctx.moveTo(x, y);
  10003. ctx.lineTo(x + mathMin$2(d_1, width), y);
  10004. d_1 -= width;
  10005. if (d_1 > 0) {
  10006. ctx.lineTo(x + width, y + mathMin$2(d_1, height));
  10007. }
  10008. d_1 -= height;
  10009. if (d_1 > 0) {
  10010. ctx.lineTo(x + mathMax$2(width - d_1, 0), y + height);
  10011. }
  10012. d_1 -= width;
  10013. if (d_1 > 0) {
  10014. ctx.lineTo(x, y + mathMax$2(height - d_1, 0));
  10015. }
  10016. break lo;
  10017. }
  10018. accumLength += l;
  10019. }
  10020. ctx.rect(x, y, width, height);
  10021. break;
  10022. case CMD.Z:
  10023. if (drawPart) {
  10024. var l = pathSegLen[segCount++];
  10025. if (accumLength + l > displayedLength) {
  10026. var t = (displayedLength - accumLength) / l;
  10027. ctx.lineTo(xi * (1 - t) + x0 * t, yi * (1 - t) + y0 * t);
  10028. break lo;
  10029. }
  10030. accumLength += l;
  10031. }
  10032. ctx.closePath();
  10033. xi = x0;
  10034. yi = y0;
  10035. }
  10036. }
  10037. };
  10038. PathProxy.CMD = CMD;
  10039. PathProxy.initDefaultProps = (function () {
  10040. var proto = PathProxy.prototype;
  10041. proto._saveData = true;
  10042. proto._needsDash = false;
  10043. proto._dashOffset = 0;
  10044. proto._dashIdx = 0;
  10045. proto._dashSum = 0;
  10046. proto._ux = 0;
  10047. proto._uy = 0;
  10048. })();
  10049. return PathProxy;
  10050. }());
  10051. function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
  10052. if (lineWidth === 0) {
  10053. return false;
  10054. }
  10055. var _l = lineWidth;
  10056. var _a = 0;
  10057. var _b = x0;
  10058. if ((y > y0 + _l && y > y1 + _l)
  10059. || (y < y0 - _l && y < y1 - _l)
  10060. || (x > x0 + _l && x > x1 + _l)
  10061. || (x < x0 - _l && x < x1 - _l)) {
  10062. return false;
  10063. }
  10064. if (x0 !== x1) {
  10065. _a = (y0 - y1) / (x0 - x1);
  10066. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  10067. }
  10068. else {
  10069. return Math.abs(x - x0) <= _l / 2;
  10070. }
  10071. var tmp = _a * x - y + _b;
  10072. var _s = tmp * tmp / (_a * _a + 1);
  10073. return _s <= _l / 2 * _l / 2;
  10074. }
  10075. function containStroke$1(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  10076. if (lineWidth === 0) {
  10077. return false;
  10078. }
  10079. var _l = lineWidth;
  10080. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  10081. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  10082. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  10083. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)) {
  10084. return false;
  10085. }
  10086. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  10087. return d <= _l / 2;
  10088. }
  10089. function containStroke$2(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  10090. if (lineWidth === 0) {
  10091. return false;
  10092. }
  10093. var _l = lineWidth;
  10094. if ((y > y0 + _l && y > y1 + _l && y > y2 + _l)
  10095. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  10096. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  10097. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)) {
  10098. return false;
  10099. }
  10100. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  10101. return d <= _l / 2;
  10102. }
  10103. var PI2$2 = Math.PI * 2;
  10104. function normalizeRadian(angle) {
  10105. angle %= PI2$2;
  10106. if (angle < 0) {
  10107. angle += PI2$2;
  10108. }
  10109. return angle;
  10110. }
  10111. var PI2$3 = Math.PI * 2;
  10112. function containStroke$3(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  10113. if (lineWidth === 0) {
  10114. return false;
  10115. }
  10116. var _l = lineWidth;
  10117. x -= cx;
  10118. y -= cy;
  10119. var d = Math.sqrt(x * x + y * y);
  10120. if ((d - _l > r) || (d + _l < r)) {
  10121. return false;
  10122. }
  10123. if (Math.abs(startAngle - endAngle) % PI2$3 < 1e-4) {
  10124. return true;
  10125. }
  10126. if (anticlockwise) {
  10127. var tmp = startAngle;
  10128. startAngle = normalizeRadian(endAngle);
  10129. endAngle = normalizeRadian(tmp);
  10130. }
  10131. else {
  10132. startAngle = normalizeRadian(startAngle);
  10133. endAngle = normalizeRadian(endAngle);
  10134. }
  10135. if (startAngle > endAngle) {
  10136. endAngle += PI2$3;
  10137. }
  10138. var angle = Math.atan2(y, x);
  10139. if (angle < 0) {
  10140. angle += PI2$3;
  10141. }
  10142. return (angle >= startAngle && angle <= endAngle)
  10143. || (angle + PI2$3 >= startAngle && angle + PI2$3 <= endAngle);
  10144. }
  10145. function windingLine(x0, y0, x1, y1, x, y) {
  10146. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  10147. return 0;
  10148. }
  10149. if (y1 === y0) {
  10150. return 0;
  10151. }
  10152. var t = (y - y0) / (y1 - y0);
  10153. var dir = y1 < y0 ? 1 : -1;
  10154. if (t === 1 || t === 0) {
  10155. dir = y1 < y0 ? 0.5 : -0.5;
  10156. }
  10157. var x_ = t * (x1 - x0) + x0;
  10158. return x_ === x ? Infinity : x_ > x ? dir : 0;
  10159. }
  10160. var CMD$1 = PathProxy.CMD;
  10161. var PI2$4 = Math.PI * 2;
  10162. var EPSILON$2 = 1e-4;
  10163. function isAroundEqual(a, b) {
  10164. return Math.abs(a - b) < EPSILON$2;
  10165. }
  10166. var roots = [-1, -1, -1];
  10167. var extrema = [-1, -1];
  10168. function swapExtrema() {
  10169. var tmp = extrema[0];
  10170. extrema[0] = extrema[1];
  10171. extrema[1] = tmp;
  10172. }
  10173. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  10174. if ((y > y0 && y > y1 && y > y2 && y > y3)
  10175. || (y < y0 && y < y1 && y < y2 && y < y3)) {
  10176. return 0;
  10177. }
  10178. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  10179. if (nRoots === 0) {
  10180. return 0;
  10181. }
  10182. else {
  10183. var w = 0;
  10184. var nExtrema = -1;
  10185. var y0_ = void 0;
  10186. var y1_ = void 0;
  10187. for (var i = 0; i < nRoots; i++) {
  10188. var t = roots[i];
  10189. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  10190. var x_ = cubicAt(x0, x1, x2, x3, t);
  10191. if (x_ < x) {
  10192. continue;
  10193. }
  10194. if (nExtrema < 0) {
  10195. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  10196. if (extrema[1] < extrema[0] && nExtrema > 1) {
  10197. swapExtrema();
  10198. }
  10199. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  10200. if (nExtrema > 1) {
  10201. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  10202. }
  10203. }
  10204. if (nExtrema === 2) {
  10205. if (t < extrema[0]) {
  10206. w += y0_ < y0 ? unit : -unit;
  10207. }
  10208. else if (t < extrema[1]) {
  10209. w += y1_ < y0_ ? unit : -unit;
  10210. }
  10211. else {
  10212. w += y3 < y1_ ? unit : -unit;
  10213. }
  10214. }
  10215. else {
  10216. if (t < extrema[0]) {
  10217. w += y0_ < y0 ? unit : -unit;
  10218. }
  10219. else {
  10220. w += y3 < y0_ ? unit : -unit;
  10221. }
  10222. }
  10223. }
  10224. return w;
  10225. }
  10226. }
  10227. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  10228. if ((y > y0 && y > y1 && y > y2)
  10229. || (y < y0 && y < y1 && y < y2)) {
  10230. return 0;
  10231. }
  10232. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  10233. if (nRoots === 0) {
  10234. return 0;
  10235. }
  10236. else {
  10237. var t = quadraticExtremum(y0, y1, y2);
  10238. if (t >= 0 && t <= 1) {
  10239. var w = 0;
  10240. var y_ = quadraticAt(y0, y1, y2, t);
  10241. for (var i = 0; i < nRoots; i++) {
  10242. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  10243. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  10244. if (x_ < x) {
  10245. continue;
  10246. }
  10247. if (roots[i] < t) {
  10248. w += y_ < y0 ? unit : -unit;
  10249. }
  10250. else {
  10251. w += y2 < y_ ? unit : -unit;
  10252. }
  10253. }
  10254. return w;
  10255. }
  10256. else {
  10257. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  10258. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  10259. if (x_ < x) {
  10260. return 0;
  10261. }
  10262. return y2 < y0 ? unit : -unit;
  10263. }
  10264. }
  10265. }
  10266. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  10267. y -= cy;
  10268. if (y > r || y < -r) {
  10269. return 0;
  10270. }
  10271. var tmp = Math.sqrt(r * r - y * y);
  10272. roots[0] = -tmp;
  10273. roots[1] = tmp;
  10274. var dTheta = Math.abs(startAngle - endAngle);
  10275. if (dTheta < 1e-4) {
  10276. return 0;
  10277. }
  10278. if (dTheta >= PI2$4 - 1e-4) {
  10279. startAngle = 0;
  10280. endAngle = PI2$4;
  10281. var dir = anticlockwise ? 1 : -1;
  10282. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  10283. return dir;
  10284. }
  10285. else {
  10286. return 0;
  10287. }
  10288. }
  10289. if (startAngle > endAngle) {
  10290. var tmp_1 = startAngle;
  10291. startAngle = endAngle;
  10292. endAngle = tmp_1;
  10293. }
  10294. if (startAngle < 0) {
  10295. startAngle += PI2$4;
  10296. endAngle += PI2$4;
  10297. }
  10298. var w = 0;
  10299. for (var i = 0; i < 2; i++) {
  10300. var x_ = roots[i];
  10301. if (x_ + cx > x) {
  10302. var angle = Math.atan2(y, x_);
  10303. var dir = anticlockwise ? 1 : -1;
  10304. if (angle < 0) {
  10305. angle = PI2$4 + angle;
  10306. }
  10307. if ((angle >= startAngle && angle <= endAngle)
  10308. || (angle + PI2$4 >= startAngle && angle + PI2$4 <= endAngle)) {
  10309. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  10310. dir = -dir;
  10311. }
  10312. w += dir;
  10313. }
  10314. }
  10315. }
  10316. return w;
  10317. }
  10318. function containPath(path, lineWidth, isStroke, x, y) {
  10319. var data = path.data;
  10320. var len = path.len();
  10321. var w = 0;
  10322. var xi = 0;
  10323. var yi = 0;
  10324. var x0 = 0;
  10325. var y0 = 0;
  10326. var x1;
  10327. var y1;
  10328. for (var i = 0; i < len;) {
  10329. var cmd = data[i++];
  10330. var isFirst = i === 1;
  10331. if (cmd === CMD$1.M && i > 1) {
  10332. if (!isStroke) {
  10333. w += windingLine(xi, yi, x0, y0, x, y);
  10334. }
  10335. }
  10336. if (isFirst) {
  10337. xi = data[i];
  10338. yi = data[i + 1];
  10339. x0 = xi;
  10340. y0 = yi;
  10341. }
  10342. switch (cmd) {
  10343. case CMD$1.M:
  10344. x0 = data[i++];
  10345. y0 = data[i++];
  10346. xi = x0;
  10347. yi = y0;
  10348. break;
  10349. case CMD$1.L:
  10350. if (isStroke) {
  10351. if (containStroke(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  10352. return true;
  10353. }
  10354. }
  10355. else {
  10356. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  10357. }
  10358. xi = data[i++];
  10359. yi = data[i++];
  10360. break;
  10361. case CMD$1.C:
  10362. if (isStroke) {
  10363. if (containStroke$1(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10364. return true;
  10365. }
  10366. }
  10367. else {
  10368. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10369. }
  10370. xi = data[i++];
  10371. yi = data[i++];
  10372. break;
  10373. case CMD$1.Q:
  10374. if (isStroke) {
  10375. if (containStroke$2(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  10376. return true;
  10377. }
  10378. }
  10379. else {
  10380. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  10381. }
  10382. xi = data[i++];
  10383. yi = data[i++];
  10384. break;
  10385. case CMD$1.A:
  10386. var cx = data[i++];
  10387. var cy = data[i++];
  10388. var rx = data[i++];
  10389. var ry = data[i++];
  10390. var theta = data[i++];
  10391. var dTheta = data[i++];
  10392. i += 1;
  10393. var anticlockwise = !!(1 - data[i++]);
  10394. x1 = Math.cos(theta) * rx + cx;
  10395. y1 = Math.sin(theta) * ry + cy;
  10396. if (!isFirst) {
  10397. w += windingLine(xi, yi, x1, y1, x, y);
  10398. }
  10399. else {
  10400. x0 = x1;
  10401. y0 = y1;
  10402. }
  10403. var _x = (x - cx) * ry / rx + cx;
  10404. if (isStroke) {
  10405. if (containStroke$3(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  10406. return true;
  10407. }
  10408. }
  10409. else {
  10410. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  10411. }
  10412. xi = Math.cos(theta + dTheta) * rx + cx;
  10413. yi = Math.sin(theta + dTheta) * ry + cy;
  10414. break;
  10415. case CMD$1.R:
  10416. x0 = xi = data[i++];
  10417. y0 = yi = data[i++];
  10418. var width = data[i++];
  10419. var height = data[i++];
  10420. x1 = x0 + width;
  10421. y1 = y0 + height;
  10422. if (isStroke) {
  10423. if (containStroke(x0, y0, x1, y0, lineWidth, x, y)
  10424. || containStroke(x1, y0, x1, y1, lineWidth, x, y)
  10425. || containStroke(x1, y1, x0, y1, lineWidth, x, y)
  10426. || containStroke(x0, y1, x0, y0, lineWidth, x, y)) {
  10427. return true;
  10428. }
  10429. }
  10430. else {
  10431. w += windingLine(x1, y0, x1, y1, x, y);
  10432. w += windingLine(x0, y1, x0, y0, x, y);
  10433. }
  10434. break;
  10435. case CMD$1.Z:
  10436. if (isStroke) {
  10437. if (containStroke(xi, yi, x0, y0, lineWidth, x, y)) {
  10438. return true;
  10439. }
  10440. }
  10441. else {
  10442. w += windingLine(xi, yi, x0, y0, x, y);
  10443. }
  10444. xi = x0;
  10445. yi = y0;
  10446. break;
  10447. }
  10448. }
  10449. if (!isStroke && !isAroundEqual(yi, y0)) {
  10450. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  10451. }
  10452. return w !== 0;
  10453. }
  10454. function contain(pathProxy, x, y) {
  10455. return containPath(pathProxy, 0, false, x, y);
  10456. }
  10457. function containStroke$4(pathProxy, lineWidth, x, y) {
  10458. return containPath(pathProxy, lineWidth, true, x, y);
  10459. }
  10460. var DEFAULT_PATH_STYLE = defaults({
  10461. fill: '#000',
  10462. stroke: null,
  10463. strokePercent: 1,
  10464. fillOpacity: 1,
  10465. strokeOpacity: 1,
  10466. lineDashOffset: 0,
  10467. lineWidth: 1,
  10468. lineCap: 'butt',
  10469. miterLimit: 10,
  10470. strokeNoScale: false,
  10471. strokeFirst: false
  10472. }, DEFAULT_COMMON_STYLE);
  10473. var DEFAULT_PATH_ANIMATION_PROPS = {
  10474. style: defaults({
  10475. fill: true,
  10476. stroke: true,
  10477. strokePercent: true,
  10478. fillOpacity: true,
  10479. strokeOpacity: true,
  10480. lineDashOffset: true,
  10481. lineWidth: true,
  10482. miterLimit: true
  10483. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10484. };
  10485. var pathCopyParams = [
  10486. 'x', 'y', 'rotation', 'scaleX', 'scaleY', 'originX', 'originY', 'invisible',
  10487. 'culling', 'z', 'z2', 'zlevel', 'parent'
  10488. ];
  10489. var Path = (function (_super) {
  10490. __extends(Path, _super);
  10491. function Path(opts) {
  10492. return _super.call(this, opts) || this;
  10493. }
  10494. Path.prototype.update = function () {
  10495. var _this = this;
  10496. _super.prototype.update.call(this);
  10497. var style = this.style;
  10498. if (style.decal) {
  10499. var decalEl = this._decalEl
  10500. = this._decalEl || new Path();
  10501. if (decalEl.buildPath === Path.prototype.buildPath) {
  10502. decalEl.buildPath = function (ctx) {
  10503. _this.buildPath(ctx, _this.shape);
  10504. };
  10505. }
  10506. decalEl.silent = true;
  10507. var decalElStyle = decalEl.style;
  10508. for (var key in style) {
  10509. if (decalElStyle[key] !== style[key]) {
  10510. decalElStyle[key] = style[key];
  10511. }
  10512. }
  10513. decalElStyle.fill = style.fill ? style.decal : null;
  10514. decalElStyle.decal = null;
  10515. decalElStyle.shadowColor = null;
  10516. style.strokeFirst && (decalElStyle.stroke = null);
  10517. for (var i = 0; i < pathCopyParams.length; ++i) {
  10518. decalEl[pathCopyParams[i]] = this[pathCopyParams[i]];
  10519. }
  10520. decalEl.__dirty |= Element.REDARAW_BIT;
  10521. }
  10522. else if (this._decalEl) {
  10523. this._decalEl = null;
  10524. }
  10525. };
  10526. Path.prototype.getDecalElement = function () {
  10527. return this._decalEl;
  10528. };
  10529. Path.prototype._init = function (props) {
  10530. var keysArr = keys(props);
  10531. this.shape = this.getDefaultShape();
  10532. var defaultStyle = this.getDefaultStyle();
  10533. if (defaultStyle) {
  10534. this.useStyle(defaultStyle);
  10535. }
  10536. for (var i = 0; i < keysArr.length; i++) {
  10537. var key = keysArr[i];
  10538. var value = props[key];
  10539. if (key === 'style') {
  10540. if (!this.style) {
  10541. this.useStyle(value);
  10542. }
  10543. else {
  10544. extend(this.style, value);
  10545. }
  10546. }
  10547. else if (key === 'shape') {
  10548. extend(this.shape, value);
  10549. }
  10550. else {
  10551. _super.prototype.attrKV.call(this, key, value);
  10552. }
  10553. }
  10554. if (!this.style) {
  10555. this.useStyle({});
  10556. }
  10557. };
  10558. Path.prototype.getDefaultStyle = function () {
  10559. return null;
  10560. };
  10561. Path.prototype.getDefaultShape = function () {
  10562. return {};
  10563. };
  10564. Path.prototype.canBeInsideText = function () {
  10565. return this.hasFill();
  10566. };
  10567. Path.prototype.getInsideTextFill = function () {
  10568. var pathFill = this.style.fill;
  10569. if (pathFill !== 'none') {
  10570. if (isString(pathFill)) {
  10571. var fillLum = lum(pathFill, 0);
  10572. if (fillLum > 0.5) {
  10573. return DARK_LABEL_COLOR;
  10574. }
  10575. else if (fillLum > 0.2) {
  10576. return LIGHTER_LABEL_COLOR;
  10577. }
  10578. return LIGHT_LABEL_COLOR;
  10579. }
  10580. else if (pathFill) {
  10581. return LIGHT_LABEL_COLOR;
  10582. }
  10583. }
  10584. return DARK_LABEL_COLOR;
  10585. };
  10586. Path.prototype.getInsideTextStroke = function (textFill) {
  10587. var pathFill = this.style.fill;
  10588. if (isString(pathFill)) {
  10589. var zr = this.__zr;
  10590. var isDarkMode = !!(zr && zr.isDarkMode());
  10591. var isDarkLabel = lum(textFill, 0) < DARK_MODE_THRESHOLD;
  10592. if (isDarkMode === isDarkLabel) {
  10593. return pathFill;
  10594. }
  10595. }
  10596. };
  10597. Path.prototype.buildPath = function (ctx, shapeCfg, inBundle) { };
  10598. Path.prototype.pathUpdated = function () {
  10599. this.__dirty &= ~Path.SHAPE_CHANGED_BIT;
  10600. };
  10601. Path.prototype.createPathProxy = function () {
  10602. this.path = new PathProxy(false);
  10603. };
  10604. Path.prototype.hasStroke = function () {
  10605. var style = this.style;
  10606. var stroke = style.stroke;
  10607. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  10608. };
  10609. Path.prototype.hasFill = function () {
  10610. var style = this.style;
  10611. var fill = style.fill;
  10612. return fill != null && fill !== 'none';
  10613. };
  10614. Path.prototype.getBoundingRect = function () {
  10615. var rect = this._rect;
  10616. var style = this.style;
  10617. var needsUpdateRect = !rect;
  10618. if (needsUpdateRect) {
  10619. var firstInvoke = false;
  10620. if (!this.path) {
  10621. firstInvoke = true;
  10622. this.createPathProxy();
  10623. }
  10624. var path = this.path;
  10625. if (firstInvoke || (this.__dirty & Path.SHAPE_CHANGED_BIT)) {
  10626. path.beginPath();
  10627. this.buildPath(path, this.shape, false);
  10628. this.pathUpdated();
  10629. }
  10630. rect = path.getBoundingRect();
  10631. }
  10632. this._rect = rect;
  10633. if (this.hasStroke() && this.path && this.path.len() > 0) {
  10634. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  10635. if (this.__dirty || needsUpdateRect) {
  10636. rectWithStroke.copy(rect);
  10637. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10638. var w = style.lineWidth;
  10639. if (!this.hasFill()) {
  10640. var strokeContainThreshold = this.strokeContainThreshold;
  10641. w = Math.max(w, strokeContainThreshold == null ? 4 : strokeContainThreshold);
  10642. }
  10643. if (lineScale > 1e-10) {
  10644. rectWithStroke.width += w / lineScale;
  10645. rectWithStroke.height += w / lineScale;
  10646. rectWithStroke.x -= w / lineScale / 2;
  10647. rectWithStroke.y -= w / lineScale / 2;
  10648. }
  10649. }
  10650. return rectWithStroke;
  10651. }
  10652. return rect;
  10653. };
  10654. Path.prototype.contain = function (x, y) {
  10655. var localPos = this.transformCoordToLocal(x, y);
  10656. var rect = this.getBoundingRect();
  10657. var style = this.style;
  10658. x = localPos[0];
  10659. y = localPos[1];
  10660. if (rect.contain(x, y)) {
  10661. var pathProxy = this.path;
  10662. if (this.hasStroke()) {
  10663. var lineWidth = style.lineWidth;
  10664. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  10665. if (lineScale > 1e-10) {
  10666. if (!this.hasFill()) {
  10667. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  10668. }
  10669. if (containStroke$4(pathProxy, lineWidth / lineScale, x, y)) {
  10670. return true;
  10671. }
  10672. }
  10673. }
  10674. if (this.hasFill()) {
  10675. return contain(pathProxy, x, y);
  10676. }
  10677. }
  10678. return false;
  10679. };
  10680. Path.prototype.dirtyShape = function () {
  10681. this.__dirty |= Path.SHAPE_CHANGED_BIT;
  10682. if (this._rect) {
  10683. this._rect = null;
  10684. }
  10685. if (this._decalEl) {
  10686. this._decalEl.dirtyShape();
  10687. }
  10688. this.markRedraw();
  10689. };
  10690. Path.prototype.dirty = function () {
  10691. this.dirtyStyle();
  10692. this.dirtyShape();
  10693. };
  10694. Path.prototype.animateShape = function (loop) {
  10695. return this.animate('shape', loop);
  10696. };
  10697. Path.prototype.updateDuringAnimation = function (targetKey) {
  10698. if (targetKey === 'style') {
  10699. this.dirtyStyle();
  10700. }
  10701. else if (targetKey === 'shape') {
  10702. this.dirtyShape();
  10703. }
  10704. else {
  10705. this.markRedraw();
  10706. }
  10707. };
  10708. Path.prototype.attrKV = function (key, value) {
  10709. if (key === 'shape') {
  10710. this.setShape(value);
  10711. }
  10712. else {
  10713. _super.prototype.attrKV.call(this, key, value);
  10714. }
  10715. };
  10716. Path.prototype.setShape = function (keyOrObj, value) {
  10717. var shape = this.shape;
  10718. if (!shape) {
  10719. shape = this.shape = {};
  10720. }
  10721. if (typeof keyOrObj === 'string') {
  10722. shape[keyOrObj] = value;
  10723. }
  10724. else {
  10725. extend(shape, keyOrObj);
  10726. }
  10727. this.dirtyShape();
  10728. return this;
  10729. };
  10730. Path.prototype.shapeChanged = function () {
  10731. return !!(this.__dirty & Path.SHAPE_CHANGED_BIT);
  10732. };
  10733. Path.prototype.createStyle = function (obj) {
  10734. return createObject(DEFAULT_PATH_STYLE, obj);
  10735. };
  10736. Path.prototype._innerSaveToNormal = function (toState) {
  10737. _super.prototype._innerSaveToNormal.call(this, toState);
  10738. var normalState = this._normalState;
  10739. if (toState.shape && !normalState.shape) {
  10740. normalState.shape = extend({}, this.shape);
  10741. }
  10742. };
  10743. Path.prototype._applyStateObj = function (stateName, state, normalState, keepCurrentStates, transition, animationCfg) {
  10744. _super.prototype._applyStateObj.call(this, stateName, state, normalState, keepCurrentStates, transition, animationCfg);
  10745. var needsRestoreToNormal = !(state && keepCurrentStates);
  10746. var targetShape;
  10747. if (state && state.shape) {
  10748. if (transition) {
  10749. if (keepCurrentStates) {
  10750. targetShape = state.shape;
  10751. }
  10752. else {
  10753. targetShape = extend({}, normalState.shape);
  10754. extend(targetShape, state.shape);
  10755. }
  10756. }
  10757. else {
  10758. targetShape = extend({}, keepCurrentStates ? this.shape : normalState.shape);
  10759. extend(targetShape, state.shape);
  10760. }
  10761. }
  10762. else if (needsRestoreToNormal) {
  10763. targetShape = normalState.shape;
  10764. }
  10765. if (targetShape) {
  10766. if (transition) {
  10767. this.shape = extend({}, this.shape);
  10768. var targetShapePrimaryProps = {};
  10769. var shapeKeys = keys(targetShape);
  10770. for (var i = 0; i < shapeKeys.length; i++) {
  10771. var key = shapeKeys[i];
  10772. if (typeof targetShape[key] === 'object') {
  10773. this.shape[key] = targetShape[key];
  10774. }
  10775. else {
  10776. targetShapePrimaryProps[key] = targetShape[key];
  10777. }
  10778. }
  10779. this._transitionState(stateName, {
  10780. shape: targetShapePrimaryProps
  10781. }, animationCfg);
  10782. }
  10783. else {
  10784. this.shape = targetShape;
  10785. this.dirtyShape();
  10786. }
  10787. }
  10788. };
  10789. Path.prototype._mergeStates = function (states) {
  10790. var mergedState = _super.prototype._mergeStates.call(this, states);
  10791. var mergedShape;
  10792. for (var i = 0; i < states.length; i++) {
  10793. var state = states[i];
  10794. if (state.shape) {
  10795. mergedShape = mergedShape || {};
  10796. this._mergeStyle(mergedShape, state.shape);
  10797. }
  10798. }
  10799. if (mergedShape) {
  10800. mergedState.shape = mergedShape;
  10801. }
  10802. return mergedState;
  10803. };
  10804. Path.prototype.getAnimationStyleProps = function () {
  10805. return DEFAULT_PATH_ANIMATION_PROPS;
  10806. };
  10807. Path.prototype.isZeroArea = function () {
  10808. return false;
  10809. };
  10810. Path.extend = function (defaultProps) {
  10811. var Sub = (function (_super) {
  10812. __extends(Sub, _super);
  10813. function Sub(opts) {
  10814. var _this = _super.call(this, opts) || this;
  10815. defaultProps.init && defaultProps.init.call(_this, opts);
  10816. return _this;
  10817. }
  10818. Sub.prototype.getDefaultStyle = function () {
  10819. return clone(defaultProps.style);
  10820. };
  10821. Sub.prototype.getDefaultShape = function () {
  10822. return clone(defaultProps.shape);
  10823. };
  10824. return Sub;
  10825. }(Path));
  10826. for (var key in defaultProps) {
  10827. if (typeof defaultProps[key] === 'function') {
  10828. Sub.prototype[key] = defaultProps[key];
  10829. }
  10830. }
  10831. return Sub;
  10832. };
  10833. Path.SHAPE_CHANGED_BIT = 4;
  10834. Path.initDefaultProps = (function () {
  10835. var pathProto = Path.prototype;
  10836. pathProto.type = 'path';
  10837. pathProto.strokeContainThreshold = 5;
  10838. pathProto.segmentIgnoreThreshold = 0;
  10839. pathProto.subPixelOptimize = false;
  10840. pathProto.autoBatch = false;
  10841. pathProto.__dirty = Element.REDARAW_BIT | Displayable.STYLE_CHANGED_BIT | Path.SHAPE_CHANGED_BIT;
  10842. })();
  10843. return Path;
  10844. }(Displayable));
  10845. var DEFAULT_TSPAN_STYLE = defaults({
  10846. strokeFirst: true,
  10847. font: DEFAULT_FONT,
  10848. x: 0,
  10849. y: 0,
  10850. textAlign: 'left',
  10851. textBaseline: 'top',
  10852. miterLimit: 2
  10853. }, DEFAULT_PATH_STYLE);
  10854. var TSpan = (function (_super) {
  10855. __extends(TSpan, _super);
  10856. function TSpan() {
  10857. return _super !== null && _super.apply(this, arguments) || this;
  10858. }
  10859. TSpan.prototype.hasStroke = function () {
  10860. var style = this.style;
  10861. var stroke = style.stroke;
  10862. return stroke != null && stroke !== 'none' && style.lineWidth > 0;
  10863. };
  10864. TSpan.prototype.hasFill = function () {
  10865. var style = this.style;
  10866. var fill = style.fill;
  10867. return fill != null && fill !== 'none';
  10868. };
  10869. TSpan.prototype.createStyle = function (obj) {
  10870. return createObject(DEFAULT_TSPAN_STYLE, obj);
  10871. };
  10872. TSpan.prototype.setBoundingRect = function (rect) {
  10873. this._rect = rect;
  10874. };
  10875. TSpan.prototype.getBoundingRect = function () {
  10876. var style = this.style;
  10877. if (!this._rect) {
  10878. var text = style.text;
  10879. text != null ? (text += '') : (text = '');
  10880. var rect = getBoundingRect(text, style.font, style.textAlign, style.textBaseline);
  10881. rect.x += style.x || 0;
  10882. rect.y += style.y || 0;
  10883. if (this.hasStroke()) {
  10884. var w = style.lineWidth;
  10885. rect.x -= w / 2;
  10886. rect.y -= w / 2;
  10887. rect.width += w;
  10888. rect.height += w;
  10889. }
  10890. this._rect = rect;
  10891. }
  10892. return this._rect;
  10893. };
  10894. TSpan.initDefaultProps = (function () {
  10895. var tspanProto = TSpan.prototype;
  10896. tspanProto.dirtyRectTolerance = 10;
  10897. })();
  10898. return TSpan;
  10899. }(Displayable));
  10900. TSpan.prototype.type = 'tspan';
  10901. var DEFAULT_IMAGE_STYLE = defaults({
  10902. x: 0,
  10903. y: 0
  10904. }, DEFAULT_COMMON_STYLE);
  10905. var DEFAULT_IMAGE_ANIMATION_PROPS = {
  10906. style: defaults({
  10907. x: true,
  10908. y: true,
  10909. width: true,
  10910. height: true,
  10911. sx: true,
  10912. sy: true,
  10913. sWidth: true,
  10914. sHeight: true
  10915. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  10916. };
  10917. function isImageLike(source) {
  10918. return !!(source
  10919. && typeof source !== 'string'
  10920. && source.width && source.height);
  10921. }
  10922. var ZRImage = (function (_super) {
  10923. __extends(ZRImage, _super);
  10924. function ZRImage() {
  10925. return _super !== null && _super.apply(this, arguments) || this;
  10926. }
  10927. ZRImage.prototype.createStyle = function (obj) {
  10928. return createObject(DEFAULT_IMAGE_STYLE, obj);
  10929. };
  10930. ZRImage.prototype._getSize = function (dim) {
  10931. var style = this.style;
  10932. var size = style[dim];
  10933. if (size != null) {
  10934. return size;
  10935. }
  10936. var imageSource = isImageLike(style.image)
  10937. ? style.image : this.__image;
  10938. if (!imageSource) {
  10939. return 0;
  10940. }
  10941. var otherDim = dim === 'width' ? 'height' : 'width';
  10942. var otherDimSize = style[otherDim];
  10943. if (otherDimSize == null) {
  10944. return imageSource[dim];
  10945. }
  10946. else {
  10947. return imageSource[dim] / imageSource[otherDim] * otherDimSize;
  10948. }
  10949. };
  10950. ZRImage.prototype.getWidth = function () {
  10951. return this._getSize('width');
  10952. };
  10953. ZRImage.prototype.getHeight = function () {
  10954. return this._getSize('height');
  10955. };
  10956. ZRImage.prototype.getAnimationStyleProps = function () {
  10957. return DEFAULT_IMAGE_ANIMATION_PROPS;
  10958. };
  10959. ZRImage.prototype.getBoundingRect = function () {
  10960. var style = this.style;
  10961. if (!this._rect) {
  10962. this._rect = new BoundingRect(style.x || 0, style.y || 0, this.getWidth(), this.getHeight());
  10963. }
  10964. return this._rect;
  10965. };
  10966. return ZRImage;
  10967. }(Displayable));
  10968. ZRImage.prototype.type = 'image';
  10969. function buildPath(ctx, shape) {
  10970. var x = shape.x;
  10971. var y = shape.y;
  10972. var width = shape.width;
  10973. var height = shape.height;
  10974. var r = shape.r;
  10975. var r1;
  10976. var r2;
  10977. var r3;
  10978. var r4;
  10979. if (width < 0) {
  10980. x = x + width;
  10981. width = -width;
  10982. }
  10983. if (height < 0) {
  10984. y = y + height;
  10985. height = -height;
  10986. }
  10987. if (typeof r === 'number') {
  10988. r1 = r2 = r3 = r4 = r;
  10989. }
  10990. else if (r instanceof Array) {
  10991. if (r.length === 1) {
  10992. r1 = r2 = r3 = r4 = r[0];
  10993. }
  10994. else if (r.length === 2) {
  10995. r1 = r3 = r[0];
  10996. r2 = r4 = r[1];
  10997. }
  10998. else if (r.length === 3) {
  10999. r1 = r[0];
  11000. r2 = r4 = r[1];
  11001. r3 = r[2];
  11002. }
  11003. else {
  11004. r1 = r[0];
  11005. r2 = r[1];
  11006. r3 = r[2];
  11007. r4 = r[3];
  11008. }
  11009. }
  11010. else {
  11011. r1 = r2 = r3 = r4 = 0;
  11012. }
  11013. var total;
  11014. if (r1 + r2 > width) {
  11015. total = r1 + r2;
  11016. r1 *= width / total;
  11017. r2 *= width / total;
  11018. }
  11019. if (r3 + r4 > width) {
  11020. total = r3 + r4;
  11021. r3 *= width / total;
  11022. r4 *= width / total;
  11023. }
  11024. if (r2 + r3 > height) {
  11025. total = r2 + r3;
  11026. r2 *= height / total;
  11027. r3 *= height / total;
  11028. }
  11029. if (r1 + r4 > height) {
  11030. total = r1 + r4;
  11031. r1 *= height / total;
  11032. r4 *= height / total;
  11033. }
  11034. ctx.moveTo(x + r1, y);
  11035. ctx.lineTo(x + width - r2, y);
  11036. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  11037. ctx.lineTo(x + width, y + height - r3);
  11038. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  11039. ctx.lineTo(x + r4, y + height);
  11040. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  11041. ctx.lineTo(x, y + r1);
  11042. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  11043. }
  11044. var round$1 = Math.round;
  11045. function subPixelOptimizeLine(outputShape, inputShape, style) {
  11046. if (!inputShape) {
  11047. return;
  11048. }
  11049. var x1 = inputShape.x1;
  11050. var x2 = inputShape.x2;
  11051. var y1 = inputShape.y1;
  11052. var y2 = inputShape.y2;
  11053. outputShape.x1 = x1;
  11054. outputShape.x2 = x2;
  11055. outputShape.y1 = y1;
  11056. outputShape.y2 = y2;
  11057. var lineWidth = style && style.lineWidth;
  11058. if (!lineWidth) {
  11059. return outputShape;
  11060. }
  11061. if (round$1(x1 * 2) === round$1(x2 * 2)) {
  11062. outputShape.x1 = outputShape.x2 = subPixelOptimize(x1, lineWidth, true);
  11063. }
  11064. if (round$1(y1 * 2) === round$1(y2 * 2)) {
  11065. outputShape.y1 = outputShape.y2 = subPixelOptimize(y1, lineWidth, true);
  11066. }
  11067. return outputShape;
  11068. }
  11069. function subPixelOptimizeRect(outputShape, inputShape, style) {
  11070. if (!inputShape) {
  11071. return;
  11072. }
  11073. var originX = inputShape.x;
  11074. var originY = inputShape.y;
  11075. var originWidth = inputShape.width;
  11076. var originHeight = inputShape.height;
  11077. outputShape.x = originX;
  11078. outputShape.y = originY;
  11079. outputShape.width = originWidth;
  11080. outputShape.height = originHeight;
  11081. var lineWidth = style && style.lineWidth;
  11082. if (!lineWidth) {
  11083. return outputShape;
  11084. }
  11085. outputShape.x = subPixelOptimize(originX, lineWidth, true);
  11086. outputShape.y = subPixelOptimize(originY, lineWidth, true);
  11087. outputShape.width = Math.max(subPixelOptimize(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  11088. outputShape.height = Math.max(subPixelOptimize(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  11089. return outputShape;
  11090. }
  11091. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  11092. if (!lineWidth) {
  11093. return position;
  11094. }
  11095. var doubledPosition = round$1(position * 2);
  11096. return (doubledPosition + round$1(lineWidth)) % 2 === 0
  11097. ? doubledPosition / 2
  11098. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  11099. }
  11100. var RectShape = (function () {
  11101. function RectShape() {
  11102. this.x = 0;
  11103. this.y = 0;
  11104. this.width = 0;
  11105. this.height = 0;
  11106. }
  11107. return RectShape;
  11108. }());
  11109. var subPixelOptimizeOutputShape = {};
  11110. var Rect = (function (_super) {
  11111. __extends(Rect, _super);
  11112. function Rect(opts) {
  11113. return _super.call(this, opts) || this;
  11114. }
  11115. Rect.prototype.getDefaultShape = function () {
  11116. return new RectShape();
  11117. };
  11118. Rect.prototype.buildPath = function (ctx, shape) {
  11119. var x;
  11120. var y;
  11121. var width;
  11122. var height;
  11123. if (this.subPixelOptimize) {
  11124. var optimizedShape = subPixelOptimizeRect(subPixelOptimizeOutputShape, shape, this.style);
  11125. x = optimizedShape.x;
  11126. y = optimizedShape.y;
  11127. width = optimizedShape.width;
  11128. height = optimizedShape.height;
  11129. optimizedShape.r = shape.r;
  11130. shape = optimizedShape;
  11131. }
  11132. else {
  11133. x = shape.x;
  11134. y = shape.y;
  11135. width = shape.width;
  11136. height = shape.height;
  11137. }
  11138. if (!shape.r) {
  11139. ctx.rect(x, y, width, height);
  11140. }
  11141. else {
  11142. buildPath(ctx, shape);
  11143. }
  11144. };
  11145. Rect.prototype.isZeroArea = function () {
  11146. return !this.shape.width || !this.shape.height;
  11147. };
  11148. return Rect;
  11149. }(Path));
  11150. Rect.prototype.type = 'rect';
  11151. var DEFAULT_RICH_TEXT_COLOR = {
  11152. fill: '#000'
  11153. };
  11154. var DEFAULT_STROKE_LINE_WIDTH = 2;
  11155. var DEFAULT_TEXT_ANIMATION_PROPS = {
  11156. style: defaults({
  11157. fill: true,
  11158. stroke: true,
  11159. fillOpacity: true,
  11160. strokeOpacity: true,
  11161. lineWidth: true,
  11162. fontSize: true,
  11163. lineHeight: true,
  11164. width: true,
  11165. height: true,
  11166. textShadowColor: true,
  11167. textShadowBlur: true,
  11168. textShadowOffsetX: true,
  11169. textShadowOffsetY: true,
  11170. backgroundColor: true,
  11171. padding: true,
  11172. borderColor: true,
  11173. borderWidth: true,
  11174. borderRadius: true
  11175. }, DEFAULT_COMMON_ANIMATION_PROPS.style)
  11176. };
  11177. var ZRText = (function (_super) {
  11178. __extends(ZRText, _super);
  11179. function ZRText(opts) {
  11180. var _this = _super.call(this) || this;
  11181. _this.type = 'text';
  11182. _this._children = [];
  11183. _this._defaultStyle = DEFAULT_RICH_TEXT_COLOR;
  11184. _this.attr(opts);
  11185. return _this;
  11186. }
  11187. ZRText.prototype.childrenRef = function () {
  11188. return this._children;
  11189. };
  11190. ZRText.prototype.update = function () {
  11191. if (this.styleChanged()) {
  11192. this._updateSubTexts();
  11193. }
  11194. for (var i = 0; i < this._children.length; i++) {
  11195. var child = this._children[i];
  11196. child.zlevel = this.zlevel;
  11197. child.z = this.z;
  11198. child.z2 = this.z2;
  11199. child.culling = this.culling;
  11200. child.cursor = this.cursor;
  11201. child.invisible = this.invisible;
  11202. }
  11203. var attachedTransform = this.attachedTransform;
  11204. if (attachedTransform) {
  11205. attachedTransform.updateTransform();
  11206. var m = attachedTransform.transform;
  11207. if (m) {
  11208. this.transform = this.transform || [];
  11209. copy$1(this.transform, m);
  11210. }
  11211. else {
  11212. this.transform = null;
  11213. }
  11214. }
  11215. else {
  11216. _super.prototype.update.call(this);
  11217. }
  11218. };
  11219. ZRText.prototype.getComputedTransform = function () {
  11220. if (this.__hostTarget) {
  11221. this.__hostTarget.getComputedTransform();
  11222. this.__hostTarget.updateInnerText(true);
  11223. }
  11224. return this.attachedTransform ? this.attachedTransform.getComputedTransform()
  11225. : _super.prototype.getComputedTransform.call(this);
  11226. };
  11227. ZRText.prototype._updateSubTexts = function () {
  11228. this._childCursor = 0;
  11229. normalizeTextStyle(this.style);
  11230. this.style.rich
  11231. ? this._updateRichTexts()
  11232. : this._updatePlainTexts();
  11233. this._children.length = this._childCursor;
  11234. this.styleUpdated();
  11235. };
  11236. ZRText.prototype.addSelfToZr = function (zr) {
  11237. _super.prototype.addSelfToZr.call(this, zr);
  11238. for (var i = 0; i < this._children.length; i++) {
  11239. this._children[i].__zr = zr;
  11240. }
  11241. };
  11242. ZRText.prototype.removeSelfFromZr = function (zr) {
  11243. _super.prototype.removeSelfFromZr.call(this, zr);
  11244. for (var i = 0; i < this._children.length; i++) {
  11245. this._children[i].__zr = null;
  11246. }
  11247. };
  11248. ZRText.prototype.getBoundingRect = function () {
  11249. if (this.styleChanged()) {
  11250. this._updateSubTexts();
  11251. }
  11252. if (!this._rect) {
  11253. var tmpRect = new BoundingRect(0, 0, 0, 0);
  11254. var children = this._children;
  11255. var tmpMat = [];
  11256. var rect = null;
  11257. for (var i = 0; i < children.length; i++) {
  11258. var child = children[i];
  11259. var childRect = child.getBoundingRect();
  11260. var transform = child.getLocalTransform(tmpMat);
  11261. if (transform) {
  11262. tmpRect.copy(childRect);
  11263. tmpRect.applyTransform(transform);
  11264. rect = rect || tmpRect.clone();
  11265. rect.union(tmpRect);
  11266. }
  11267. else {
  11268. rect = rect || childRect.clone();
  11269. rect.union(childRect);
  11270. }
  11271. }
  11272. this._rect = rect || tmpRect;
  11273. }
  11274. return this._rect;
  11275. };
  11276. ZRText.prototype.setDefaultTextStyle = function (defaultTextStyle) {
  11277. this._defaultStyle = defaultTextStyle || DEFAULT_RICH_TEXT_COLOR;
  11278. };
  11279. ZRText.prototype.setTextContent = function (textContent) {
  11280. throw new Error('Can\'t attach text on another text');
  11281. };
  11282. ZRText.prototype._mergeStyle = function (targetStyle, sourceStyle) {
  11283. if (!sourceStyle) {
  11284. return targetStyle;
  11285. }
  11286. var sourceRich = sourceStyle.rich;
  11287. var targetRich = targetStyle.rich || (sourceRich && {});
  11288. extend(targetStyle, sourceStyle);
  11289. if (sourceRich && targetRich) {
  11290. this._mergeRich(targetRich, sourceRich);
  11291. targetStyle.rich = targetRich;
  11292. }
  11293. else if (targetRich) {
  11294. targetStyle.rich = targetRich;
  11295. }
  11296. return targetStyle;
  11297. };
  11298. ZRText.prototype._mergeRich = function (targetRich, sourceRich) {
  11299. var richNames = keys(sourceRich);
  11300. for (var i = 0; i < richNames.length; i++) {
  11301. var richName = richNames[i];
  11302. targetRich[richName] = targetRich[richName] || {};
  11303. extend(targetRich[richName], sourceRich[richName]);
  11304. }
  11305. };
  11306. ZRText.prototype.getAnimationStyleProps = function () {
  11307. return DEFAULT_TEXT_ANIMATION_PROPS;
  11308. };
  11309. ZRText.prototype._getOrCreateChild = function (Ctor) {
  11310. var child = this._children[this._childCursor];
  11311. if (!child || !(child instanceof Ctor)) {
  11312. child = new Ctor();
  11313. }
  11314. this._children[this._childCursor++] = child;
  11315. child.__zr = this.__zr;
  11316. child.parent = this;
  11317. return child;
  11318. };
  11319. ZRText.prototype._updatePlainTexts = function () {
  11320. var style = this.style;
  11321. var textFont = style.font || DEFAULT_FONT;
  11322. var textPadding = style.padding;
  11323. var text = getStyleText(style);
  11324. var contentBlock = parsePlainText(text, style);
  11325. var needDrawBg = needDrawBackground(style);
  11326. var bgColorDrawn = !!(style.backgroundColor);
  11327. var outerHeight = contentBlock.outerHeight;
  11328. var textLines = contentBlock.lines;
  11329. var lineHeight = contentBlock.lineHeight;
  11330. var defaultStyle = this._defaultStyle;
  11331. var baseX = style.x || 0;
  11332. var baseY = style.y || 0;
  11333. var textAlign = style.align || defaultStyle.align || 'left';
  11334. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign || 'top';
  11335. var textX = baseX;
  11336. var textY = adjustTextY(baseY, contentBlock.contentHeight, verticalAlign);
  11337. if (needDrawBg || textPadding) {
  11338. var outerWidth_1 = contentBlock.width;
  11339. textPadding && (outerWidth_1 += textPadding[1] + textPadding[3]);
  11340. var boxX = adjustTextX(baseX, outerWidth_1, textAlign);
  11341. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11342. needDrawBg && this._renderBackground(style, style, boxX, boxY, outerWidth_1, outerHeight);
  11343. }
  11344. textY += lineHeight / 2;
  11345. if (textPadding) {
  11346. textX = getTextXForPadding(baseX, textAlign, textPadding);
  11347. if (verticalAlign === 'top') {
  11348. textY += textPadding[0];
  11349. }
  11350. else if (verticalAlign === 'bottom') {
  11351. textY -= textPadding[2];
  11352. }
  11353. }
  11354. var defaultLineWidth = 0;
  11355. var useDefaultFill = false;
  11356. var textFill = getFill('fill' in style
  11357. ? style.fill
  11358. : (useDefaultFill = true, defaultStyle.fill));
  11359. var textStroke = getStroke('stroke' in style
  11360. ? style.stroke
  11361. : (!bgColorDrawn
  11362. && (!defaultStyle.autoStroke || useDefaultFill))
  11363. ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11364. : null);
  11365. var hasShadow = style.textShadowBlur > 0;
  11366. var fixedBoundingRect = style.width != null
  11367. && (style.overflow === 'truncate' || style.overflow === 'break' || style.overflow === 'breakAll');
  11368. var calculatedLineHeight = contentBlock.calculatedLineHeight;
  11369. for (var i = 0; i < textLines.length; i++) {
  11370. var el = this._getOrCreateChild(TSpan);
  11371. var subElStyle = el.createStyle();
  11372. el.useStyle(subElStyle);
  11373. subElStyle.text = textLines[i];
  11374. subElStyle.x = textX;
  11375. subElStyle.y = textY;
  11376. if (textAlign) {
  11377. subElStyle.textAlign = textAlign;
  11378. }
  11379. subElStyle.textBaseline = 'middle';
  11380. subElStyle.opacity = style.opacity;
  11381. subElStyle.strokeFirst = true;
  11382. if (hasShadow) {
  11383. subElStyle.shadowBlur = style.textShadowBlur || 0;
  11384. subElStyle.shadowColor = style.textShadowColor || 'transparent';
  11385. subElStyle.shadowOffsetX = style.textShadowOffsetX || 0;
  11386. subElStyle.shadowOffsetY = style.textShadowOffsetY || 0;
  11387. }
  11388. if (textStroke) {
  11389. subElStyle.stroke = textStroke;
  11390. subElStyle.lineWidth = style.lineWidth || defaultLineWidth;
  11391. subElStyle.lineDash = style.lineDash;
  11392. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11393. }
  11394. if (textFill) {
  11395. subElStyle.fill = textFill;
  11396. }
  11397. subElStyle.font = textFont;
  11398. textY += lineHeight;
  11399. if (fixedBoundingRect) {
  11400. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, style.width, subElStyle.textAlign), adjustTextY(subElStyle.y, calculatedLineHeight, subElStyle.textBaseline), style.width, calculatedLineHeight));
  11401. }
  11402. }
  11403. };
  11404. ZRText.prototype._updateRichTexts = function () {
  11405. var style = this.style;
  11406. var text = getStyleText(style);
  11407. var contentBlock = parseRichText(text, style);
  11408. var contentWidth = contentBlock.width;
  11409. var outerWidth = contentBlock.outerWidth;
  11410. var outerHeight = contentBlock.outerHeight;
  11411. var textPadding = style.padding;
  11412. var baseX = style.x || 0;
  11413. var baseY = style.y || 0;
  11414. var defaultStyle = this._defaultStyle;
  11415. var textAlign = style.align || defaultStyle.align;
  11416. var verticalAlign = style.verticalAlign || defaultStyle.verticalAlign;
  11417. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  11418. var boxY = adjustTextY(baseY, outerHeight, verticalAlign);
  11419. var xLeft = boxX;
  11420. var lineTop = boxY;
  11421. if (textPadding) {
  11422. xLeft += textPadding[3];
  11423. lineTop += textPadding[0];
  11424. }
  11425. var xRight = xLeft + contentWidth;
  11426. if (needDrawBackground(style)) {
  11427. this._renderBackground(style, style, boxX, boxY, outerWidth, outerHeight);
  11428. }
  11429. var bgColorDrawn = !!(style.backgroundColor);
  11430. for (var i = 0; i < contentBlock.lines.length; i++) {
  11431. var line = contentBlock.lines[i];
  11432. var tokens = line.tokens;
  11433. var tokenCount = tokens.length;
  11434. var lineHeight = line.lineHeight;
  11435. var remainedWidth = line.width;
  11436. var leftIndex = 0;
  11437. var lineXLeft = xLeft;
  11438. var lineXRight = xRight;
  11439. var rightIndex = tokenCount - 1;
  11440. var token = void 0;
  11441. while (leftIndex < tokenCount
  11442. && (token = tokens[leftIndex], !token.align || token.align === 'left')) {
  11443. this._placeToken(token, style, lineHeight, lineTop, lineXLeft, 'left', bgColorDrawn);
  11444. remainedWidth -= token.width;
  11445. lineXLeft += token.width;
  11446. leftIndex++;
  11447. }
  11448. while (rightIndex >= 0
  11449. && (token = tokens[rightIndex], token.align === 'right')) {
  11450. this._placeToken(token, style, lineHeight, lineTop, lineXRight, 'right', bgColorDrawn);
  11451. remainedWidth -= token.width;
  11452. lineXRight -= token.width;
  11453. rightIndex--;
  11454. }
  11455. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - remainedWidth) / 2;
  11456. while (leftIndex <= rightIndex) {
  11457. token = tokens[leftIndex];
  11458. this._placeToken(token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center', bgColorDrawn);
  11459. lineXLeft += token.width;
  11460. leftIndex++;
  11461. }
  11462. lineTop += lineHeight;
  11463. }
  11464. };
  11465. ZRText.prototype._placeToken = function (token, style, lineHeight, lineTop, x, textAlign, parentBgColorDrawn) {
  11466. var tokenStyle = style.rich[token.styleName] || {};
  11467. tokenStyle.text = token.text;
  11468. var verticalAlign = token.verticalAlign;
  11469. var y = lineTop + lineHeight / 2;
  11470. if (verticalAlign === 'top') {
  11471. y = lineTop + token.height / 2;
  11472. }
  11473. else if (verticalAlign === 'bottom') {
  11474. y = lineTop + lineHeight - token.height / 2;
  11475. }
  11476. var needDrawBg = !token.isLineHolder && needDrawBackground(tokenStyle);
  11477. needDrawBg && this._renderBackground(tokenStyle, style, textAlign === 'right'
  11478. ? x - token.width
  11479. : textAlign === 'center'
  11480. ? x - token.width / 2
  11481. : x, y - token.height / 2, token.width, token.height);
  11482. var bgColorDrawn = !!tokenStyle.backgroundColor;
  11483. var textPadding = token.textPadding;
  11484. if (textPadding) {
  11485. x = getTextXForPadding(x, textAlign, textPadding);
  11486. y -= token.height / 2 - textPadding[0] - token.innerHeight / 2;
  11487. }
  11488. var el = this._getOrCreateChild(TSpan);
  11489. var subElStyle = el.createStyle();
  11490. el.useStyle(subElStyle);
  11491. var defaultStyle = this._defaultStyle;
  11492. var useDefaultFill = false;
  11493. var defaultLineWidth = 0;
  11494. var textFill = getStroke('fill' in tokenStyle ? tokenStyle.fill
  11495. : 'fill' in style ? style.fill
  11496. : (useDefaultFill = true, defaultStyle.fill));
  11497. var textStroke = getStroke('stroke' in tokenStyle ? tokenStyle.stroke
  11498. : 'stroke' in style ? style.stroke
  11499. : (!bgColorDrawn
  11500. && !parentBgColorDrawn
  11501. && (!defaultStyle.autoStroke || useDefaultFill)) ? (defaultLineWidth = DEFAULT_STROKE_LINE_WIDTH, defaultStyle.stroke)
  11502. : null);
  11503. var hasShadow = tokenStyle.textShadowBlur > 0
  11504. || style.textShadowBlur > 0;
  11505. subElStyle.text = token.text;
  11506. subElStyle.x = x;
  11507. subElStyle.y = y;
  11508. if (hasShadow) {
  11509. subElStyle.shadowBlur = tokenStyle.textShadowBlur || style.textShadowBlur || 0;
  11510. subElStyle.shadowColor = tokenStyle.textShadowColor || style.textShadowColor || 'transparent';
  11511. subElStyle.shadowOffsetX = tokenStyle.textShadowOffsetX || style.textShadowOffsetX || 0;
  11512. subElStyle.shadowOffsetY = tokenStyle.textShadowOffsetY || style.textShadowOffsetY || 0;
  11513. }
  11514. subElStyle.textAlign = textAlign;
  11515. subElStyle.textBaseline = 'middle';
  11516. subElStyle.font = token.font || DEFAULT_FONT;
  11517. subElStyle.opacity = retrieve3(tokenStyle.opacity, style.opacity, 1);
  11518. if (textStroke) {
  11519. subElStyle.lineWidth = retrieve3(tokenStyle.lineWidth, style.lineWidth, defaultLineWidth);
  11520. subElStyle.lineDash = retrieve2(tokenStyle.lineDash, style.lineDash);
  11521. subElStyle.lineDashOffset = style.lineDashOffset || 0;
  11522. subElStyle.stroke = textStroke;
  11523. }
  11524. if (textFill) {
  11525. subElStyle.fill = textFill;
  11526. }
  11527. var textWidth = token.contentWidth;
  11528. var textHeight = token.contentHeight;
  11529. el.setBoundingRect(new BoundingRect(adjustTextX(subElStyle.x, textWidth, subElStyle.textAlign), adjustTextY(subElStyle.y, textHeight, subElStyle.textBaseline), textWidth, textHeight));
  11530. };
  11531. ZRText.prototype._renderBackground = function (style, topStyle, x, y, width, height) {
  11532. var textBackgroundColor = style.backgroundColor;
  11533. var textBorderWidth = style.borderWidth;
  11534. var textBorderColor = style.borderColor;
  11535. var isPlainBg = isString(textBackgroundColor);
  11536. var textBorderRadius = style.borderRadius;
  11537. var self = this;
  11538. var rectEl;
  11539. var imgEl;
  11540. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  11541. rectEl = this._getOrCreateChild(Rect);
  11542. rectEl.useStyle(rectEl.createStyle());
  11543. rectEl.style.fill = null;
  11544. var rectShape = rectEl.shape;
  11545. rectShape.x = x;
  11546. rectShape.y = y;
  11547. rectShape.width = width;
  11548. rectShape.height = height;
  11549. rectShape.r = textBorderRadius;
  11550. rectEl.dirtyShape();
  11551. }
  11552. if (isPlainBg) {
  11553. var rectStyle = rectEl.style;
  11554. rectStyle.fill = textBackgroundColor || null;
  11555. rectStyle.fillOpacity = retrieve2(style.fillOpacity, 1);
  11556. }
  11557. else if (textBackgroundColor && textBackgroundColor.image) {
  11558. imgEl = this._getOrCreateChild(ZRImage);
  11559. imgEl.onload = function () {
  11560. self.dirtyStyle();
  11561. };
  11562. var imgStyle = imgEl.style;
  11563. imgStyle.image = textBackgroundColor.image;
  11564. imgStyle.x = x;
  11565. imgStyle.y = y;
  11566. imgStyle.width = width;
  11567. imgStyle.height = height;
  11568. }
  11569. if (textBorderWidth && textBorderColor) {
  11570. var rectStyle = rectEl.style;
  11571. rectStyle.lineWidth = textBorderWidth;
  11572. rectStyle.stroke = textBorderColor;
  11573. rectStyle.strokeOpacity = retrieve2(style.strokeOpacity, 1);
  11574. rectStyle.lineDash = style.borderDash;
  11575. rectStyle.lineDashOffset = style.borderDashOffset || 0;
  11576. rectEl.strokeContainThreshold = 0;
  11577. if (rectEl.hasFill() && rectEl.hasStroke()) {
  11578. rectStyle.strokeFirst = true;
  11579. rectStyle.lineWidth *= 2;
  11580. }
  11581. }
  11582. var commonStyle = (rectEl || imgEl).style;
  11583. commonStyle.shadowBlur = style.shadowBlur || 0;
  11584. commonStyle.shadowColor = style.shadowColor || 'transparent';
  11585. commonStyle.shadowOffsetX = style.shadowOffsetX || 0;
  11586. commonStyle.shadowOffsetY = style.shadowOffsetY || 0;
  11587. commonStyle.opacity = retrieve3(style.opacity, topStyle.opacity, 1);
  11588. };
  11589. ZRText.makeFont = function (style) {
  11590. var font = '';
  11591. if (style.fontSize || style.fontFamily || style.fontWeight) {
  11592. var fontSize = '';
  11593. if (typeof style.fontSize === 'string'
  11594. && (style.fontSize.indexOf('px') !== -1
  11595. || style.fontSize.indexOf('rem') !== -1
  11596. || style.fontSize.indexOf('em') !== -1)) {
  11597. fontSize = style.fontSize;
  11598. }
  11599. else if (!isNaN(+style.fontSize)) {
  11600. fontSize = style.fontSize + 'px';
  11601. }
  11602. else {
  11603. fontSize = '12px';
  11604. }
  11605. font = [
  11606. style.fontStyle,
  11607. style.fontWeight,
  11608. fontSize,
  11609. style.fontFamily || 'sans-serif'
  11610. ].join(' ');
  11611. }
  11612. return font && trim(font) || style.textFont || style.font;
  11613. };
  11614. return ZRText;
  11615. }(Displayable));
  11616. var VALID_TEXT_ALIGN = { left: true, right: 1, center: 1 };
  11617. var VALID_TEXT_VERTICAL_ALIGN = { top: 1, bottom: 1, middle: 1 };
  11618. function normalizeTextStyle(style) {
  11619. normalizeStyle(style);
  11620. each(style.rich, normalizeStyle);
  11621. return style;
  11622. }
  11623. function normalizeStyle(style) {
  11624. if (style) {
  11625. style.font = ZRText.makeFont(style);
  11626. var textAlign = style.align;
  11627. textAlign === 'middle' && (textAlign = 'center');
  11628. style.align = (textAlign == null || VALID_TEXT_ALIGN[textAlign]) ? textAlign : 'left';
  11629. var verticalAlign = style.verticalAlign;
  11630. verticalAlign === 'center' && (verticalAlign = 'middle');
  11631. style.verticalAlign = (verticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[verticalAlign]) ? verticalAlign : 'top';
  11632. var textPadding = style.padding;
  11633. if (textPadding) {
  11634. style.padding = normalizeCssArray(style.padding);
  11635. }
  11636. }
  11637. }
  11638. function getStroke(stroke, lineWidth) {
  11639. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  11640. ? null
  11641. : (stroke.image || stroke.colorStops)
  11642. ? '#000'
  11643. : stroke;
  11644. }
  11645. function getFill(fill) {
  11646. return (fill == null || fill === 'none')
  11647. ? null
  11648. : (fill.image || fill.colorStops)
  11649. ? '#000'
  11650. : fill;
  11651. }
  11652. function getTextXForPadding(x, textAlign, textPadding) {
  11653. return textAlign === 'right'
  11654. ? (x - textPadding[1])
  11655. : textAlign === 'center'
  11656. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  11657. : (x + textPadding[3]);
  11658. }
  11659. function getStyleText(style) {
  11660. var text = style.text;
  11661. text != null && (text += '');
  11662. return text;
  11663. }
  11664. function needDrawBackground(style) {
  11665. return !!(style.backgroundColor
  11666. || (style.borderWidth && style.borderColor));
  11667. }
  11668. var getECData = makeInner();
  11669. var _highlightNextDigit = 1;
  11670. var _highlightKeyMap = {};
  11671. var getSavedStates = makeInner();
  11672. var HOVER_STATE_NORMAL = 0;
  11673. var HOVER_STATE_BLUR = 1;
  11674. var HOVER_STATE_EMPHASIS = 2;
  11675. var SPECIAL_STATES = ['emphasis', 'blur', 'select'];
  11676. var DISPLAY_STATES = ['normal', 'emphasis', 'blur', 'select'];
  11677. var Z2_EMPHASIS_LIFT = 10;
  11678. var Z2_SELECT_LIFT = 9;
  11679. var HIGHLIGHT_ACTION_TYPE = 'highlight';
  11680. var DOWNPLAY_ACTION_TYPE = 'downplay';
  11681. var SELECT_ACTION_TYPE = 'select';
  11682. var UNSELECT_ACTION_TYPE = 'unselect';
  11683. var TOGGLE_SELECT_ACTION_TYPE = 'toggleSelect';
  11684. function hasFillOrStroke(fillOrStroke) {
  11685. return fillOrStroke != null && fillOrStroke !== 'none';
  11686. } // Most lifted color are duplicated.
  11687. var liftedColorCache = new LRU(100);
  11688. function liftColor(color$1) {
  11689. if (typeof color$1 !== 'string') {
  11690. return color$1;
  11691. }
  11692. var liftedColor = liftedColorCache.get(color$1);
  11693. if (!liftedColor) {
  11694. liftedColor = lift(color$1, -0.1);
  11695. liftedColorCache.put(color$1, liftedColor);
  11696. }
  11697. return liftedColor;
  11698. }
  11699. function doChangeHoverState(el, stateName, hoverStateEnum) {
  11700. if (el.onHoverStateChange && (el.hoverState || 0) !== hoverStateEnum) {
  11701. el.onHoverStateChange(stateName);
  11702. }
  11703. el.hoverState = hoverStateEnum;
  11704. }
  11705. function singleEnterEmphasis(el) {
  11706. // Only mark the flag.
  11707. // States will be applied in the echarts.ts in next frame.
  11708. doChangeHoverState(el, 'emphasis', HOVER_STATE_EMPHASIS);
  11709. }
  11710. function singleLeaveEmphasis(el) {
  11711. // Only mark the flag.
  11712. // States will be applied in the echarts.ts in next frame.
  11713. if (el.hoverState === HOVER_STATE_EMPHASIS) {
  11714. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11715. }
  11716. }
  11717. function singleEnterBlur(el) {
  11718. doChangeHoverState(el, 'blur', HOVER_STATE_BLUR);
  11719. }
  11720. function singleLeaveBlur(el) {
  11721. if (el.hoverState === HOVER_STATE_BLUR) {
  11722. doChangeHoverState(el, 'normal', HOVER_STATE_NORMAL);
  11723. }
  11724. }
  11725. function singleEnterSelect(el) {
  11726. el.selected = true;
  11727. }
  11728. function singleLeaveSelect(el) {
  11729. el.selected = false;
  11730. }
  11731. function updateElementState(el, updater, commonParam) {
  11732. updater(el, commonParam);
  11733. }
  11734. function traverseUpdateState(el, updater, commonParam) {
  11735. updateElementState(el, updater, commonParam);
  11736. el.isGroup && el.traverse(function (child) {
  11737. updateElementState(child, updater, commonParam);
  11738. });
  11739. }
  11740. function setStatesFlag(el, stateName) {
  11741. switch (stateName) {
  11742. case 'emphasis':
  11743. el.hoverState = HOVER_STATE_EMPHASIS;
  11744. break;
  11745. case 'normal':
  11746. el.hoverState = HOVER_STATE_NORMAL;
  11747. break;
  11748. case 'blur':
  11749. el.hoverState = HOVER_STATE_BLUR;
  11750. break;
  11751. case 'select':
  11752. el.selected = true;
  11753. }
  11754. }
  11755. function getFromStateStyle(el, props, toStateName, defaultValue) {
  11756. var style = el.style;
  11757. var fromState = {};
  11758. for (var i = 0; i < props.length; i++) {
  11759. var propName = props[i];
  11760. var val = style[propName];
  11761. fromState[propName] = val == null ? defaultValue && defaultValue[propName] : val;
  11762. }
  11763. for (var i = 0; i < el.animators.length; i++) {
  11764. var animator = el.animators[i];
  11765. if (animator.__fromStateTransition // Dont consider the animation to emphasis state.
  11766. && animator.__fromStateTransition.indexOf(toStateName) < 0 && animator.targetName === 'style') {
  11767. animator.saveFinalToTarget(fromState, props);
  11768. }
  11769. }
  11770. return fromState;
  11771. }
  11772. function createEmphasisDefaultState(el, stateName, targetStates, state) {
  11773. var hasSelect = targetStates && indexOf(targetStates, 'select') >= 0;
  11774. var cloned = false;
  11775. if (el instanceof Path) {
  11776. var store = getSavedStates(el);
  11777. var fromFill = hasSelect ? store.selectFill || store.normalFill : store.normalFill;
  11778. var fromStroke = hasSelect ? store.selectStroke || store.normalStroke : store.normalStroke;
  11779. if (hasFillOrStroke(fromFill) || hasFillOrStroke(fromStroke)) {
  11780. state = state || {}; // Apply default color lift
  11781. var emphasisStyle = state.style || {};
  11782. if (!hasFillOrStroke(emphasisStyle.fill) && hasFillOrStroke(fromFill)) {
  11783. cloned = true; // Not modify the original value.
  11784. state = extend({}, state);
  11785. emphasisStyle = extend({}, emphasisStyle); // Already being applied 'emphasis'. DON'T lift color multiple times.
  11786. emphasisStyle.fill = liftColor(fromFill);
  11787. } // Not highlight stroke if fill has been highlighted.
  11788. else if (!hasFillOrStroke(emphasisStyle.stroke) && hasFillOrStroke(fromStroke)) {
  11789. if (!cloned) {
  11790. state = extend({}, state);
  11791. emphasisStyle = extend({}, emphasisStyle);
  11792. }
  11793. emphasisStyle.stroke = liftColor(fromStroke);
  11794. }
  11795. state.style = emphasisStyle;
  11796. }
  11797. }
  11798. if (state) {
  11799. // TODO Share with textContent?
  11800. if (state.z2 == null) {
  11801. if (!cloned) {
  11802. state = extend({}, state);
  11803. }
  11804. var z2EmphasisLift = el.z2EmphasisLift;
  11805. state.z2 = el.z2 + (z2EmphasisLift != null ? z2EmphasisLift : Z2_EMPHASIS_LIFT);
  11806. }
  11807. }
  11808. return state;
  11809. }
  11810. function createSelectDefaultState(el, stateName, state) {
  11811. // const hasSelect = indexOf(el.currentStates, stateName) >= 0;
  11812. if (state) {
  11813. // TODO Share with textContent?
  11814. if (state.z2 == null) {
  11815. state = extend({}, state);
  11816. var z2SelectLift = el.z2SelectLift;
  11817. state.z2 = el.z2 + (z2SelectLift != null ? z2SelectLift : Z2_SELECT_LIFT);
  11818. }
  11819. }
  11820. return state;
  11821. }
  11822. function createBlurDefaultState(el, stateName, state) {
  11823. var hasBlur = indexOf(el.currentStates, stateName) >= 0;
  11824. var currentOpacity = el.style.opacity;
  11825. var fromState = !hasBlur ? getFromStateStyle(el, ['opacity'], stateName, {
  11826. opacity: 1
  11827. }) : null;
  11828. state = state || {};
  11829. var blurStyle = state.style || {};
  11830. if (blurStyle.opacity == null) {
  11831. // clone state
  11832. state = extend({}, state);
  11833. blurStyle = extend({
  11834. // Already being applied 'emphasis'. DON'T mul opacity multiple times.
  11835. opacity: hasBlur ? currentOpacity : fromState.opacity * 0.1
  11836. }, blurStyle);
  11837. state.style = blurStyle;
  11838. }
  11839. return state;
  11840. }
  11841. function elementStateProxy(stateName, targetStates) {
  11842. var state = this.states[stateName];
  11843. if (this.style) {
  11844. if (stateName === 'emphasis') {
  11845. return createEmphasisDefaultState(this, stateName, targetStates, state);
  11846. } else if (stateName === 'blur') {
  11847. return createBlurDefaultState(this, stateName, state);
  11848. } else if (stateName === 'select') {
  11849. return createSelectDefaultState(this, stateName, state);
  11850. }
  11851. }
  11852. return state;
  11853. }
  11854. /**FI
  11855. * Set hover style (namely "emphasis style") of element.
  11856. * @param el Should not be `zrender/graphic/Group`.
  11857. * @param focus 'self' | 'selfInSeries' | 'series'
  11858. */
  11859. function setDefaultStateProxy(el) {
  11860. el.stateProxy = elementStateProxy;
  11861. var textContent = el.getTextContent();
  11862. var textGuide = el.getTextGuideLine();
  11863. if (textContent) {
  11864. textContent.stateProxy = elementStateProxy;
  11865. }
  11866. if (textGuide) {
  11867. textGuide.stateProxy = elementStateProxy;
  11868. }
  11869. }
  11870. function enterEmphasisWhenMouseOver(el, e) {
  11871. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11872. && !el.__highByOuter && traverseUpdateState(el, singleEnterEmphasis);
  11873. }
  11874. function leaveEmphasisWhenMouseOut(el, e) {
  11875. !shouldSilent(el, e) // "emphasis" event highlight has higher priority than mouse highlight.
  11876. && !el.__highByOuter && traverseUpdateState(el, singleLeaveEmphasis);
  11877. }
  11878. function enterEmphasis(el, highlightDigit) {
  11879. el.__highByOuter |= 1 << (highlightDigit || 0);
  11880. traverseUpdateState(el, singleEnterEmphasis);
  11881. }
  11882. function leaveEmphasis(el, highlightDigit) {
  11883. !(el.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdateState(el, singleLeaveEmphasis);
  11884. }
  11885. function enterBlur(el) {
  11886. traverseUpdateState(el, singleEnterBlur);
  11887. }
  11888. function leaveBlur(el) {
  11889. traverseUpdateState(el, singleLeaveBlur);
  11890. }
  11891. function enterSelect(el) {
  11892. traverseUpdateState(el, singleEnterSelect);
  11893. }
  11894. function leaveSelect(el) {
  11895. traverseUpdateState(el, singleLeaveSelect);
  11896. }
  11897. function shouldSilent(el, e) {
  11898. return el.__highDownSilentOnTouch && e.zrByTouch;
  11899. }
  11900. function allLeaveBlur(api) {
  11901. var model = api.getModel();
  11902. model.eachComponent(function (componentType, componentModel) {
  11903. var view = componentType === 'series' ? api.getViewOfSeriesModel(componentModel) : api.getViewOfComponentModel(componentModel); // Leave blur anyway
  11904. view.group.traverse(function (child) {
  11905. singleLeaveBlur(child);
  11906. });
  11907. });
  11908. }
  11909. function toggleSeriesBlurState(targetSeriesIndex, focus, blurScope, api, isBlur) {
  11910. var ecModel = api.getModel();
  11911. blurScope = blurScope || 'coordinateSystem';
  11912. function leaveBlurOfIndices(data, dataIndices) {
  11913. for (var i = 0; i < dataIndices.length; i++) {
  11914. var itemEl = data.getItemGraphicEl(dataIndices[i]);
  11915. itemEl && leaveBlur(itemEl);
  11916. }
  11917. }
  11918. if (!isBlur) {
  11919. allLeaveBlur(api);
  11920. return;
  11921. }
  11922. if (targetSeriesIndex == null) {
  11923. return;
  11924. }
  11925. if (!focus || focus === 'none') {
  11926. return;
  11927. }
  11928. var targetSeriesModel = ecModel.getSeriesByIndex(targetSeriesIndex);
  11929. var targetCoordSys = targetSeriesModel.coordinateSystem;
  11930. if (targetCoordSys && targetCoordSys.master) {
  11931. targetCoordSys = targetCoordSys.master;
  11932. }
  11933. var blurredSeries = [];
  11934. ecModel.eachSeries(function (seriesModel) {
  11935. var sameSeries = targetSeriesModel === seriesModel;
  11936. var coordSys = seriesModel.coordinateSystem;
  11937. if (coordSys && coordSys.master) {
  11938. coordSys = coordSys.master;
  11939. }
  11940. var sameCoordSys = coordSys && targetCoordSys ? coordSys === targetCoordSys : sameSeries; // If there is no coordinate system. use sameSeries instead.
  11941. if (!( // Not blur other series if blurScope series
  11942. blurScope === 'series' && !sameSeries // Not blur other coordinate system if blurScope is coordinateSystem
  11943. || blurScope === 'coordinateSystem' && !sameCoordSys // Not blur self series if focus is series.
  11944. || focus === 'series' && sameSeries // TODO blurScope: coordinate system
  11945. )) {
  11946. var view = api.getViewOfSeriesModel(seriesModel);
  11947. view.group.traverse(function (child) {
  11948. singleEnterBlur(child);
  11949. });
  11950. if (isArrayLike(focus)) {
  11951. leaveBlurOfIndices(seriesModel.getData(), focus);
  11952. } else if (isObject(focus)) {
  11953. var dataTypes = keys(focus);
  11954. for (var d = 0; d < dataTypes.length; d++) {
  11955. leaveBlurOfIndices(seriesModel.getData(dataTypes[d]), focus[dataTypes[d]]);
  11956. }
  11957. }
  11958. blurredSeries.push(seriesModel);
  11959. }
  11960. });
  11961. ecModel.eachComponent(function (componentType, componentModel) {
  11962. if (componentType === 'series') {
  11963. return;
  11964. }
  11965. var view = api.getViewOfComponentModel(componentModel);
  11966. if (view && view.blurSeries) {
  11967. view.blurSeries(blurredSeries, ecModel);
  11968. }
  11969. });
  11970. }
  11971. function toggleSeriesBlurStateFromPayload(seriesModel, payload, api) {
  11972. if (!isHighDownPayload(payload)) {
  11973. return;
  11974. }
  11975. var isHighlight = payload.type === HIGHLIGHT_ACTION_TYPE;
  11976. var seriesIndex = seriesModel.seriesIndex;
  11977. var data = seriesModel.getData(payload.dataType);
  11978. var dataIndex = queryDataIndex(data, payload); // Pick the first one if there is multiple/none exists.
  11979. dataIndex = (isArray(dataIndex) ? dataIndex[0] : dataIndex) || 0;
  11980. var el = data.getItemGraphicEl(dataIndex);
  11981. if (!el) {
  11982. var count = data.count();
  11983. var current = 0; // If data on dataIndex is NaN.
  11984. while (!el && current < count) {
  11985. el = data.getItemGraphicEl(current++);
  11986. }
  11987. }
  11988. if (el) {
  11989. var ecData = getECData(el);
  11990. toggleSeriesBlurState(seriesIndex, ecData.focus, ecData.blurScope, api, isHighlight);
  11991. } else {
  11992. // If there is no element put on the data. Try getting it from raw option
  11993. // TODO Should put it on seriesModel?
  11994. var focus_1 = seriesModel.get(['emphasis', 'focus']);
  11995. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  11996. if (focus_1 != null) {
  11997. toggleSeriesBlurState(seriesIndex, focus_1, blurScope, api, isHighlight);
  11998. }
  11999. }
  12000. }
  12001. function toggleSelectionFromPayload(seriesModel, payload, api) {
  12002. if (!isSelectChangePayload(payload)) {
  12003. return;
  12004. }
  12005. var dataType = payload.dataType;
  12006. var data = seriesModel.getData(dataType);
  12007. var dataIndex = queryDataIndex(data, payload);
  12008. if (!isArray(dataIndex)) {
  12009. dataIndex = [dataIndex];
  12010. }
  12011. seriesModel[payload.type === TOGGLE_SELECT_ACTION_TYPE ? 'toggleSelect' : payload.type === SELECT_ACTION_TYPE ? 'select' : 'unselect'](dataIndex, dataType);
  12012. }
  12013. function updateSeriesElementSelection(seriesModel) {
  12014. var allData = seriesModel.getAllData();
  12015. each(allData, function (_a) {
  12016. var data = _a.data,
  12017. type = _a.type;
  12018. data.eachItemGraphicEl(function (el, idx) {
  12019. seriesModel.isSelected(idx, type) ? enterSelect(el) : leaveSelect(el);
  12020. });
  12021. });
  12022. }
  12023. function getAllSelectedIndices(ecModel) {
  12024. var ret = [];
  12025. ecModel.eachSeries(function (seriesModel) {
  12026. var allData = seriesModel.getAllData();
  12027. each(allData, function (_a) {
  12028. var data = _a.data,
  12029. type = _a.type;
  12030. var dataIndices = seriesModel.getSelectedDataIndices();
  12031. if (dataIndices.length > 0) {
  12032. var item = {
  12033. dataIndex: dataIndices,
  12034. seriesIndex: seriesModel.seriesIndex
  12035. };
  12036. if (type != null) {
  12037. item.dataType = type;
  12038. }
  12039. ret.push(item);
  12040. }
  12041. });
  12042. });
  12043. return ret;
  12044. }
  12045. /**
  12046. * Enable the function that mouseover will trigger the emphasis state.
  12047. *
  12048. * NOTE:
  12049. * This function should be used on the element with dataIndex, seriesIndex.
  12050. *
  12051. */
  12052. function enableHoverEmphasis(el, focus, blurScope) {
  12053. setAsHighDownDispatcher(el, true);
  12054. traverseUpdateState(el, setDefaultStateProxy);
  12055. enableHoverFocus(el, focus, blurScope);
  12056. }
  12057. function enableHoverFocus(el, focus, blurScope) {
  12058. var ecData = getECData(el);
  12059. if (focus != null) {
  12060. // TODO dataIndex may be set after this function. This check is not useful.
  12061. // if (ecData.dataIndex == null) {
  12062. // if (__DEV__) {
  12063. // console.warn('focus can only been set on element with dataIndex');
  12064. // }
  12065. // }
  12066. // else {
  12067. ecData.focus = focus;
  12068. ecData.blurScope = blurScope; // }
  12069. } else if (ecData.focus) {
  12070. ecData.focus = null;
  12071. }
  12072. }
  12073. var OTHER_STATES = ['emphasis', 'blur', 'select'];
  12074. var defaultStyleGetterMap = {
  12075. itemStyle: 'getItemStyle',
  12076. lineStyle: 'getLineStyle',
  12077. areaStyle: 'getAreaStyle'
  12078. };
  12079. /**
  12080. * Set emphasis/blur/selected states of element.
  12081. */
  12082. function setStatesStylesFromModel(el, itemModel, styleType, // default itemStyle
  12083. getter) {
  12084. styleType = styleType || 'itemStyle';
  12085. for (var i = 0; i < OTHER_STATES.length; i++) {
  12086. var stateName = OTHER_STATES[i];
  12087. var model = itemModel.getModel([stateName, styleType]);
  12088. var state = el.ensureState(stateName); // Let it throw error if getterType is not found.
  12089. state.style = getter ? getter(model) : model[defaultStyleGetterMap[styleType]]();
  12090. }
  12091. }
  12092. /**
  12093. * @parame el
  12094. * @param el.highDownSilentOnTouch
  12095. * In touch device, mouseover event will be trigger on touchstart event
  12096. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  12097. * conveniently use hoverStyle when tap on touch screen without additional
  12098. * code for compatibility.
  12099. * But if the chart/component has select feature, which usually also use
  12100. * hoverStyle, there might be conflict between 'select-highlight' and
  12101. * 'hover-highlight' especially when roam is enabled (see geo for example).
  12102. * In this case, `highDownSilentOnTouch` should be used to disable
  12103. * hover-highlight on touch device.
  12104. * @param asDispatcher If `false`, do not set as "highDownDispatcher".
  12105. */
  12106. function setAsHighDownDispatcher(el, asDispatcher) {
  12107. var disable = asDispatcher === false;
  12108. var extendedEl = el; // Make `highDownSilentOnTouch` and `onStateChange` only work after
  12109. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  12110. if (el.highDownSilentOnTouch) {
  12111. extendedEl.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  12112. } // Simple optimize, since this method might be
  12113. // called for each elements of a group in some cases.
  12114. if (!disable || extendedEl.__highDownDispatcher) {
  12115. // Emphasis, normal can be triggered manually by API or other components like hover link.
  12116. // el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent);
  12117. // Also keep previous record.
  12118. extendedEl.__highByOuter = extendedEl.__highByOuter || 0;
  12119. extendedEl.__highDownDispatcher = !disable;
  12120. }
  12121. }
  12122. function isHighDownDispatcher(el) {
  12123. return !!(el && el.__highDownDispatcher);
  12124. }
  12125. /**
  12126. * Support hightlight/downplay record on each elements.
  12127. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  12128. * user triggerred hightlight/downplay should not conflict.
  12129. * Only all of the highlightDigit cleared, return to normal.
  12130. * @param {string} highlightKey
  12131. * @return {number} highlightDigit
  12132. */
  12133. function getHighlightDigit(highlightKey) {
  12134. var highlightDigit = _highlightKeyMap[highlightKey];
  12135. if (highlightDigit == null && _highlightNextDigit <= 32) {
  12136. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  12137. }
  12138. return highlightDigit;
  12139. }
  12140. function isSelectChangePayload(payload) {
  12141. var payloadType = payload.type;
  12142. return payloadType === SELECT_ACTION_TYPE || payloadType === UNSELECT_ACTION_TYPE || payloadType === TOGGLE_SELECT_ACTION_TYPE;
  12143. }
  12144. function isHighDownPayload(payload) {
  12145. var payloadType = payload.type;
  12146. return payloadType === HIGHLIGHT_ACTION_TYPE || payloadType === DOWNPLAY_ACTION_TYPE;
  12147. }
  12148. function savePathStates(el) {
  12149. var store = getSavedStates(el);
  12150. store.normalFill = el.style.fill;
  12151. store.normalStroke = el.style.stroke;
  12152. var selectState = el.states.select || {};
  12153. store.selectFill = selectState.style && selectState.style.fill || null;
  12154. store.selectStroke = selectState.style && selectState.style.stroke || null;
  12155. }
  12156. var CMD$2 = PathProxy.CMD;
  12157. var points = [[], [], []];
  12158. var mathSqrt$2 = Math.sqrt;
  12159. var mathAtan2 = Math.atan2;
  12160. function transformPath(path, m) {
  12161. var data = path.data;
  12162. var len = path.len();
  12163. var cmd;
  12164. var nPoint;
  12165. var i;
  12166. var j;
  12167. var k;
  12168. var p;
  12169. var M = CMD$2.M;
  12170. var C = CMD$2.C;
  12171. var L = CMD$2.L;
  12172. var R = CMD$2.R;
  12173. var A = CMD$2.A;
  12174. var Q = CMD$2.Q;
  12175. for (i = 0, j = 0; i < len;) {
  12176. cmd = data[i++];
  12177. j = i;
  12178. nPoint = 0;
  12179. switch (cmd) {
  12180. case M:
  12181. nPoint = 1;
  12182. break;
  12183. case L:
  12184. nPoint = 1;
  12185. break;
  12186. case C:
  12187. nPoint = 3;
  12188. break;
  12189. case Q:
  12190. nPoint = 2;
  12191. break;
  12192. case A:
  12193. var x = m[4];
  12194. var y = m[5];
  12195. var sx = mathSqrt$2(m[0] * m[0] + m[1] * m[1]);
  12196. var sy = mathSqrt$2(m[2] * m[2] + m[3] * m[3]);
  12197. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12198. data[i] *= sx;
  12199. data[i++] += x;
  12200. data[i] *= sy;
  12201. data[i++] += y;
  12202. data[i++] *= sx;
  12203. data[i++] *= sy;
  12204. data[i++] += angle;
  12205. data[i++] += angle;
  12206. i += 2;
  12207. j = i;
  12208. break;
  12209. case R:
  12210. p[0] = data[i++];
  12211. p[1] = data[i++];
  12212. applyTransform(p, p, m);
  12213. data[j++] = p[0];
  12214. data[j++] = p[1];
  12215. p[0] += data[i++];
  12216. p[1] += data[i++];
  12217. applyTransform(p, p, m);
  12218. data[j++] = p[0];
  12219. data[j++] = p[1];
  12220. }
  12221. for (k = 0; k < nPoint; k++) {
  12222. var p_1 = points[k];
  12223. p_1[0] = data[i++];
  12224. p_1[1] = data[i++];
  12225. applyTransform(p_1, p_1, m);
  12226. data[j++] = p_1[0];
  12227. data[j++] = p_1[1];
  12228. }
  12229. }
  12230. path.increaseVersion();
  12231. }
  12232. var mathSqrt$3 = Math.sqrt;
  12233. var mathSin$2 = Math.sin;
  12234. var mathCos$2 = Math.cos;
  12235. var PI$1 = Math.PI;
  12236. function vMag(v) {
  12237. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12238. }
  12239. function vRatio(u, v) {
  12240. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12241. }
  12242. function vAngle(u, v) {
  12243. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12244. * Math.acos(vRatio(u, v));
  12245. }
  12246. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12247. var psi = psiDeg * (PI$1 / 180.0);
  12248. var xp = mathCos$2(psi) * (x1 - x2) / 2.0
  12249. + mathSin$2(psi) * (y1 - y2) / 2.0;
  12250. var yp = -1 * mathSin$2(psi) * (x1 - x2) / 2.0
  12251. + mathCos$2(psi) * (y1 - y2) / 2.0;
  12252. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12253. if (lambda > 1) {
  12254. rx *= mathSqrt$3(lambda);
  12255. ry *= mathSqrt$3(lambda);
  12256. }
  12257. var f = (fa === fs ? -1 : 1)
  12258. * mathSqrt$3((((rx * rx) * (ry * ry))
  12259. - ((rx * rx) * (yp * yp))
  12260. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12261. + (ry * ry) * (xp * xp))) || 0;
  12262. var cxp = f * rx * yp / ry;
  12263. var cyp = f * -ry * xp / rx;
  12264. var cx = (x1 + x2) / 2.0
  12265. + mathCos$2(psi) * cxp
  12266. - mathSin$2(psi) * cyp;
  12267. var cy = (y1 + y2) / 2.0
  12268. + mathSin$2(psi) * cxp
  12269. + mathCos$2(psi) * cyp;
  12270. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12271. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12272. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12273. var dTheta = vAngle(u, v);
  12274. if (vRatio(u, v) <= -1) {
  12275. dTheta = PI$1;
  12276. }
  12277. if (vRatio(u, v) >= 1) {
  12278. dTheta = 0;
  12279. }
  12280. if (dTheta < 0) {
  12281. var n = Math.round(dTheta / PI$1 * 1e6) / 1e6;
  12282. dTheta = PI$1 * 2 + (n % 2) * PI$1;
  12283. }
  12284. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12285. }
  12286. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig;
  12287. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;
  12288. function createPathProxyFromString(data) {
  12289. var path = new PathProxy();
  12290. if (!data) {
  12291. return path;
  12292. }
  12293. var cpx = 0;
  12294. var cpy = 0;
  12295. var subpathX = cpx;
  12296. var subpathY = cpy;
  12297. var prevCmd;
  12298. var CMD = PathProxy.CMD;
  12299. var cmdList = data.match(commandReg);
  12300. if (!cmdList) {
  12301. return path;
  12302. }
  12303. for (var l = 0; l < cmdList.length; l++) {
  12304. var cmdText = cmdList[l];
  12305. var cmdStr = cmdText.charAt(0);
  12306. var cmd = void 0;
  12307. var p = cmdText.match(numberReg) || [];
  12308. var pLen = p.length;
  12309. for (var i = 0; i < pLen; i++) {
  12310. p[i] = parseFloat(p[i]);
  12311. }
  12312. var off = 0;
  12313. while (off < pLen) {
  12314. var ctlPtx = void 0;
  12315. var ctlPty = void 0;
  12316. var rx = void 0;
  12317. var ry = void 0;
  12318. var psi = void 0;
  12319. var fa = void 0;
  12320. var fs = void 0;
  12321. var x1 = cpx;
  12322. var y1 = cpy;
  12323. var len = void 0;
  12324. var pathData = void 0;
  12325. switch (cmdStr) {
  12326. case 'l':
  12327. cpx += p[off++];
  12328. cpy += p[off++];
  12329. cmd = CMD.L;
  12330. path.addData(cmd, cpx, cpy);
  12331. break;
  12332. case 'L':
  12333. cpx = p[off++];
  12334. cpy = p[off++];
  12335. cmd = CMD.L;
  12336. path.addData(cmd, cpx, cpy);
  12337. break;
  12338. case 'm':
  12339. cpx += p[off++];
  12340. cpy += p[off++];
  12341. cmd = CMD.M;
  12342. path.addData(cmd, cpx, cpy);
  12343. subpathX = cpx;
  12344. subpathY = cpy;
  12345. cmdStr = 'l';
  12346. break;
  12347. case 'M':
  12348. cpx = p[off++];
  12349. cpy = p[off++];
  12350. cmd = CMD.M;
  12351. path.addData(cmd, cpx, cpy);
  12352. subpathX = cpx;
  12353. subpathY = cpy;
  12354. cmdStr = 'L';
  12355. break;
  12356. case 'h':
  12357. cpx += p[off++];
  12358. cmd = CMD.L;
  12359. path.addData(cmd, cpx, cpy);
  12360. break;
  12361. case 'H':
  12362. cpx = p[off++];
  12363. cmd = CMD.L;
  12364. path.addData(cmd, cpx, cpy);
  12365. break;
  12366. case 'v':
  12367. cpy += p[off++];
  12368. cmd = CMD.L;
  12369. path.addData(cmd, cpx, cpy);
  12370. break;
  12371. case 'V':
  12372. cpy = p[off++];
  12373. cmd = CMD.L;
  12374. path.addData(cmd, cpx, cpy);
  12375. break;
  12376. case 'C':
  12377. cmd = CMD.C;
  12378. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12379. cpx = p[off - 2];
  12380. cpy = p[off - 1];
  12381. break;
  12382. case 'c':
  12383. cmd = CMD.C;
  12384. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12385. cpx += p[off - 2];
  12386. cpy += p[off - 1];
  12387. break;
  12388. case 'S':
  12389. ctlPtx = cpx;
  12390. ctlPty = cpy;
  12391. len = path.len();
  12392. pathData = path.data;
  12393. if (prevCmd === CMD.C) {
  12394. ctlPtx += cpx - pathData[len - 4];
  12395. ctlPty += cpy - pathData[len - 3];
  12396. }
  12397. cmd = CMD.C;
  12398. x1 = p[off++];
  12399. y1 = p[off++];
  12400. cpx = p[off++];
  12401. cpy = p[off++];
  12402. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12403. break;
  12404. case 's':
  12405. ctlPtx = cpx;
  12406. ctlPty = cpy;
  12407. len = path.len();
  12408. pathData = path.data;
  12409. if (prevCmd === CMD.C) {
  12410. ctlPtx += cpx - pathData[len - 4];
  12411. ctlPty += cpy - pathData[len - 3];
  12412. }
  12413. cmd = CMD.C;
  12414. x1 = cpx + p[off++];
  12415. y1 = cpy + p[off++];
  12416. cpx += p[off++];
  12417. cpy += p[off++];
  12418. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12419. break;
  12420. case 'Q':
  12421. x1 = p[off++];
  12422. y1 = p[off++];
  12423. cpx = p[off++];
  12424. cpy = p[off++];
  12425. cmd = CMD.Q;
  12426. path.addData(cmd, x1, y1, cpx, cpy);
  12427. break;
  12428. case 'q':
  12429. x1 = p[off++] + cpx;
  12430. y1 = p[off++] + cpy;
  12431. cpx += p[off++];
  12432. cpy += p[off++];
  12433. cmd = CMD.Q;
  12434. path.addData(cmd, x1, y1, cpx, cpy);
  12435. break;
  12436. case 'T':
  12437. ctlPtx = cpx;
  12438. ctlPty = cpy;
  12439. len = path.len();
  12440. pathData = path.data;
  12441. if (prevCmd === CMD.Q) {
  12442. ctlPtx += cpx - pathData[len - 4];
  12443. ctlPty += cpy - pathData[len - 3];
  12444. }
  12445. cpx = p[off++];
  12446. cpy = p[off++];
  12447. cmd = CMD.Q;
  12448. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12449. break;
  12450. case 't':
  12451. ctlPtx = cpx;
  12452. ctlPty = cpy;
  12453. len = path.len();
  12454. pathData = path.data;
  12455. if (prevCmd === CMD.Q) {
  12456. ctlPtx += cpx - pathData[len - 4];
  12457. ctlPty += cpy - pathData[len - 3];
  12458. }
  12459. cpx += p[off++];
  12460. cpy += p[off++];
  12461. cmd = CMD.Q;
  12462. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12463. break;
  12464. case 'A':
  12465. rx = p[off++];
  12466. ry = p[off++];
  12467. psi = p[off++];
  12468. fa = p[off++];
  12469. fs = p[off++];
  12470. x1 = cpx, y1 = cpy;
  12471. cpx = p[off++];
  12472. cpy = p[off++];
  12473. cmd = CMD.A;
  12474. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12475. break;
  12476. case 'a':
  12477. rx = p[off++];
  12478. ry = p[off++];
  12479. psi = p[off++];
  12480. fa = p[off++];
  12481. fs = p[off++];
  12482. x1 = cpx, y1 = cpy;
  12483. cpx += p[off++];
  12484. cpy += p[off++];
  12485. cmd = CMD.A;
  12486. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12487. break;
  12488. }
  12489. }
  12490. if (cmdStr === 'z' || cmdStr === 'Z') {
  12491. cmd = CMD.Z;
  12492. path.addData(cmd);
  12493. cpx = subpathX;
  12494. cpy = subpathY;
  12495. }
  12496. prevCmd = cmd;
  12497. }
  12498. path.toStatic();
  12499. return path;
  12500. }
  12501. var SVGPath = (function (_super) {
  12502. __extends(SVGPath, _super);
  12503. function SVGPath() {
  12504. return _super !== null && _super.apply(this, arguments) || this;
  12505. }
  12506. SVGPath.prototype.applyTransform = function (m) { };
  12507. return SVGPath;
  12508. }(Path));
  12509. function isPathProxy(path) {
  12510. return path.setData != null;
  12511. }
  12512. function createPathOptions(str, opts) {
  12513. var pathProxy = createPathProxyFromString(str);
  12514. var innerOpts = extend({}, opts);
  12515. innerOpts.buildPath = function (path) {
  12516. if (isPathProxy(path)) {
  12517. path.setData(pathProxy.data);
  12518. var ctx = path.getContext();
  12519. if (ctx) {
  12520. path.rebuildPath(ctx, 1);
  12521. }
  12522. }
  12523. else {
  12524. var ctx = path;
  12525. pathProxy.rebuildPath(ctx, 1);
  12526. }
  12527. };
  12528. innerOpts.applyTransform = function (m) {
  12529. transformPath(pathProxy, m);
  12530. this.dirtyShape();
  12531. };
  12532. return innerOpts;
  12533. }
  12534. function createFromString(str, opts) {
  12535. return new SVGPath(createPathOptions(str, opts));
  12536. }
  12537. function extendFromString(str, defaultOpts) {
  12538. var innerOpts = createPathOptions(str, defaultOpts);
  12539. var Sub = (function (_super) {
  12540. __extends(Sub, _super);
  12541. function Sub(opts) {
  12542. var _this = _super.call(this, opts) || this;
  12543. _this.applyTransform = innerOpts.applyTransform;
  12544. _this.buildPath = innerOpts.buildPath;
  12545. return _this;
  12546. }
  12547. return Sub;
  12548. }(SVGPath));
  12549. return Sub;
  12550. }
  12551. function mergePath(pathEls, opts) {
  12552. var pathList = [];
  12553. var len = pathEls.length;
  12554. for (var i = 0; i < len; i++) {
  12555. var pathEl = pathEls[i];
  12556. if (!pathEl.path) {
  12557. pathEl.createPathProxy();
  12558. }
  12559. if (pathEl.shapeChanged()) {
  12560. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12561. }
  12562. pathList.push(pathEl.path);
  12563. }
  12564. var pathBundle = new Path(opts);
  12565. pathBundle.createPathProxy();
  12566. pathBundle.buildPath = function (path) {
  12567. if (isPathProxy(path)) {
  12568. path.appendPath(pathList);
  12569. var ctx = path.getContext();
  12570. if (ctx) {
  12571. path.rebuildPath(ctx, 1);
  12572. }
  12573. }
  12574. };
  12575. return pathBundle;
  12576. }
  12577. var CircleShape = (function () {
  12578. function CircleShape() {
  12579. this.cx = 0;
  12580. this.cy = 0;
  12581. this.r = 0;
  12582. }
  12583. return CircleShape;
  12584. }());
  12585. var Circle = (function (_super) {
  12586. __extends(Circle, _super);
  12587. function Circle(opts) {
  12588. return _super.call(this, opts) || this;
  12589. }
  12590. Circle.prototype.getDefaultShape = function () {
  12591. return new CircleShape();
  12592. };
  12593. Circle.prototype.buildPath = function (ctx, shape, inBundle) {
  12594. if (inBundle) {
  12595. ctx.moveTo(shape.cx + shape.r, shape.cy);
  12596. }
  12597. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2);
  12598. };
  12599. return Circle;
  12600. }(Path));
  12601. Circle.prototype.type = 'circle';
  12602. var EllipseShape = (function () {
  12603. function EllipseShape() {
  12604. this.cx = 0;
  12605. this.cy = 0;
  12606. this.rx = 0;
  12607. this.ry = 0;
  12608. }
  12609. return EllipseShape;
  12610. }());
  12611. var Ellipse = (function (_super) {
  12612. __extends(Ellipse, _super);
  12613. function Ellipse(opts) {
  12614. return _super.call(this, opts) || this;
  12615. }
  12616. Ellipse.prototype.getDefaultShape = function () {
  12617. return new EllipseShape();
  12618. };
  12619. Ellipse.prototype.buildPath = function (ctx, shape) {
  12620. var k = 0.5522848;
  12621. var x = shape.cx;
  12622. var y = shape.cy;
  12623. var a = shape.rx;
  12624. var b = shape.ry;
  12625. var ox = a * k;
  12626. var oy = b * k;
  12627. ctx.moveTo(x - a, y);
  12628. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  12629. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  12630. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  12631. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  12632. ctx.closePath();
  12633. };
  12634. return Ellipse;
  12635. }(Path));
  12636. Ellipse.prototype.type = 'ellipse';
  12637. var PI$2 = Math.PI;
  12638. var PI2$5 = PI$2 * 2;
  12639. var mathSin$3 = Math.sin;
  12640. var mathCos$3 = Math.cos;
  12641. var mathACos = Math.acos;
  12642. var mathATan2 = Math.atan2;
  12643. var mathAbs$1 = Math.abs;
  12644. var mathSqrt$4 = Math.sqrt;
  12645. var mathMax$3 = Math.max;
  12646. var mathMin$3 = Math.min;
  12647. var e = 1e-4;
  12648. function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
  12649. var x10 = x1 - x0;
  12650. var y10 = y1 - y0;
  12651. var x32 = x3 - x2;
  12652. var y32 = y3 - y2;
  12653. var t = y32 * x10 - x32 * y10;
  12654. if (t * t < e) {
  12655. return;
  12656. }
  12657. t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;
  12658. return [x0 + t * x10, y0 + t * y10];
  12659. }
  12660. function computeCornerTangents(x0, y0, x1, y1, radius, cr, clockwise) {
  12661. var x01 = x0 - x1;
  12662. var y01 = y0 - y1;
  12663. var lo = (clockwise ? cr : -cr) / mathSqrt$4(x01 * x01 + y01 * y01);
  12664. var ox = lo * y01;
  12665. var oy = -lo * x01;
  12666. var x11 = x0 + ox;
  12667. var y11 = y0 + oy;
  12668. var x10 = x1 + ox;
  12669. var y10 = y1 + oy;
  12670. var x00 = (x11 + x10) / 2;
  12671. var y00 = (y11 + y10) / 2;
  12672. var dx = x10 - x11;
  12673. var dy = y10 - y11;
  12674. var d2 = dx * dx + dy * dy;
  12675. var r = radius - cr;
  12676. var s = x11 * y10 - x10 * y11;
  12677. var d = (dy < 0 ? -1 : 1) * mathSqrt$4(mathMax$3(0, r * r * d2 - s * s));
  12678. var cx0 = (s * dy - dx * d) / d2;
  12679. var cy0 = (-s * dx - dy * d) / d2;
  12680. var cx1 = (s * dy + dx * d) / d2;
  12681. var cy1 = (-s * dx + dy * d) / d2;
  12682. var dx0 = cx0 - x00;
  12683. var dy0 = cy0 - y00;
  12684. var dx1 = cx1 - x00;
  12685. var dy1 = cy1 - y00;
  12686. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) {
  12687. cx0 = cx1;
  12688. cy0 = cy1;
  12689. }
  12690. return {
  12691. cx: cx0,
  12692. cy: cy0,
  12693. x01: -ox,
  12694. y01: -oy,
  12695. x11: cx0 * (radius / r - 1),
  12696. y11: cy0 * (radius / r - 1)
  12697. };
  12698. }
  12699. function buildPath$1(ctx, shape) {
  12700. var radius = mathMax$3(shape.r, 0);
  12701. var innerRadius = mathMax$3(shape.r0 || 0, 0);
  12702. var hasRadius = radius > 0;
  12703. var hasInnerRadius = innerRadius > 0;
  12704. if (!hasRadius && !hasInnerRadius) {
  12705. return;
  12706. }
  12707. if (!hasRadius) {
  12708. radius = innerRadius;
  12709. innerRadius = 0;
  12710. }
  12711. if (innerRadius > radius) {
  12712. var tmp = radius;
  12713. radius = innerRadius;
  12714. innerRadius = tmp;
  12715. }
  12716. var clockwise = !!shape.clockwise;
  12717. var startAngle = shape.startAngle;
  12718. var endAngle = shape.endAngle;
  12719. var arc;
  12720. if (startAngle === endAngle) {
  12721. arc = 0;
  12722. }
  12723. else {
  12724. var tmpAngles = [startAngle, endAngle];
  12725. normalizeArcAngles(tmpAngles, !clockwise);
  12726. arc = mathAbs$1(tmpAngles[0] - tmpAngles[1]);
  12727. }
  12728. var x = shape.cx;
  12729. var y = shape.cy;
  12730. var cornerRadius = shape.cornerRadius || 0;
  12731. var innerCornerRadius = shape.innerCornerRadius || 0;
  12732. if (!(radius > e)) {
  12733. ctx.moveTo(x, y);
  12734. }
  12735. else if (arc > PI2$5 - e) {
  12736. ctx.moveTo(x + radius * mathCos$3(startAngle), y + radius * mathSin$3(startAngle));
  12737. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12738. if (innerRadius > e) {
  12739. ctx.moveTo(x + innerRadius * mathCos$3(endAngle), y + innerRadius * mathSin$3(endAngle));
  12740. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12741. }
  12742. }
  12743. else {
  12744. var halfRd = mathAbs$1(radius - innerRadius) / 2;
  12745. var cr = mathMin$3(halfRd, cornerRadius);
  12746. var icr = mathMin$3(halfRd, innerCornerRadius);
  12747. var cr0 = icr;
  12748. var cr1 = cr;
  12749. var xrs = radius * mathCos$3(startAngle);
  12750. var yrs = radius * mathSin$3(startAngle);
  12751. var xire = innerRadius * mathCos$3(endAngle);
  12752. var yire = innerRadius * mathSin$3(endAngle);
  12753. var xre = void 0;
  12754. var yre = void 0;
  12755. var xirs = void 0;
  12756. var yirs = void 0;
  12757. if (cr > e || icr > e) {
  12758. xre = radius * mathCos$3(endAngle);
  12759. yre = radius * mathSin$3(endAngle);
  12760. xirs = innerRadius * mathCos$3(startAngle);
  12761. yirs = innerRadius * mathSin$3(startAngle);
  12762. if (arc < PI$2) {
  12763. var it_1 = intersect(xrs, yrs, xirs, yirs, xre, yre, xire, yire);
  12764. if (it_1) {
  12765. var x0 = xrs - it_1[0];
  12766. var y0 = yrs - it_1[1];
  12767. var x1 = xre - it_1[0];
  12768. var y1 = yre - it_1[1];
  12769. var a = 1 / mathSin$3(mathACos((x0 * x1 + y0 * y1) / (mathSqrt$4(x0 * x0 + y0 * y0) * mathSqrt$4(x1 * x1 + y1 * y1))) / 2);
  12770. var b = mathSqrt$4(it_1[0] * it_1[0] + it_1[1] * it_1[1]);
  12771. cr0 = mathMin$3(icr, (innerRadius - b) / (a - 1));
  12772. cr1 = mathMin$3(cr, (radius - b) / (a + 1));
  12773. }
  12774. }
  12775. }
  12776. if (!(arc > e)) {
  12777. ctx.moveTo(x + xrs, y + yrs);
  12778. }
  12779. else if (cr1 > e) {
  12780. var ct0 = computeCornerTangents(xirs, yirs, xrs, yrs, radius, cr1, clockwise);
  12781. var ct1 = computeCornerTangents(xre, yre, xire, yire, radius, cr1, clockwise);
  12782. ctx.moveTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12783. if (cr1 < cr) {
  12784. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12785. }
  12786. else {
  12787. ctx.arc(x + ct0.cx, y + ct0.cy, cr1, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12788. ctx.arc(x, y, radius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), !clockwise);
  12789. ctx.arc(x + ct1.cx, y + ct1.cy, cr1, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12790. }
  12791. }
  12792. else {
  12793. ctx.moveTo(x + xrs, y + yrs);
  12794. ctx.arc(x, y, radius, startAngle, endAngle, !clockwise);
  12795. }
  12796. if (!(innerRadius > e) || !(arc > e)) {
  12797. ctx.lineTo(x + xire, y + yire);
  12798. }
  12799. else if (cr0 > e) {
  12800. var ct0 = computeCornerTangents(xire, yire, xre, yre, innerRadius, -cr0, clockwise);
  12801. var ct1 = computeCornerTangents(xrs, yrs, xirs, yirs, innerRadius, -cr0, clockwise);
  12802. ctx.lineTo(x + ct0.cx + ct0.x01, y + ct0.cy + ct0.y01);
  12803. if (cr0 < icr) {
  12804. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12805. }
  12806. else {
  12807. ctx.arc(x + ct0.cx, y + ct0.cy, cr0, mathATan2(ct0.y01, ct0.x01), mathATan2(ct0.y11, ct0.x11), !clockwise);
  12808. ctx.arc(x, y, innerRadius, mathATan2(ct0.cy + ct0.y11, ct0.cx + ct0.x11), mathATan2(ct1.cy + ct1.y11, ct1.cx + ct1.x11), clockwise);
  12809. ctx.arc(x + ct1.cx, y + ct1.cy, cr0, mathATan2(ct1.y11, ct1.x11), mathATan2(ct1.y01, ct1.x01), !clockwise);
  12810. }
  12811. }
  12812. else {
  12813. ctx.lineTo(x + xire, y + yire);
  12814. ctx.arc(x, y, innerRadius, endAngle, startAngle, clockwise);
  12815. }
  12816. }
  12817. ctx.closePath();
  12818. }
  12819. var SectorShape = (function () {
  12820. function SectorShape() {
  12821. this.cx = 0;
  12822. this.cy = 0;
  12823. this.r0 = 0;
  12824. this.r = 0;
  12825. this.startAngle = 0;
  12826. this.endAngle = Math.PI * 2;
  12827. this.clockwise = true;
  12828. this.cornerRadius = 0;
  12829. this.innerCornerRadius = 0;
  12830. }
  12831. return SectorShape;
  12832. }());
  12833. var Sector = (function (_super) {
  12834. __extends(Sector, _super);
  12835. function Sector(opts) {
  12836. return _super.call(this, opts) || this;
  12837. }
  12838. Sector.prototype.getDefaultShape = function () {
  12839. return new SectorShape();
  12840. };
  12841. Sector.prototype.buildPath = function (ctx, shape) {
  12842. buildPath$1(ctx, shape);
  12843. };
  12844. Sector.prototype.isZeroArea = function () {
  12845. return this.shape.startAngle === this.shape.endAngle
  12846. || this.shape.r === this.shape.r0;
  12847. };
  12848. return Sector;
  12849. }(Path));
  12850. Sector.prototype.type = 'sector';
  12851. var RingShape = (function () {
  12852. function RingShape() {
  12853. this.cx = 0;
  12854. this.cy = 0;
  12855. this.r = 0;
  12856. this.r0 = 0;
  12857. }
  12858. return RingShape;
  12859. }());
  12860. var Ring = (function (_super) {
  12861. __extends(Ring, _super);
  12862. function Ring(opts) {
  12863. return _super.call(this, opts) || this;
  12864. }
  12865. Ring.prototype.getDefaultShape = function () {
  12866. return new RingShape();
  12867. };
  12868. Ring.prototype.buildPath = function (ctx, shape) {
  12869. var x = shape.cx;
  12870. var y = shape.cy;
  12871. var PI2 = Math.PI * 2;
  12872. ctx.moveTo(x + shape.r, y);
  12873. ctx.arc(x, y, shape.r, 0, PI2, false);
  12874. ctx.moveTo(x + shape.r0, y);
  12875. ctx.arc(x, y, shape.r0, 0, PI2, true);
  12876. };
  12877. return Ring;
  12878. }(Path));
  12879. Ring.prototype.type = 'ring';
  12880. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  12881. var v0 = (p2 - p0) * 0.5;
  12882. var v1 = (p3 - p1) * 0.5;
  12883. return (2 * (p1 - p2) + v0 + v1) * t3
  12884. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  12885. + v0 * t + p1;
  12886. }
  12887. function smoothSpline(points, isLoop) {
  12888. var len = points.length;
  12889. var ret = [];
  12890. var distance$1 = 0;
  12891. for (var i = 1; i < len; i++) {
  12892. distance$1 += distance(points[i - 1], points[i]);
  12893. }
  12894. var segs = distance$1 / 2;
  12895. segs = segs < len ? len : segs;
  12896. for (var i = 0; i < segs; i++) {
  12897. var pos = i / (segs - 1) * (isLoop ? len : len - 1);
  12898. var idx = Math.floor(pos);
  12899. var w = pos - idx;
  12900. var p0 = void 0;
  12901. var p1 = points[idx % len];
  12902. var p2 = void 0;
  12903. var p3 = void 0;
  12904. if (!isLoop) {
  12905. p0 = points[idx === 0 ? idx : idx - 1];
  12906. p2 = points[idx > len - 2 ? len - 1 : idx + 1];
  12907. p3 = points[idx > len - 3 ? len - 1 : idx + 2];
  12908. }
  12909. else {
  12910. p0 = points[(idx - 1 + len) % len];
  12911. p2 = points[(idx + 1) % len];
  12912. p3 = points[(idx + 2) % len];
  12913. }
  12914. var w2 = w * w;
  12915. var w3 = w * w2;
  12916. ret.push([
  12917. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  12918. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  12919. ]);
  12920. }
  12921. return ret;
  12922. }
  12923. function smoothBezier(points, smooth, isLoop, constraint) {
  12924. var cps = [];
  12925. var v = [];
  12926. var v1 = [];
  12927. var v2 = [];
  12928. var prevPoint;
  12929. var nextPoint;
  12930. var min$1;
  12931. var max$1;
  12932. if (constraint) {
  12933. min$1 = [Infinity, Infinity];
  12934. max$1 = [-Infinity, -Infinity];
  12935. for (var i = 0, len = points.length; i < len; i++) {
  12936. min(min$1, min$1, points[i]);
  12937. max(max$1, max$1, points[i]);
  12938. }
  12939. min(min$1, min$1, constraint[0]);
  12940. max(max$1, max$1, constraint[1]);
  12941. }
  12942. for (var i = 0, len = points.length; i < len; i++) {
  12943. var point = points[i];
  12944. if (isLoop) {
  12945. prevPoint = points[i ? i - 1 : len - 1];
  12946. nextPoint = points[(i + 1) % len];
  12947. }
  12948. else {
  12949. if (i === 0 || i === len - 1) {
  12950. cps.push(clone$1(points[i]));
  12951. continue;
  12952. }
  12953. else {
  12954. prevPoint = points[i - 1];
  12955. nextPoint = points[i + 1];
  12956. }
  12957. }
  12958. sub(v, nextPoint, prevPoint);
  12959. scale(v, v, smooth);
  12960. var d0 = distance(point, prevPoint);
  12961. var d1 = distance(point, nextPoint);
  12962. var sum = d0 + d1;
  12963. if (sum !== 0) {
  12964. d0 /= sum;
  12965. d1 /= sum;
  12966. }
  12967. scale(v1, v, -d0);
  12968. scale(v2, v, d1);
  12969. var cp0 = add([], point, v1);
  12970. var cp1 = add([], point, v2);
  12971. if (constraint) {
  12972. max(cp0, cp0, min$1);
  12973. min(cp0, cp0, max$1);
  12974. max(cp1, cp1, min$1);
  12975. min(cp1, cp1, max$1);
  12976. }
  12977. cps.push(cp0);
  12978. cps.push(cp1);
  12979. }
  12980. if (isLoop) {
  12981. cps.push(cps.shift());
  12982. }
  12983. return cps;
  12984. }
  12985. function buildPath$2(ctx, shape, closePath) {
  12986. var smooth = shape.smooth;
  12987. var points = shape.points;
  12988. if (points && points.length >= 2) {
  12989. if (smooth && smooth !== 'spline') {
  12990. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  12991. ctx.moveTo(points[0][0], points[0][1]);
  12992. var len = points.length;
  12993. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  12994. var cp1 = controlPoints[i * 2];
  12995. var cp2 = controlPoints[i * 2 + 1];
  12996. var p = points[(i + 1) % len];
  12997. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  12998. }
  12999. }
  13000. else {
  13001. if (smooth === 'spline') {
  13002. points = smoothSpline(points, closePath);
  13003. }
  13004. ctx.moveTo(points[0][0], points[0][1]);
  13005. for (var i = 1, l = points.length; i < l; i++) {
  13006. ctx.lineTo(points[i][0], points[i][1]);
  13007. }
  13008. }
  13009. closePath && ctx.closePath();
  13010. }
  13011. }
  13012. var PolygonShape = (function () {
  13013. function PolygonShape() {
  13014. this.points = null;
  13015. this.smooth = 0;
  13016. this.smoothConstraint = null;
  13017. }
  13018. return PolygonShape;
  13019. }());
  13020. var Polygon = (function (_super) {
  13021. __extends(Polygon, _super);
  13022. function Polygon(opts) {
  13023. return _super.call(this, opts) || this;
  13024. }
  13025. Polygon.prototype.getDefaultShape = function () {
  13026. return new PolygonShape();
  13027. };
  13028. Polygon.prototype.buildPath = function (ctx, shape) {
  13029. buildPath$2(ctx, shape, true);
  13030. };
  13031. return Polygon;
  13032. }(Path));
  13033. Polygon.prototype.type = 'polygon';
  13034. var PolylineShape = (function () {
  13035. function PolylineShape() {
  13036. this.points = null;
  13037. this.percent = 1;
  13038. this.smooth = 0;
  13039. this.smoothConstraint = null;
  13040. }
  13041. return PolylineShape;
  13042. }());
  13043. var Polyline = (function (_super) {
  13044. __extends(Polyline, _super);
  13045. function Polyline(opts) {
  13046. return _super.call(this, opts) || this;
  13047. }
  13048. Polyline.prototype.getDefaultStyle = function () {
  13049. return {
  13050. stroke: '#000',
  13051. fill: null
  13052. };
  13053. };
  13054. Polyline.prototype.getDefaultShape = function () {
  13055. return new PolylineShape();
  13056. };
  13057. Polyline.prototype.buildPath = function (ctx, shape) {
  13058. buildPath$2(ctx, shape, false);
  13059. };
  13060. return Polyline;
  13061. }(Path));
  13062. Polyline.prototype.type = 'polyline';
  13063. var subPixelOptimizeOutputShape$1 = {};
  13064. var LineShape = (function () {
  13065. function LineShape() {
  13066. this.x1 = 0;
  13067. this.y1 = 0;
  13068. this.x2 = 0;
  13069. this.y2 = 0;
  13070. this.percent = 1;
  13071. }
  13072. return LineShape;
  13073. }());
  13074. var Line = (function (_super) {
  13075. __extends(Line, _super);
  13076. function Line(opts) {
  13077. return _super.call(this, opts) || this;
  13078. }
  13079. Line.prototype.getDefaultStyle = function () {
  13080. return {
  13081. stroke: '#000',
  13082. fill: null
  13083. };
  13084. };
  13085. Line.prototype.getDefaultShape = function () {
  13086. return new LineShape();
  13087. };
  13088. Line.prototype.buildPath = function (ctx, shape) {
  13089. var x1;
  13090. var y1;
  13091. var x2;
  13092. var y2;
  13093. if (this.subPixelOptimize) {
  13094. var optimizedShape = subPixelOptimizeLine(subPixelOptimizeOutputShape$1, shape, this.style);
  13095. x1 = optimizedShape.x1;
  13096. y1 = optimizedShape.y1;
  13097. x2 = optimizedShape.x2;
  13098. y2 = optimizedShape.y2;
  13099. }
  13100. else {
  13101. x1 = shape.x1;
  13102. y1 = shape.y1;
  13103. x2 = shape.x2;
  13104. y2 = shape.y2;
  13105. }
  13106. var percent = shape.percent;
  13107. if (percent === 0) {
  13108. return;
  13109. }
  13110. ctx.moveTo(x1, y1);
  13111. if (percent < 1) {
  13112. x2 = x1 * (1 - percent) + x2 * percent;
  13113. y2 = y1 * (1 - percent) + y2 * percent;
  13114. }
  13115. ctx.lineTo(x2, y2);
  13116. };
  13117. Line.prototype.pointAt = function (p) {
  13118. var shape = this.shape;
  13119. return [
  13120. shape.x1 * (1 - p) + shape.x2 * p,
  13121. shape.y1 * (1 - p) + shape.y2 * p
  13122. ];
  13123. };
  13124. return Line;
  13125. }(Path));
  13126. Line.prototype.type = 'line';
  13127. var out = [];
  13128. var BezierCurveShape = (function () {
  13129. function BezierCurveShape() {
  13130. this.x1 = 0;
  13131. this.y1 = 0;
  13132. this.x2 = 0;
  13133. this.y2 = 0;
  13134. this.cpx1 = 0;
  13135. this.cpy1 = 0;
  13136. this.percent = 1;
  13137. }
  13138. return BezierCurveShape;
  13139. }());
  13140. function someVectorAt(shape, t, isTangent) {
  13141. var cpx2 = shape.cpx2;
  13142. var cpy2 = shape.cpy2;
  13143. if (cpx2 === null || cpy2 === null) {
  13144. return [
  13145. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13146. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13147. ];
  13148. }
  13149. else {
  13150. return [
  13151. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13152. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13153. ];
  13154. }
  13155. }
  13156. var BezierCurve = (function (_super) {
  13157. __extends(BezierCurve, _super);
  13158. function BezierCurve(opts) {
  13159. return _super.call(this, opts) || this;
  13160. }
  13161. BezierCurve.prototype.getDefaultStyle = function () {
  13162. return {
  13163. stroke: '#000',
  13164. fill: null
  13165. };
  13166. };
  13167. BezierCurve.prototype.getDefaultShape = function () {
  13168. return new BezierCurveShape();
  13169. };
  13170. BezierCurve.prototype.buildPath = function (ctx, shape) {
  13171. var x1 = shape.x1;
  13172. var y1 = shape.y1;
  13173. var x2 = shape.x2;
  13174. var y2 = shape.y2;
  13175. var cpx1 = shape.cpx1;
  13176. var cpy1 = shape.cpy1;
  13177. var cpx2 = shape.cpx2;
  13178. var cpy2 = shape.cpy2;
  13179. var percent = shape.percent;
  13180. if (percent === 0) {
  13181. return;
  13182. }
  13183. ctx.moveTo(x1, y1);
  13184. if (cpx2 == null || cpy2 == null) {
  13185. if (percent < 1) {
  13186. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13187. cpx1 = out[1];
  13188. x2 = out[2];
  13189. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13190. cpy1 = out[1];
  13191. y2 = out[2];
  13192. }
  13193. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13194. }
  13195. else {
  13196. if (percent < 1) {
  13197. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13198. cpx1 = out[1];
  13199. cpx2 = out[2];
  13200. x2 = out[3];
  13201. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13202. cpy1 = out[1];
  13203. cpy2 = out[2];
  13204. y2 = out[3];
  13205. }
  13206. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13207. }
  13208. };
  13209. BezierCurve.prototype.pointAt = function (t) {
  13210. return someVectorAt(this.shape, t, false);
  13211. };
  13212. BezierCurve.prototype.tangentAt = function (t) {
  13213. var p = someVectorAt(this.shape, t, true);
  13214. return normalize(p, p);
  13215. };
  13216. return BezierCurve;
  13217. }(Path));
  13218. BezierCurve.prototype.type = 'bezier-curve';
  13219. var ArcShape = (function () {
  13220. function ArcShape() {
  13221. this.cx = 0;
  13222. this.cy = 0;
  13223. this.r = 0;
  13224. this.startAngle = 0;
  13225. this.endAngle = Math.PI * 2;
  13226. this.clockwise = true;
  13227. }
  13228. return ArcShape;
  13229. }());
  13230. var Arc = (function (_super) {
  13231. __extends(Arc, _super);
  13232. function Arc(opts) {
  13233. return _super.call(this, opts) || this;
  13234. }
  13235. Arc.prototype.getDefaultStyle = function () {
  13236. return {
  13237. stroke: '#000',
  13238. fill: null
  13239. };
  13240. };
  13241. Arc.prototype.getDefaultShape = function () {
  13242. return new ArcShape();
  13243. };
  13244. Arc.prototype.buildPath = function (ctx, shape) {
  13245. var x = shape.cx;
  13246. var y = shape.cy;
  13247. var r = Math.max(shape.r, 0);
  13248. var startAngle = shape.startAngle;
  13249. var endAngle = shape.endAngle;
  13250. var clockwise = shape.clockwise;
  13251. var unitX = Math.cos(startAngle);
  13252. var unitY = Math.sin(startAngle);
  13253. ctx.moveTo(unitX * r + x, unitY * r + y);
  13254. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13255. };
  13256. return Arc;
  13257. }(Path));
  13258. Arc.prototype.type = 'arc';
  13259. var CompoundPath = (function (_super) {
  13260. __extends(CompoundPath, _super);
  13261. function CompoundPath() {
  13262. var _this = _super !== null && _super.apply(this, arguments) || this;
  13263. _this.type = 'compound';
  13264. return _this;
  13265. }
  13266. CompoundPath.prototype._updatePathDirty = function () {
  13267. var paths = this.shape.paths;
  13268. var dirtyPath = this.shapeChanged();
  13269. for (var i = 0; i < paths.length; i++) {
  13270. dirtyPath = dirtyPath || paths[i].shapeChanged();
  13271. }
  13272. if (dirtyPath) {
  13273. this.dirtyShape();
  13274. }
  13275. };
  13276. CompoundPath.prototype.beforeBrush = function () {
  13277. this._updatePathDirty();
  13278. var paths = this.shape.paths || [];
  13279. var scale = this.getGlobalScale();
  13280. for (var i = 0; i < paths.length; i++) {
  13281. if (!paths[i].path) {
  13282. paths[i].createPathProxy();
  13283. }
  13284. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13285. }
  13286. };
  13287. CompoundPath.prototype.buildPath = function (ctx, shape) {
  13288. var paths = shape.paths || [];
  13289. for (var i = 0; i < paths.length; i++) {
  13290. paths[i].buildPath(ctx, paths[i].shape, true);
  13291. }
  13292. };
  13293. CompoundPath.prototype.afterBrush = function () {
  13294. var paths = this.shape.paths || [];
  13295. for (var i = 0; i < paths.length; i++) {
  13296. paths[i].pathUpdated();
  13297. }
  13298. };
  13299. CompoundPath.prototype.getBoundingRect = function () {
  13300. this._updatePathDirty.call(this);
  13301. return Path.prototype.getBoundingRect.call(this);
  13302. };
  13303. return CompoundPath;
  13304. }(Path));
  13305. var Gradient = (function () {
  13306. function Gradient(colorStops) {
  13307. this.colorStops = colorStops || [];
  13308. }
  13309. Gradient.prototype.addColorStop = function (offset, color) {
  13310. this.colorStops.push({
  13311. offset: offset,
  13312. color: color
  13313. });
  13314. };
  13315. return Gradient;
  13316. }());
  13317. var LinearGradient = (function (_super) {
  13318. __extends(LinearGradient, _super);
  13319. function LinearGradient(x, y, x2, y2, colorStops, globalCoord) {
  13320. var _this = _super.call(this, colorStops) || this;
  13321. _this.x = x == null ? 0 : x;
  13322. _this.y = y == null ? 0 : y;
  13323. _this.x2 = x2 == null ? 1 : x2;
  13324. _this.y2 = y2 == null ? 0 : y2;
  13325. _this.type = 'linear';
  13326. _this.global = globalCoord || false;
  13327. return _this;
  13328. }
  13329. return LinearGradient;
  13330. }(Gradient));
  13331. var RadialGradient = (function (_super) {
  13332. __extends(RadialGradient, _super);
  13333. function RadialGradient(x, y, r, colorStops, globalCoord) {
  13334. var _this = _super.call(this, colorStops) || this;
  13335. _this.x = x == null ? 0.5 : x;
  13336. _this.y = y == null ? 0.5 : y;
  13337. _this.r = r == null ? 0.5 : r;
  13338. _this.type = 'radial';
  13339. _this.global = globalCoord || false;
  13340. return _this;
  13341. }
  13342. return RadialGradient;
  13343. }(Gradient));
  13344. var extent = [0, 0];
  13345. var extent2 = [0, 0];
  13346. var minTv$1 = new Point();
  13347. var maxTv$1 = new Point();
  13348. var OrientedBoundingRect = (function () {
  13349. function OrientedBoundingRect(rect, transform) {
  13350. this._corners = [];
  13351. this._axes = [];
  13352. this._origin = [0, 0];
  13353. for (var i = 0; i < 4; i++) {
  13354. this._corners[i] = new Point();
  13355. }
  13356. for (var i = 0; i < 2; i++) {
  13357. this._axes[i] = new Point();
  13358. }
  13359. if (rect) {
  13360. this.fromBoundingRect(rect, transform);
  13361. }
  13362. }
  13363. OrientedBoundingRect.prototype.fromBoundingRect = function (rect, transform) {
  13364. var corners = this._corners;
  13365. var axes = this._axes;
  13366. var x = rect.x;
  13367. var y = rect.y;
  13368. var x2 = x + rect.width;
  13369. var y2 = y + rect.height;
  13370. corners[0].set(x, y);
  13371. corners[1].set(x2, y);
  13372. corners[2].set(x2, y2);
  13373. corners[3].set(x, y2);
  13374. if (transform) {
  13375. for (var i = 0; i < 4; i++) {
  13376. corners[i].transform(transform);
  13377. }
  13378. }
  13379. Point.sub(axes[0], corners[1], corners[0]);
  13380. Point.sub(axes[1], corners[3], corners[0]);
  13381. axes[0].normalize();
  13382. axes[1].normalize();
  13383. for (var i = 0; i < 2; i++) {
  13384. this._origin[i] = axes[i].dot(corners[0]);
  13385. }
  13386. };
  13387. OrientedBoundingRect.prototype.intersect = function (other, mtv) {
  13388. var overlapped = true;
  13389. var noMtv = !mtv;
  13390. minTv$1.set(Infinity, Infinity);
  13391. maxTv$1.set(0, 0);
  13392. if (!this._intersectCheckOneSide(this, other, minTv$1, maxTv$1, noMtv, 1)) {
  13393. overlapped = false;
  13394. if (noMtv) {
  13395. return overlapped;
  13396. }
  13397. }
  13398. if (!this._intersectCheckOneSide(other, this, minTv$1, maxTv$1, noMtv, -1)) {
  13399. overlapped = false;
  13400. if (noMtv) {
  13401. return overlapped;
  13402. }
  13403. }
  13404. if (!noMtv) {
  13405. Point.copy(mtv, overlapped ? minTv$1 : maxTv$1);
  13406. }
  13407. return overlapped;
  13408. };
  13409. OrientedBoundingRect.prototype._intersectCheckOneSide = function (self, other, minTv, maxTv, noMtv, inverse) {
  13410. var overlapped = true;
  13411. for (var i = 0; i < 2; i++) {
  13412. var axis = this._axes[i];
  13413. this._getProjMinMaxOnAxis(i, self._corners, extent);
  13414. this._getProjMinMaxOnAxis(i, other._corners, extent2);
  13415. if (extent[1] < extent2[0] || extent[0] > extent2[1]) {
  13416. overlapped = false;
  13417. if (noMtv) {
  13418. return overlapped;
  13419. }
  13420. var dist0 = Math.abs(extent2[0] - extent[1]);
  13421. var dist1 = Math.abs(extent[0] - extent2[1]);
  13422. if (Math.min(dist0, dist1) > maxTv.len()) {
  13423. if (dist0 < dist1) {
  13424. Point.scale(maxTv, axis, -dist0 * inverse);
  13425. }
  13426. else {
  13427. Point.scale(maxTv, axis, dist1 * inverse);
  13428. }
  13429. }
  13430. }
  13431. else if (minTv) {
  13432. var dist0 = Math.abs(extent2[0] - extent[1]);
  13433. var dist1 = Math.abs(extent[0] - extent2[1]);
  13434. if (Math.min(dist0, dist1) < minTv.len()) {
  13435. if (dist0 < dist1) {
  13436. Point.scale(minTv, axis, dist0 * inverse);
  13437. }
  13438. else {
  13439. Point.scale(minTv, axis, -dist1 * inverse);
  13440. }
  13441. }
  13442. }
  13443. }
  13444. return overlapped;
  13445. };
  13446. OrientedBoundingRect.prototype._getProjMinMaxOnAxis = function (dim, corners, out) {
  13447. var axis = this._axes[dim];
  13448. var origin = this._origin;
  13449. var proj = corners[0].dot(axis) + origin[dim];
  13450. var min = proj;
  13451. var max = proj;
  13452. for (var i = 1; i < corners.length; i++) {
  13453. var proj_1 = corners[i].dot(axis) + origin[dim];
  13454. min = Math.min(proj_1, min);
  13455. max = Math.max(proj_1, max);
  13456. }
  13457. out[0] = min;
  13458. out[1] = max;
  13459. };
  13460. return OrientedBoundingRect;
  13461. }());
  13462. var m = [];
  13463. var IncrementalDisplayable = (function (_super) {
  13464. __extends(IncrementalDisplayable, _super);
  13465. function IncrementalDisplayable() {
  13466. var _this = _super !== null && _super.apply(this, arguments) || this;
  13467. _this.notClear = true;
  13468. _this.incremental = true;
  13469. _this._displayables = [];
  13470. _this._temporaryDisplayables = [];
  13471. _this._cursor = 0;
  13472. return _this;
  13473. }
  13474. IncrementalDisplayable.prototype.traverse = function (cb, context) {
  13475. cb.call(context, this);
  13476. };
  13477. IncrementalDisplayable.prototype.useStyle = function () {
  13478. this.style = {};
  13479. };
  13480. IncrementalDisplayable.prototype.getCursor = function () {
  13481. return this._cursor;
  13482. };
  13483. IncrementalDisplayable.prototype.innerAfterBrush = function () {
  13484. this._cursor = this._displayables.length;
  13485. };
  13486. IncrementalDisplayable.prototype.clearDisplaybles = function () {
  13487. this._displayables = [];
  13488. this._temporaryDisplayables = [];
  13489. this._cursor = 0;
  13490. this.markRedraw();
  13491. this.notClear = false;
  13492. };
  13493. IncrementalDisplayable.prototype.clearTemporalDisplayables = function () {
  13494. this._temporaryDisplayables = [];
  13495. };
  13496. IncrementalDisplayable.prototype.addDisplayable = function (displayable, notPersistent) {
  13497. if (notPersistent) {
  13498. this._temporaryDisplayables.push(displayable);
  13499. }
  13500. else {
  13501. this._displayables.push(displayable);
  13502. }
  13503. this.markRedraw();
  13504. };
  13505. IncrementalDisplayable.prototype.addDisplayables = function (displayables, notPersistent) {
  13506. notPersistent = notPersistent || false;
  13507. for (var i = 0; i < displayables.length; i++) {
  13508. this.addDisplayable(displayables[i], notPersistent);
  13509. }
  13510. };
  13511. IncrementalDisplayable.prototype.getDisplayables = function () {
  13512. return this._displayables;
  13513. };
  13514. IncrementalDisplayable.prototype.getTemporalDisplayables = function () {
  13515. return this._temporaryDisplayables;
  13516. };
  13517. IncrementalDisplayable.prototype.eachPendingDisplayable = function (cb) {
  13518. for (var i = this._cursor; i < this._displayables.length; i++) {
  13519. cb && cb(this._displayables[i]);
  13520. }
  13521. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13522. cb && cb(this._temporaryDisplayables[i]);
  13523. }
  13524. };
  13525. IncrementalDisplayable.prototype.update = function () {
  13526. this.updateTransform();
  13527. for (var i = this._cursor; i < this._displayables.length; i++) {
  13528. var displayable = this._displayables[i];
  13529. displayable.parent = this;
  13530. displayable.update();
  13531. displayable.parent = null;
  13532. }
  13533. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13534. var displayable = this._temporaryDisplayables[i];
  13535. displayable.parent = this;
  13536. displayable.update();
  13537. displayable.parent = null;
  13538. }
  13539. };
  13540. IncrementalDisplayable.prototype.getBoundingRect = function () {
  13541. if (!this._rect) {
  13542. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13543. for (var i = 0; i < this._displayables.length; i++) {
  13544. var displayable = this._displayables[i];
  13545. var childRect = displayable.getBoundingRect().clone();
  13546. if (displayable.needLocalTransform()) {
  13547. childRect.applyTransform(displayable.getLocalTransform(m));
  13548. }
  13549. rect.union(childRect);
  13550. }
  13551. this._rect = rect;
  13552. }
  13553. return this._rect;
  13554. };
  13555. IncrementalDisplayable.prototype.contain = function (x, y) {
  13556. var localPos = this.transformCoordToLocal(x, y);
  13557. var rect = this.getBoundingRect();
  13558. if (rect.contain(localPos[0], localPos[1])) {
  13559. for (var i = 0; i < this._displayables.length; i++) {
  13560. var displayable = this._displayables[i];
  13561. if (displayable.contain(x, y)) {
  13562. return true;
  13563. }
  13564. }
  13565. }
  13566. return false;
  13567. };
  13568. return IncrementalDisplayable;
  13569. }(Displayable));
  13570. var mathMax$4 = Math.max;
  13571. var mathMin$4 = Math.min;
  13572. var _customShapeMap = {};
  13573. /**
  13574. * Extend shape with parameters
  13575. */
  13576. function extendShape(opts) {
  13577. return Path.extend(opts);
  13578. }
  13579. var extendPathFromString = extendFromString;
  13580. /**
  13581. * Extend path
  13582. */
  13583. function extendPath(pathData, opts) {
  13584. return extendPathFromString(pathData, opts);
  13585. }
  13586. /**
  13587. * Register a user defined shape.
  13588. * The shape class can be fetched by `getShapeClass`
  13589. * This method will overwrite the registered shapes, including
  13590. * the registered built-in shapes, if using the same `name`.
  13591. * The shape can be used in `custom series` and
  13592. * `graphic component` by declaring `{type: name}`.
  13593. *
  13594. * @param name
  13595. * @param ShapeClass Can be generated by `extendShape`.
  13596. */
  13597. function registerShape(name, ShapeClass) {
  13598. _customShapeMap[name] = ShapeClass;
  13599. }
  13600. /**
  13601. * Find shape class registered by `registerShape`. Usually used in
  13602. * fetching user defined shape.
  13603. *
  13604. * [Caution]:
  13605. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13606. * to use user registered shapes.
  13607. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13608. * `registerShape` by default. That enables users to get both built-in
  13609. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13610. * the built-in shapes by using names like 'circle', 'rect' via calling
  13611. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13612. * in case that it is overwritten by users, except that some features, like
  13613. * `custom series`, `graphic component`, do it deliberately.
  13614. *
  13615. * (2) In the features like `custom series`, `graphic component`, the user input
  13616. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13617. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13618. * are reserved names, that is, if some user register a shape named `'image'`,
  13619. * the shape will not be used. If we intending to add some more reserved names
  13620. * in feature, that might bring break changes (disable some existing user shape
  13621. * names). But that case probably rearly happen. So we dont make more mechanism
  13622. * to resolve this issue here.
  13623. *
  13624. * @param name
  13625. * @return The shape class. If not found, return nothing.
  13626. */
  13627. function getShapeClass(name) {
  13628. if (_customShapeMap.hasOwnProperty(name)) {
  13629. return _customShapeMap[name];
  13630. }
  13631. }
  13632. /**
  13633. * Create a path element from path data string
  13634. * @param pathData
  13635. * @param opts
  13636. * @param rect
  13637. * @param layout 'center' or 'cover' default to be cover
  13638. */
  13639. function makePath(pathData, opts, rect, layout) {
  13640. var path = createFromString(pathData, opts);
  13641. if (rect) {
  13642. if (layout === 'center') {
  13643. rect = centerGraphic(rect, path.getBoundingRect());
  13644. }
  13645. resizePath(path, rect);
  13646. }
  13647. return path;
  13648. }
  13649. /**
  13650. * Create a image element from image url
  13651. * @param imageUrl image url
  13652. * @param opts options
  13653. * @param rect constrain rect
  13654. * @param layout 'center' or 'cover'. Default to be 'cover'
  13655. */
  13656. function makeImage(imageUrl, rect, layout) {
  13657. var zrImg = new ZRImage({
  13658. style: {
  13659. image: imageUrl,
  13660. x: rect.x,
  13661. y: rect.y,
  13662. width: rect.width,
  13663. height: rect.height
  13664. },
  13665. onload: function (img) {
  13666. if (layout === 'center') {
  13667. var boundingRect = {
  13668. width: img.width,
  13669. height: img.height
  13670. };
  13671. zrImg.setStyle(centerGraphic(rect, boundingRect));
  13672. }
  13673. }
  13674. });
  13675. return zrImg;
  13676. }
  13677. /**
  13678. * Get position of centered element in bounding box.
  13679. *
  13680. * @param rect element local bounding box
  13681. * @param boundingRect constraint bounding box
  13682. * @return element position containing x, y, width, and height
  13683. */
  13684. function centerGraphic(rect, boundingRect) {
  13685. // Set rect to center, keep width / height ratio.
  13686. var aspect = boundingRect.width / boundingRect.height;
  13687. var width = rect.height * aspect;
  13688. var height;
  13689. if (width <= rect.width) {
  13690. height = rect.height;
  13691. } else {
  13692. width = rect.width;
  13693. height = width / aspect;
  13694. }
  13695. var cx = rect.x + rect.width / 2;
  13696. var cy = rect.y + rect.height / 2;
  13697. return {
  13698. x: cx - width / 2,
  13699. y: cy - height / 2,
  13700. width: width,
  13701. height: height
  13702. };
  13703. }
  13704. var mergePath$1 = mergePath;
  13705. /**
  13706. * Resize a path to fit the rect
  13707. * @param path
  13708. * @param rect
  13709. */
  13710. function resizePath(path, rect) {
  13711. if (!path.applyTransform) {
  13712. return;
  13713. }
  13714. var pathRect = path.getBoundingRect();
  13715. var m = pathRect.calculateTransform(rect);
  13716. path.applyTransform(m);
  13717. }
  13718. /**
  13719. * Sub pixel optimize line for canvas
  13720. */
  13721. function subPixelOptimizeLine$1(param) {
  13722. subPixelOptimizeLine(param.shape, param.shape, param.style);
  13723. return param;
  13724. }
  13725. /**
  13726. * Sub pixel optimize rect for canvas
  13727. */
  13728. function subPixelOptimizeRect$1(param) {
  13729. subPixelOptimizeRect(param.shape, param.shape, param.style);
  13730. return param;
  13731. }
  13732. /**
  13733. * Sub pixel optimize for canvas
  13734. *
  13735. * @param position Coordinate, such as x, y
  13736. * @param lineWidth Should be nonnegative integer.
  13737. * @param positiveOrNegative Default false (negative).
  13738. * @return Optimized position.
  13739. */
  13740. var subPixelOptimize$1 = subPixelOptimize;
  13741. function animateOrSetProps(animationType, el, props, animatableModel, dataIndex, cb, during) {
  13742. var isFrom = false;
  13743. var removeOpt;
  13744. if (typeof dataIndex === 'function') {
  13745. during = cb;
  13746. cb = dataIndex;
  13747. dataIndex = null;
  13748. } else if (isObject(dataIndex)) {
  13749. cb = dataIndex.cb;
  13750. during = dataIndex.during;
  13751. isFrom = dataIndex.isFrom;
  13752. removeOpt = dataIndex.removeOpt;
  13753. dataIndex = dataIndex.dataIndex;
  13754. }
  13755. var isUpdate = animationType === 'update';
  13756. var isRemove = animationType === 'remove';
  13757. var animationPayload; // Check if there is global animation configuration from dataZoom/resize can override the config in option.
  13758. // If animation is enabled. Will use this animation config in payload.
  13759. // If animation is disabled. Just ignore it.
  13760. if (animatableModel && animatableModel.ecModel) {
  13761. var updatePayload = animatableModel.ecModel.getUpdatePayload();
  13762. animationPayload = updatePayload && updatePayload.animation;
  13763. }
  13764. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  13765. if (!isRemove) {
  13766. // Must stop the remove animation.
  13767. el.stopAnimation('remove');
  13768. }
  13769. if (animationEnabled) {
  13770. var duration = void 0;
  13771. var animationEasing = void 0;
  13772. var animationDelay = void 0;
  13773. if (animationPayload) {
  13774. duration = animationPayload.duration || 0;
  13775. animationEasing = animationPayload.easing || 'cubicOut';
  13776. animationDelay = animationPayload.delay || 0;
  13777. } else if (isRemove) {
  13778. removeOpt = removeOpt || {};
  13779. duration = retrieve2(removeOpt.duration, 200);
  13780. animationEasing = retrieve2(removeOpt.easing, 'cubicOut');
  13781. animationDelay = 0;
  13782. } else {
  13783. duration = animatableModel.getShallow(isUpdate ? 'animationDurationUpdate' : 'animationDuration');
  13784. animationEasing = animatableModel.getShallow(isUpdate ? 'animationEasingUpdate' : 'animationEasing');
  13785. animationDelay = animatableModel.getShallow(isUpdate ? 'animationDelayUpdate' : 'animationDelay');
  13786. }
  13787. if (typeof animationDelay === 'function') {
  13788. animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  13789. }
  13790. if (typeof duration === 'function') {
  13791. duration = duration(dataIndex);
  13792. }
  13793. duration > 0 ? isFrom ? el.animateFrom(props, {
  13794. duration: duration,
  13795. delay: animationDelay || 0,
  13796. easing: animationEasing,
  13797. done: cb,
  13798. force: !!cb || !!during,
  13799. scope: animationType,
  13800. during: during
  13801. }) : el.animateTo(props, {
  13802. duration: duration,
  13803. delay: animationDelay || 0,
  13804. easing: animationEasing,
  13805. done: cb,
  13806. force: !!cb || !!during,
  13807. setToFinal: true,
  13808. scope: animationType,
  13809. during: during
  13810. }) : ( // FIXME:
  13811. // If `duration` is 0, only the animation on props
  13812. // can be stoped, other animation should be continued?
  13813. // But at present using duration 0 in `animateTo`, `animateFrom`
  13814. // might cause unexpected behavior.
  13815. el.stopAnimation(), // If `isFrom`, the props is the "from" props.
  13816. !isFrom && el.attr(props), cb && cb());
  13817. } else {
  13818. el.stopAnimation();
  13819. !isFrom && el.attr(props); // Call during once.
  13820. during && during(1);
  13821. cb && cb();
  13822. }
  13823. }
  13824. /**
  13825. * Update graphic element properties with or without animation according to the
  13826. * configuration in series.
  13827. *
  13828. * Caution: this method will stop previous animation.
  13829. * So do not use this method to one element twice before
  13830. * animation starts, unless you know what you are doing.
  13831. * @example
  13832. * graphic.updateProps(el, {
  13833. * position: [100, 100]
  13834. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  13835. * // Or
  13836. * graphic.updateProps(el, {
  13837. * position: [100, 100]
  13838. * }, seriesModel, function () { console.log('Animation done!'); });
  13839. */
  13840. function updateProps(el, props, // TODO: TYPE AnimatableModel
  13841. animatableModel, dataIndex, cb, during) {
  13842. animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
  13843. }
  13844. /**
  13845. * Init graphic element properties with or without animation according to the
  13846. * configuration in series.
  13847. *
  13848. * Caution: this method will stop previous animation.
  13849. * So do not use this method to one element twice before
  13850. * animation starts, unless you know what you are doing.
  13851. */
  13852. function initProps(el, props, animatableModel, dataIndex, cb, during) {
  13853. animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);
  13854. }
  13855. /**
  13856. * Remove graphic element
  13857. */
  13858. function removeElement(el, props, animatableModel, dataIndex, cb, during) {
  13859. // Don't do remove animation twice.
  13860. if (isElementRemoved(el)) {
  13861. return;
  13862. }
  13863. animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during);
  13864. }
  13865. function fadeOutDisplayable(el, animatableModel, dataIndex, done) {
  13866. el.removeTextContent();
  13867. el.removeTextGuideLine();
  13868. removeElement(el, {
  13869. style: {
  13870. opacity: 0
  13871. }
  13872. }, animatableModel, dataIndex, done);
  13873. }
  13874. function removeElementWithFadeOut(el, animatableModel, dataIndex) {
  13875. function doRemove() {
  13876. el.parent && el.parent.remove(el);
  13877. } // Hide label and labelLine first
  13878. // TODO Also use fade out animation?
  13879. if (!el.isGroup) {
  13880. fadeOutDisplayable(el, animatableModel, dataIndex, doRemove);
  13881. } else {
  13882. el.traverse(function (disp) {
  13883. if (!disp.isGroup) {
  13884. // Can invoke doRemove multiple times.
  13885. fadeOutDisplayable(disp, animatableModel, dataIndex, doRemove);
  13886. }
  13887. });
  13888. }
  13889. }
  13890. /**
  13891. * If element is removed.
  13892. * It can determine if element is having remove animation.
  13893. */
  13894. function isElementRemoved(el) {
  13895. if (!el.__zr) {
  13896. return true;
  13897. }
  13898. for (var i = 0; i < el.animators.length; i++) {
  13899. var animator = el.animators[i];
  13900. if (animator.scope === 'remove') {
  13901. return true;
  13902. }
  13903. }
  13904. return false;
  13905. }
  13906. /**
  13907. * Get transform matrix of target (param target),
  13908. * in coordinate of its ancestor (param ancestor)
  13909. *
  13910. * @param target
  13911. * @param [ancestor]
  13912. */
  13913. function getTransform(target, ancestor) {
  13914. var mat = identity([]);
  13915. while (target && target !== ancestor) {
  13916. mul$1(mat, target.getLocalTransform(), mat);
  13917. target = target.parent;
  13918. }
  13919. return mat;
  13920. }
  13921. /**
  13922. * Apply transform to an vertex.
  13923. * @param target [x, y]
  13924. * @param transform Can be:
  13925. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  13926. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  13927. * @param invert Whether use invert matrix.
  13928. * @return [x, y]
  13929. */
  13930. function applyTransform$1(target, transform, invert$1) {
  13931. if (transform && !isArrayLike(transform)) {
  13932. transform = Transformable.getLocalTransform(transform);
  13933. }
  13934. if (invert$1) {
  13935. transform = invert([], transform);
  13936. }
  13937. return applyTransform([], target, transform);
  13938. }
  13939. /**
  13940. * @param direction 'left' 'right' 'top' 'bottom'
  13941. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  13942. * @param invert Whether use invert matrix.
  13943. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  13944. */
  13945. function transformDirection(direction, transform, invert) {
  13946. // Pick a base, ensure that transform result will not be (0, 0).
  13947. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  13948. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  13949. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  13950. vertex = applyTransform$1(vertex, transform, invert);
  13951. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  13952. }
  13953. function isNotGroup(el) {
  13954. return !el.isGroup;
  13955. }
  13956. function isPath(el) {
  13957. return el.shape != null;
  13958. }
  13959. /**
  13960. * Apply group transition animation from g1 to g2.
  13961. * If no animatableModel, no animation.
  13962. */
  13963. function groupTransition(g1, g2, animatableModel) {
  13964. if (!g1 || !g2) {
  13965. return;
  13966. }
  13967. function getElMap(g) {
  13968. var elMap = {};
  13969. g.traverse(function (el) {
  13970. if (isNotGroup(el) && el.anid) {
  13971. elMap[el.anid] = el;
  13972. }
  13973. });
  13974. return elMap;
  13975. }
  13976. function getAnimatableProps(el) {
  13977. var obj = {
  13978. x: el.x,
  13979. y: el.y,
  13980. rotation: el.rotation
  13981. };
  13982. if (isPath(el)) {
  13983. obj.shape = extend({}, el.shape);
  13984. }
  13985. return obj;
  13986. }
  13987. var elMap1 = getElMap(g1);
  13988. g2.traverse(function (el) {
  13989. if (isNotGroup(el) && el.anid) {
  13990. var oldEl = elMap1[el.anid];
  13991. if (oldEl) {
  13992. var newProp = getAnimatableProps(el);
  13993. el.attr(getAnimatableProps(oldEl));
  13994. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  13995. }
  13996. }
  13997. });
  13998. }
  13999. function clipPointsByRect(points, rect) {
  14000. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14001. // and when element have border.
  14002. return map(points, function (point) {
  14003. var x = point[0];
  14004. x = mathMax$4(x, rect.x);
  14005. x = mathMin$4(x, rect.x + rect.width);
  14006. var y = point[1];
  14007. y = mathMax$4(y, rect.y);
  14008. y = mathMin$4(y, rect.y + rect.height);
  14009. return [x, y];
  14010. });
  14011. }
  14012. /**
  14013. * Return a new clipped rect. If rect size are negative, return undefined.
  14014. */
  14015. function clipRectByRect(targetRect, rect) {
  14016. var x = mathMax$4(targetRect.x, rect.x);
  14017. var x2 = mathMin$4(targetRect.x + targetRect.width, rect.x + rect.width);
  14018. var y = mathMax$4(targetRect.y, rect.y);
  14019. var y2 = mathMin$4(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14020. // should be painted. So return undefined.
  14021. if (x2 >= x && y2 >= y) {
  14022. return {
  14023. x: x,
  14024. y: y,
  14025. width: x2 - x,
  14026. height: y2 - y
  14027. };
  14028. }
  14029. }
  14030. function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  14031. opt, rect) {
  14032. var innerOpts = extend({
  14033. rectHover: true
  14034. }, opt);
  14035. var style = innerOpts.style = {
  14036. strokeNoScale: true
  14037. };
  14038. rect = rect || {
  14039. x: -1,
  14040. y: -1,
  14041. width: 2,
  14042. height: 2
  14043. };
  14044. if (iconStr) {
  14045. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  14046. }
  14047. }
  14048. /**
  14049. * Return `true` if the given line (line `a`) and the given polygon
  14050. * are intersect.
  14051. * Note that we do not count colinear as intersect here because no
  14052. * requirement for that. We could do that if required in future.
  14053. */
  14054. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14055. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14056. var p = points[i];
  14057. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14058. return true;
  14059. }
  14060. p2 = p;
  14061. }
  14062. }
  14063. /**
  14064. * Return `true` if the given two lines (line `a` and line `b`)
  14065. * are intersect.
  14066. * Note that we do not count colinear as intersect here because no
  14067. * requirement for that. We could do that if required in future.
  14068. */
  14069. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14070. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14071. var mx = a2x - a1x;
  14072. var my = a2y - a1y;
  14073. var nx = b2x - b1x;
  14074. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  14075. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  14076. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  14077. if (nearZero(nmCrossProduct)) {
  14078. return false;
  14079. } // `vec_m` and `vec_n` are intersect iff
  14080. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  14081. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  14082. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  14083. var b1a1x = a1x - b1x;
  14084. var b1a1y = a1y - b1y;
  14085. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  14086. if (q < 0 || q > 1) {
  14087. return false;
  14088. }
  14089. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  14090. if (p < 0 || p > 1) {
  14091. return false;
  14092. }
  14093. return true;
  14094. }
  14095. /**
  14096. * Cross product of 2-dimension vector.
  14097. */
  14098. function crossProduct2d(x1, y1, x2, y2) {
  14099. return x1 * y2 - x2 * y1;
  14100. }
  14101. function nearZero(val) {
  14102. return val <= 1e-6 && val >= -1e-6;
  14103. } // Register built-in shapes. These shapes might be overwirtten
  14104. // by users, although we do not recommend that.
  14105. registerShape('circle', Circle);
  14106. registerShape('ellipse', Ellipse);
  14107. registerShape('sector', Sector);
  14108. registerShape('ring', Ring);
  14109. registerShape('polygon', Polygon);
  14110. registerShape('polyline', Polyline);
  14111. registerShape('rect', Rect);
  14112. registerShape('line', Line);
  14113. registerShape('bezierCurve', BezierCurve);
  14114. registerShape('arc', Arc);
  14115. var graphic = /*#__PURE__*/Object.freeze({
  14116. __proto__: null,
  14117. extendShape: extendShape,
  14118. extendPath: extendPath,
  14119. registerShape: registerShape,
  14120. getShapeClass: getShapeClass,
  14121. makePath: makePath,
  14122. makeImage: makeImage,
  14123. mergePath: mergePath$1,
  14124. resizePath: resizePath,
  14125. subPixelOptimizeLine: subPixelOptimizeLine$1,
  14126. subPixelOptimizeRect: subPixelOptimizeRect$1,
  14127. subPixelOptimize: subPixelOptimize$1,
  14128. updateProps: updateProps,
  14129. initProps: initProps,
  14130. removeElement: removeElement,
  14131. removeElementWithFadeOut: removeElementWithFadeOut,
  14132. isElementRemoved: isElementRemoved,
  14133. getTransform: getTransform,
  14134. applyTransform: applyTransform$1,
  14135. transformDirection: transformDirection,
  14136. groupTransition: groupTransition,
  14137. clipPointsByRect: clipPointsByRect,
  14138. clipRectByRect: clipRectByRect,
  14139. createIcon: createIcon,
  14140. linePolygonIntersect: linePolygonIntersect,
  14141. lineLineIntersect: lineLineIntersect,
  14142. Group: Group,
  14143. Image: ZRImage,
  14144. Text: ZRText,
  14145. Circle: Circle,
  14146. Ellipse: Ellipse,
  14147. Sector: Sector,
  14148. Ring: Ring,
  14149. Polygon: Polygon,
  14150. Polyline: Polyline,
  14151. Rect: Rect,
  14152. Line: Line,
  14153. BezierCurve: BezierCurve,
  14154. Arc: Arc,
  14155. IncrementalDisplayable: IncrementalDisplayable,
  14156. CompoundPath: CompoundPath,
  14157. LinearGradient: LinearGradient,
  14158. RadialGradient: RadialGradient,
  14159. BoundingRect: BoundingRect,
  14160. OrientedBoundingRect: OrientedBoundingRect,
  14161. Point: Point,
  14162. Path: Path
  14163. });
  14164. var EMPTY_OBJ = {};
  14165. function setLabelText(label, labelTexts) {
  14166. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14167. var stateName = SPECIAL_STATES[i];
  14168. var text = labelTexts[stateName];
  14169. var state = label.ensureState(stateName);
  14170. state.style = state.style || {};
  14171. state.style.text = text;
  14172. }
  14173. var oldStates = label.currentStates.slice();
  14174. label.clearStates(true);
  14175. label.setStyle({
  14176. text: labelTexts.normal
  14177. });
  14178. label.useStates(oldStates, true);
  14179. }
  14180. function getLabelText(opt, stateModels, interpolatedValue) {
  14181. var labelFetcher = opt.labelFetcher;
  14182. var labelDataIndex = opt.labelDataIndex;
  14183. var labelDimIndex = opt.labelDimIndex;
  14184. var normalModel = stateModels.normal;
  14185. var baseText;
  14186. if (labelFetcher) {
  14187. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, normalModel && normalModel.get('formatter'), interpolatedValue != null ? {
  14188. interpolatedValue: interpolatedValue
  14189. } : null);
  14190. }
  14191. if (baseText == null) {
  14192. baseText = isFunction(opt.defaultText) ? opt.defaultText(labelDataIndex, opt, interpolatedValue) : opt.defaultText;
  14193. }
  14194. var statesText = {
  14195. normal: baseText
  14196. };
  14197. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14198. var stateName = SPECIAL_STATES[i];
  14199. var stateModel = stateModels[stateName];
  14200. statesText[stateName] = retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, stateName, null, labelDimIndex, stateModel && stateModel.get('formatter')) : null, baseText);
  14201. }
  14202. return statesText;
  14203. }
  14204. function setLabelStyle(targetEl, labelStatesModels, opt, stateSpecified // TODO specified position?
  14205. ) {
  14206. opt = opt || EMPTY_OBJ;
  14207. var isSetOnText = targetEl instanceof ZRText;
  14208. var needsCreateText = false;
  14209. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  14210. var stateModel = labelStatesModels[DISPLAY_STATES[i]];
  14211. if (stateModel && stateModel.getShallow('show')) {
  14212. needsCreateText = true;
  14213. break;
  14214. }
  14215. }
  14216. var textContent = isSetOnText ? targetEl : targetEl.getTextContent();
  14217. if (needsCreateText) {
  14218. if (!isSetOnText) {
  14219. // Reuse the previous
  14220. if (!textContent) {
  14221. textContent = new ZRText();
  14222. targetEl.setTextContent(textContent);
  14223. } // Use same state proxy
  14224. if (targetEl.stateProxy) {
  14225. textContent.stateProxy = targetEl.stateProxy;
  14226. }
  14227. }
  14228. var labelStatesTexts = getLabelText(opt, labelStatesModels);
  14229. var normalModel = labelStatesModels.normal;
  14230. var showNormal = !!normalModel.getShallow('show');
  14231. var normalStyle = createTextStyle(normalModel, stateSpecified && stateSpecified.normal, opt, false, !isSetOnText);
  14232. normalStyle.text = labelStatesTexts.normal;
  14233. if (!isSetOnText) {
  14234. // Always create new
  14235. targetEl.setTextConfig(createTextConfig(normalModel, opt, false));
  14236. }
  14237. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14238. var stateName = SPECIAL_STATES[i];
  14239. var stateModel = labelStatesModels[stateName];
  14240. if (stateModel) {
  14241. var stateObj = textContent.ensureState(stateName);
  14242. var stateShow = !!retrieve2(stateModel.getShallow('show'), showNormal);
  14243. if (stateShow !== showNormal) {
  14244. stateObj.ignore = !stateShow;
  14245. }
  14246. stateObj.style = createTextStyle(stateModel, stateSpecified && stateSpecified[stateName], opt, true, !isSetOnText);
  14247. stateObj.style.text = labelStatesTexts[stateName];
  14248. if (!isSetOnText) {
  14249. var targetElEmphasisState = targetEl.ensureState(stateName);
  14250. targetElEmphasisState.textConfig = createTextConfig(stateModel, opt, true);
  14251. }
  14252. }
  14253. } // PENDING: if there is many requirements that emphasis position
  14254. // need to be different from normal position, we might consider
  14255. // auto slient is those cases.
  14256. textContent.silent = !!normalModel.getShallow('silent'); // Keep x and y
  14257. if (textContent.style.x != null) {
  14258. normalStyle.x = textContent.style.x;
  14259. }
  14260. if (textContent.style.y != null) {
  14261. normalStyle.y = textContent.style.y;
  14262. }
  14263. textContent.ignore = !showNormal; // Always create new style.
  14264. textContent.useStyle(normalStyle);
  14265. textContent.dirty();
  14266. if (opt.enableTextSetter) {
  14267. labelInner(textContent).setLabelText = function (interpolatedValue) {
  14268. var labelStatesTexts = getLabelText(opt, labelStatesModels, interpolatedValue);
  14269. setLabelText(textContent, labelStatesTexts);
  14270. };
  14271. }
  14272. } else if (textContent) {
  14273. // Not display rich text.
  14274. textContent.ignore = true;
  14275. }
  14276. targetEl.dirty();
  14277. }
  14278. function getLabelStatesModels(itemModel, labelName) {
  14279. labelName = labelName || 'label';
  14280. var statesModels = {
  14281. normal: itemModel.getModel(labelName)
  14282. };
  14283. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  14284. var stateName = SPECIAL_STATES[i];
  14285. statesModels[stateName] = itemModel.getModel([stateName, labelName]);
  14286. }
  14287. return statesModels;
  14288. }
  14289. /**
  14290. * Set basic textStyle properties.
  14291. */
  14292. function createTextStyle(textStyleModel, specifiedTextStyle, // Fixed style in the code. Can't be set by model.
  14293. opt, isNotNormal, isAttached // If text is attached on an element. If so, auto color will handling in zrender.
  14294. ) {
  14295. var textStyle = {};
  14296. setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached);
  14297. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14298. return textStyle;
  14299. }
  14300. function createTextConfig(textStyleModel, opt, isNotNormal) {
  14301. opt = opt || {};
  14302. var textConfig = {};
  14303. var labelPosition;
  14304. var labelRotate = textStyleModel.getShallow('rotate');
  14305. var labelDistance = retrieve2(textStyleModel.getShallow('distance'), isNotNormal ? null : 5);
  14306. var labelOffset = textStyleModel.getShallow('offset');
  14307. labelPosition = textStyleModel.getShallow('position') || (isNotNormal ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14308. // in bar series, and magric type should be considered.
  14309. labelPosition === 'outside' && (labelPosition = opt.defaultOutsidePosition || 'top');
  14310. if (labelPosition != null) {
  14311. textConfig.position = labelPosition;
  14312. }
  14313. if (labelOffset != null) {
  14314. textConfig.offset = labelOffset;
  14315. }
  14316. if (labelRotate != null) {
  14317. labelRotate *= Math.PI / 180;
  14318. textConfig.rotation = labelRotate;
  14319. }
  14320. if (labelDistance != null) {
  14321. textConfig.distance = labelDistance;
  14322. } // fill and auto is determined by the color of path fill if it's not specified by developers.
  14323. textConfig.outsideFill = textStyleModel.get('color') === 'inherit' ? opt.inheritColor || null : 'auto';
  14324. return textConfig;
  14325. }
  14326. /**
  14327. * The uniform entry of set text style, that is, retrieve style definitions
  14328. * from `model` and set to `textStyle` object.
  14329. *
  14330. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14331. * properties will be set. (Consider the states of normal and emphasis and
  14332. * default value can be adopted, merge would make the logic too complicated
  14333. * to manage.)
  14334. */
  14335. function setTextStyleCommon(textStyle, textStyleModel, opt, isNotNormal, isAttached) {
  14336. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14337. opt = opt || EMPTY_OBJ;
  14338. var ecModel = textStyleModel.ecModel;
  14339. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14340. // {
  14341. // data: [{
  14342. // value: 12,
  14343. // label: {
  14344. // rich: {
  14345. // // no 'a' here but using parent 'a'.
  14346. // }
  14347. // }
  14348. // }],
  14349. // rich: {
  14350. // a: { ... }
  14351. // }
  14352. // }
  14353. var richItemNames = getRichItemNames(textStyleModel);
  14354. var richResult;
  14355. if (richItemNames) {
  14356. richResult = {};
  14357. for (var name_1 in richItemNames) {
  14358. if (richItemNames.hasOwnProperty(name_1)) {
  14359. // Cascade is supported in rich.
  14360. var richTextStyle = textStyleModel.getModel(['rich', name_1]); // In rich, never `disableBox`.
  14361. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14362. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14363. // That might confuses users. So probably we should put `textStyleModel` as the
  14364. // root ancestor of the `richTextStyle`. But that would be a break change.
  14365. setTokenTextStyle(richResult[name_1] = {}, richTextStyle, globalTextStyle, opt, isNotNormal, isAttached, false, true);
  14366. }
  14367. }
  14368. }
  14369. if (richResult) {
  14370. textStyle.rich = richResult;
  14371. }
  14372. var overflow = textStyleModel.get('overflow');
  14373. if (overflow) {
  14374. textStyle.overflow = overflow;
  14375. }
  14376. var margin = textStyleModel.get('minMargin');
  14377. if (margin != null) {
  14378. textStyle.margin = margin;
  14379. }
  14380. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, true, false);
  14381. } // Consider case:
  14382. // {
  14383. // data: [{
  14384. // value: 12,
  14385. // label: {
  14386. // rich: {
  14387. // // no 'a' here but using parent 'a'.
  14388. // }
  14389. // }
  14390. // }],
  14391. // rich: {
  14392. // a: { ... }
  14393. // }
  14394. // }
  14395. // TODO TextStyleModel
  14396. function getRichItemNames(textStyleModel) {
  14397. // Use object to remove duplicated names.
  14398. var richItemNameMap;
  14399. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14400. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14401. if (rich) {
  14402. richItemNameMap = richItemNameMap || {};
  14403. var richKeys = keys(rich);
  14404. for (var i = 0; i < richKeys.length; i++) {
  14405. var richKey = richKeys[i];
  14406. richItemNameMap[richKey] = 1;
  14407. }
  14408. }
  14409. textStyleModel = textStyleModel.parentModel;
  14410. }
  14411. return richItemNameMap;
  14412. }
  14413. var TEXT_PROPS_WITH_GLOBAL = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY'];
  14414. var TEXT_PROPS_SELF = ['align', 'lineHeight', 'width', 'height', 'tag', 'verticalAlign'];
  14415. var TEXT_PROPS_BOX = ['padding', 'borderWidth', 'borderRadius', 'borderDashOffset', 'backgroundColor', 'borderColor', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  14416. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isNotNormal, isAttached, isBlock, inRich) {
  14417. // In merge mode, default value should not be given.
  14418. globalTextStyle = !isNotNormal && globalTextStyle || EMPTY_OBJ;
  14419. var inheritColor = opt && opt.inheritColor;
  14420. var fillColor = textStyleModel.getShallow('color');
  14421. var strokeColor = textStyleModel.getShallow('textBorderColor');
  14422. var opacity = retrieve2(textStyleModel.getShallow('opacity'), globalTextStyle.opacity);
  14423. if (fillColor === 'inherit' || fillColor === 'auto') {
  14424. if ("development" !== 'production') {
  14425. if (fillColor === 'auto') {
  14426. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14427. }
  14428. }
  14429. if (inheritColor) {
  14430. fillColor = inheritColor;
  14431. } else {
  14432. fillColor = null;
  14433. }
  14434. }
  14435. if (strokeColor === 'inherit' || strokeColor === 'auto') {
  14436. if ("development" !== 'production') {
  14437. if (strokeColor === 'auto') {
  14438. deprecateReplaceLog('color: \'auto\'', 'color: \'inherit\'');
  14439. }
  14440. }
  14441. if (inheritColor) {
  14442. strokeColor = inheritColor;
  14443. } else {
  14444. strokeColor = null;
  14445. }
  14446. }
  14447. if (!isAttached) {
  14448. // Only use default global textStyle.color if text is individual.
  14449. // Otherwise it will use the strategy of attached text color because text may be on a path.
  14450. fillColor = fillColor || globalTextStyle.color;
  14451. strokeColor = strokeColor || globalTextStyle.textBorderColor;
  14452. }
  14453. if (fillColor != null) {
  14454. textStyle.fill = fillColor;
  14455. }
  14456. if (strokeColor != null) {
  14457. textStyle.stroke = strokeColor;
  14458. }
  14459. var textBorderWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14460. if (textBorderWidth != null) {
  14461. textStyle.lineWidth = textBorderWidth;
  14462. }
  14463. var textBorderType = retrieve2(textStyleModel.getShallow('textBorderType'), globalTextStyle.textBorderType);
  14464. if (textBorderType != null) {
  14465. textStyle.lineDash = textBorderType;
  14466. }
  14467. var textBorderDashOffset = retrieve2(textStyleModel.getShallow('textBorderDashOffset'), globalTextStyle.textBorderDashOffset);
  14468. if (textBorderDashOffset != null) {
  14469. textStyle.lineDashOffset = textBorderDashOffset;
  14470. }
  14471. if (!isNotNormal && opacity == null && !inRich) {
  14472. opacity = opt && opt.defaultOpacity;
  14473. }
  14474. if (opacity != null) {
  14475. textStyle.opacity = opacity;
  14476. } // TODO
  14477. if (!isNotNormal && !isAttached) {
  14478. // Set default finally.
  14479. if (textStyle.fill == null && opt.inheritColor) {
  14480. textStyle.fill = opt.inheritColor;
  14481. }
  14482. } // Do not use `getFont` here, because merge should be supported, where
  14483. // part of these properties may be changed in emphasis style, and the
  14484. // others should remain their original value got from normal style.
  14485. for (var i = 0; i < TEXT_PROPS_WITH_GLOBAL.length; i++) {
  14486. var key = TEXT_PROPS_WITH_GLOBAL[i];
  14487. var val = retrieve2(textStyleModel.getShallow(key), globalTextStyle[key]);
  14488. if (val != null) {
  14489. textStyle[key] = val;
  14490. }
  14491. }
  14492. for (var i = 0; i < TEXT_PROPS_SELF.length; i++) {
  14493. var key = TEXT_PROPS_SELF[i];
  14494. var val = textStyleModel.getShallow(key);
  14495. if (val != null) {
  14496. textStyle[key] = val;
  14497. }
  14498. }
  14499. if (textStyle.verticalAlign == null) {
  14500. var baseline = textStyleModel.getShallow('baseline');
  14501. if (baseline != null) {
  14502. textStyle.verticalAlign = baseline;
  14503. }
  14504. }
  14505. if (!isBlock || !opt.disableBox) {
  14506. for (var i = 0; i < TEXT_PROPS_BOX.length; i++) {
  14507. var key = TEXT_PROPS_BOX[i];
  14508. var val = textStyleModel.getShallow(key);
  14509. if (val != null) {
  14510. textStyle[key] = val;
  14511. }
  14512. }
  14513. var borderType = textStyleModel.getShallow('borderType');
  14514. if (borderType != null) {
  14515. textStyle.borderDash = borderType;
  14516. }
  14517. if ((textStyle.backgroundColor === 'auto' || textStyle.backgroundColor === 'inherit') && inheritColor) {
  14518. if ("development" !== 'production') {
  14519. if (textStyle.backgroundColor === 'auto') {
  14520. deprecateReplaceLog('backgroundColor: \'auto\'', 'backgroundColor: \'inherit\'');
  14521. }
  14522. }
  14523. textStyle.backgroundColor = inheritColor;
  14524. }
  14525. if ((textStyle.borderColor === 'auto' || textStyle.borderColor === 'inherit') && inheritColor) {
  14526. if ("development" !== 'production') {
  14527. if (textStyle.borderColor === 'auto') {
  14528. deprecateReplaceLog('borderColor: \'auto\'', 'borderColor: \'inherit\'');
  14529. }
  14530. }
  14531. textStyle.borderColor = inheritColor;
  14532. }
  14533. }
  14534. }
  14535. function getFont(opt, ecModel) {
  14536. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14537. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14538. 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(' '));
  14539. }
  14540. var labelInner = makeInner();
  14541. function setLabelValueAnimation(label, labelStatesModels, value, getDefaultText) {
  14542. if (!label) {
  14543. return;
  14544. }
  14545. var obj = labelInner(label);
  14546. obj.prevValue = obj.value;
  14547. obj.value = value;
  14548. var normalLabelModel = labelStatesModels.normal;
  14549. obj.valueAnimation = normalLabelModel.get('valueAnimation');
  14550. if (obj.valueAnimation) {
  14551. obj.precision = normalLabelModel.get('precision');
  14552. obj.defaultInterpolatedText = getDefaultText;
  14553. obj.statesModels = labelStatesModels;
  14554. }
  14555. }
  14556. function animateLabelValue(textEl, dataIndex, data, animatableModel, labelFetcher) {
  14557. var labelInnerStore = labelInner(textEl);
  14558. if (!labelInnerStore.valueAnimation) {
  14559. return;
  14560. }
  14561. var defaultInterpolatedText = labelInnerStore.defaultInterpolatedText; // Consider the case that being animating, do not use the `obj.value`,
  14562. // Otherwise it will jump to the `obj.value` when this new animation started.
  14563. var currValue = retrieve2(labelInnerStore.interpolatedValue, labelInnerStore.prevValue);
  14564. var targetValue = labelInnerStore.value;
  14565. function during(percent) {
  14566. var interpolated = interpolateRawValues(data, labelInnerStore.precision, currValue, targetValue, percent);
  14567. labelInnerStore.interpolatedValue = percent === 1 ? null : interpolated;
  14568. var labelText = getLabelText({
  14569. labelDataIndex: dataIndex,
  14570. labelFetcher: labelFetcher,
  14571. defaultText: defaultInterpolatedText ? defaultInterpolatedText(interpolated) : interpolated + ''
  14572. }, labelInnerStore.statesModels, interpolated);
  14573. setLabelText(textEl, labelText);
  14574. }
  14575. (currValue == null ? initProps : updateProps)(textEl, {}, animatableModel, dataIndex, null, during);
  14576. }
  14577. var PATH_COLOR = ['textStyle', 'color']; // TODO Performance improvement?
  14578. var tmpRichText = new ZRText();
  14579. var TextStyleMixin =
  14580. /** @class */
  14581. function () {
  14582. function TextStyleMixin() {}
  14583. /**
  14584. * Get color property or get color from option.textStyle.color
  14585. */
  14586. // TODO Callback
  14587. TextStyleMixin.prototype.getTextColor = function (isEmphasis) {
  14588. var ecModel = this.ecModel;
  14589. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  14590. };
  14591. /**
  14592. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14593. * @return {string}
  14594. */
  14595. TextStyleMixin.prototype.getFont = function () {
  14596. return getFont({
  14597. fontStyle: this.getShallow('fontStyle'),
  14598. fontWeight: this.getShallow('fontWeight'),
  14599. fontSize: this.getShallow('fontSize'),
  14600. fontFamily: this.getShallow('fontFamily')
  14601. }, this.ecModel);
  14602. };
  14603. TextStyleMixin.prototype.getTextRect = function (text) {
  14604. tmpRichText.useStyle({
  14605. text: text,
  14606. fontStyle: this.getShallow('fontStyle'),
  14607. fontWeight: this.getShallow('fontWeight'),
  14608. fontSize: this.getShallow('fontSize'),
  14609. fontFamily: this.getShallow('fontFamily'),
  14610. verticalAlign: this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14611. padding: this.getShallow('padding'),
  14612. lineHeight: this.getShallow('lineHeight'),
  14613. rich: this.getShallow('rich')
  14614. });
  14615. tmpRichText.update();
  14616. return tmpRichText.getBoundingRect();
  14617. };
  14618. return TextStyleMixin;
  14619. }();
  14620. 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`.
  14621. // So do not transfer decal directly.
  14622. ];
  14623. var getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);
  14624. var LineStyleMixin =
  14625. /** @class */
  14626. function () {
  14627. function LineStyleMixin() {}
  14628. LineStyleMixin.prototype.getLineStyle = function (excludes) {
  14629. return getLineStyle(this, excludes);
  14630. };
  14631. return LineStyleMixin;
  14632. }();
  14633. 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`.
  14634. // So do not transfer decal directly.
  14635. ];
  14636. var getItemStyle = makeStyleMapper(ITEM_STYLE_KEY_MAP);
  14637. var ItemStyleMixin =
  14638. /** @class */
  14639. function () {
  14640. function ItemStyleMixin() {}
  14641. ItemStyleMixin.prototype.getItemStyle = function (excludes, includes) {
  14642. return getItemStyle(this, excludes, includes);
  14643. };
  14644. return ItemStyleMixin;
  14645. }();
  14646. var Model =
  14647. /** @class */
  14648. function () {
  14649. function Model(option, parentModel, ecModel) {
  14650. this.parentModel = parentModel;
  14651. this.ecModel = ecModel;
  14652. this.option = option; // Simple optimization
  14653. // if (this.init) {
  14654. // if (arguments.length <= 4) {
  14655. // this.init(option, parentModel, ecModel, extraOpt);
  14656. // }
  14657. // else {
  14658. // this.init.apply(this, arguments);
  14659. // }
  14660. // }
  14661. }
  14662. Model.prototype.init = function (option, parentModel, ecModel) {
  14663. var rest = [];
  14664. for (var _i = 3; _i < arguments.length; _i++) {
  14665. rest[_i - 3] = arguments[_i];
  14666. }
  14667. };
  14668. /**
  14669. * Merge the input option to me.
  14670. */
  14671. Model.prototype.mergeOption = function (option, ecModel) {
  14672. merge(this.option, option, true);
  14673. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `ModelOption`
  14674. // TODO: TYPE strict key check?
  14675. // get(path: string | string[], ignoreParent?: boolean): ModelOption;
  14676. Model.prototype.get = function (path, ignoreParent) {
  14677. if (path == null) {
  14678. return this.option;
  14679. }
  14680. return this._doGet(this.parsePath(path), !ignoreParent && this.parentModel);
  14681. };
  14682. Model.prototype.getShallow = function (key, ignoreParent) {
  14683. var option = this.option;
  14684. var val = option == null ? option : option[key];
  14685. if (val == null && !ignoreParent) {
  14686. var parentModel = this.parentModel;
  14687. if (parentModel) {
  14688. // FIXME:TS do not know how to make it works
  14689. val = parentModel.getShallow(key);
  14690. }
  14691. }
  14692. return val;
  14693. }; // `path` can be 'xxx.yyy.zzz', so the return value type have to be `Model<ModelOption>`
  14694. // getModel(path: string | string[], parentModel?: Model): Model;
  14695. // TODO 'xxx.yyy.zzz' is deprecated
  14696. Model.prototype.getModel = function (path, parentModel) {
  14697. var hasPath = path != null;
  14698. var pathFinal = hasPath ? this.parsePath(path) : null;
  14699. var obj = hasPath ? this._doGet(pathFinal) : this.option;
  14700. parentModel = parentModel || this.parentModel && this.parentModel.getModel(this.resolveParentPath(pathFinal));
  14701. return new Model(obj, parentModel, this.ecModel);
  14702. };
  14703. /**
  14704. * Squash option stack into one.
  14705. * parentModel will be removed after squashed.
  14706. *
  14707. * NOTE: resolveParentPath will not be applied here for simplicity. DON'T use this function
  14708. * if resolveParentPath is modified.
  14709. *
  14710. * @param deepMerge If do deep merge. Default to be false.
  14711. */
  14712. // squash(
  14713. // deepMerge?: boolean,
  14714. // handleCallback?: (func: () => object) => object
  14715. // ) {
  14716. // const optionStack = [];
  14717. // let model: Model = this;
  14718. // while (model) {
  14719. // if (model.option) {
  14720. // optionStack.push(model.option);
  14721. // }
  14722. // model = model.parentModel;
  14723. // }
  14724. // const newOption = {} as Opt;
  14725. // let option;
  14726. // while (option = optionStack.pop()) { // Top down merge
  14727. // if (isFunction(option) && handleCallback) {
  14728. // option = handleCallback(option);
  14729. // }
  14730. // if (deepMerge) {
  14731. // merge(newOption, option);
  14732. // }
  14733. // else {
  14734. // extend(newOption, option);
  14735. // }
  14736. // }
  14737. // // Remove parentModel
  14738. // this.option = newOption;
  14739. // this.parentModel = null;
  14740. // }
  14741. /**
  14742. * If model has option
  14743. */
  14744. Model.prototype.isEmpty = function () {
  14745. return this.option == null;
  14746. };
  14747. Model.prototype.restoreData = function () {}; // Pending
  14748. Model.prototype.clone = function () {
  14749. var Ctor = this.constructor;
  14750. return new Ctor(clone(this.option));
  14751. }; // setReadOnly(properties): void {
  14752. // clazzUtil.setReadOnly(this, properties);
  14753. // }
  14754. // If path is null/undefined, return null/undefined.
  14755. Model.prototype.parsePath = function (path) {
  14756. if (typeof path === 'string') {
  14757. return path.split('.');
  14758. }
  14759. return path;
  14760. }; // Resolve path for parent. Perhaps useful when parent use a different property.
  14761. // Default to be a identity resolver.
  14762. // Can be modified to a different resolver.
  14763. Model.prototype.resolveParentPath = function (path) {
  14764. return path;
  14765. }; // FIXME:TS check whether put this method here
  14766. Model.prototype.isAnimationEnabled = function () {
  14767. if (!env.node && this.option) {
  14768. if (this.option.animation != null) {
  14769. return !!this.option.animation;
  14770. } else if (this.parentModel) {
  14771. return this.parentModel.isAnimationEnabled();
  14772. }
  14773. }
  14774. };
  14775. Model.prototype._doGet = function (pathArr, parentModel) {
  14776. var obj = this.option;
  14777. if (!pathArr) {
  14778. return obj;
  14779. }
  14780. for (var i = 0; i < pathArr.length; i++) {
  14781. // Ignore empty
  14782. if (!pathArr[i]) {
  14783. continue;
  14784. } // obj could be number/string/... (like 0)
  14785. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  14786. if (obj == null) {
  14787. break;
  14788. }
  14789. }
  14790. if (obj == null && parentModel) {
  14791. obj = parentModel._doGet(this.resolveParentPath(pathArr), parentModel.parentModel);
  14792. }
  14793. return obj;
  14794. };
  14795. return Model;
  14796. }();
  14797. enableClassExtend(Model);
  14798. enableClassCheck(Model);
  14799. mixin(Model, LineStyleMixin);
  14800. mixin(Model, ItemStyleMixin);
  14801. mixin(Model, AreaStyleMixin);
  14802. mixin(Model, TextStyleMixin);
  14803. var base = Math.round(Math.random() * 10);
  14804. /**
  14805. * @public
  14806. * @param {string} type
  14807. * @return {string}
  14808. */
  14809. function getUID(type) {
  14810. // Considering the case of crossing js context,
  14811. // use Math.random to make id as unique as possible.
  14812. return [type || '', base++].join('_');
  14813. }
  14814. /**
  14815. * Implements `SubTypeDefaulterManager` for `target`.
  14816. */
  14817. function enableSubTypeDefaulter(target) {
  14818. var subTypeDefaulters = {};
  14819. target.registerSubTypeDefaulter = function (componentType, defaulter) {
  14820. var componentTypeInfo = parseClassType(componentType);
  14821. subTypeDefaulters[componentTypeInfo.main] = defaulter;
  14822. };
  14823. target.determineSubType = function (componentType, option) {
  14824. var type = option.type;
  14825. if (!type) {
  14826. var componentTypeMain = parseClassType(componentType).main;
  14827. if (target.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  14828. type = subTypeDefaulters[componentTypeMain](option);
  14829. }
  14830. }
  14831. return type;
  14832. };
  14833. }
  14834. /**
  14835. * Implements `TopologicalTravelable<any>` for `entity`.
  14836. *
  14837. * Topological travel on Activity Network (Activity On Vertices).
  14838. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  14839. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  14840. * If there is circle dependencey, Error will be thrown.
  14841. */
  14842. function enableTopologicalTravel(entity, dependencyGetter) {
  14843. /**
  14844. * @param targetNameList Target Component type list.
  14845. * Can be ['aa', 'bb', 'aa.xx']
  14846. * @param fullNameList By which we can build dependency graph.
  14847. * @param callback Params: componentType, dependencies.
  14848. * @param context Scope of callback.
  14849. */
  14850. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  14851. if (!targetNameList.length) {
  14852. return;
  14853. }
  14854. var result = makeDepndencyGraph(fullNameList);
  14855. var graph = result.graph;
  14856. var noEntryList = result.noEntryList;
  14857. var targetNameSet = {};
  14858. each(targetNameList, function (name) {
  14859. targetNameSet[name] = true;
  14860. });
  14861. while (noEntryList.length) {
  14862. var currComponentType = noEntryList.pop();
  14863. var currVertex = graph[currComponentType];
  14864. var isInTargetNameSet = !!targetNameSet[currComponentType];
  14865. if (isInTargetNameSet) {
  14866. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  14867. delete targetNameSet[currComponentType];
  14868. }
  14869. each(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  14870. }
  14871. each(targetNameSet, function () {
  14872. var errMsg = '';
  14873. if ("development" !== 'production') {
  14874. errMsg = makePrintable('Circle dependency may exists: ', targetNameSet, targetNameList, fullNameList);
  14875. }
  14876. throw new Error(errMsg);
  14877. });
  14878. function removeEdge(succComponentType) {
  14879. graph[succComponentType].entryCount--;
  14880. if (graph[succComponentType].entryCount === 0) {
  14881. noEntryList.push(succComponentType);
  14882. }
  14883. } // Consider this case: legend depends on series, and we call
  14884. // chart.setOption({series: [...]}), where only series is in option.
  14885. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  14886. // not be called, but only sereis.mergeOption is called. Thus legend
  14887. // have no chance to update its local record about series (like which
  14888. // name of series is available in legend).
  14889. function removeEdgeAndAdd(succComponentType) {
  14890. targetNameSet[succComponentType] = true;
  14891. removeEdge(succComponentType);
  14892. }
  14893. };
  14894. function makeDepndencyGraph(fullNameList) {
  14895. var graph = {};
  14896. var noEntryList = [];
  14897. each(fullNameList, function (name) {
  14898. var thisItem = createDependencyGraphItem(graph, name);
  14899. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  14900. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  14901. thisItem.entryCount = availableDeps.length;
  14902. if (thisItem.entryCount === 0) {
  14903. noEntryList.push(name);
  14904. }
  14905. each(availableDeps, function (dependentName) {
  14906. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  14907. thisItem.predecessor.push(dependentName);
  14908. }
  14909. var thatItem = createDependencyGraphItem(graph, dependentName);
  14910. if (indexOf(thatItem.successor, dependentName) < 0) {
  14911. thatItem.successor.push(name);
  14912. }
  14913. });
  14914. });
  14915. return {
  14916. graph: graph,
  14917. noEntryList: noEntryList
  14918. };
  14919. }
  14920. function createDependencyGraphItem(graph, name) {
  14921. if (!graph[name]) {
  14922. graph[name] = {
  14923. predecessor: [],
  14924. successor: []
  14925. };
  14926. }
  14927. return graph[name];
  14928. }
  14929. function getAvailableDependencies(originalDeps, fullNameList) {
  14930. var availableDeps = [];
  14931. each(originalDeps, function (dep) {
  14932. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  14933. });
  14934. return availableDeps;
  14935. }
  14936. }
  14937. function inheritDefaultOption(superOption, subOption) {
  14938. // See also `model/Component.ts#getDefaultOption`
  14939. return merge(merge({}, superOption, true), subOption, true);
  14940. }
  14941. /*
  14942. * Licensed to the Apache Software Foundation (ASF) under one
  14943. * or more contributor license agreements. See the NOTICE file
  14944. * distributed with this work for additional information
  14945. * regarding copyright ownership. The ASF licenses this file
  14946. * to you under the Apache License, Version 2.0 (the
  14947. * "License"); you may not use this file except in compliance
  14948. * with the License. You may obtain a copy of the License at
  14949. *
  14950. * http://www.apache.org/licenses/LICENSE-2.0
  14951. *
  14952. * Unless required by applicable law or agreed to in writing,
  14953. * software distributed under the License is distributed on an
  14954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14955. * KIND, either express or implied. See the License for the
  14956. * specific language governing permissions and limitations
  14957. * under the License.
  14958. */
  14959. /**
  14960. * AUTO-GENERATED FILE. DO NOT MODIFY.
  14961. */
  14962. /*
  14963. * Licensed to the Apache Software Foundation (ASF) under one
  14964. * or more contributor license agreements. See the NOTICE file
  14965. * distributed with this work for additional information
  14966. * regarding copyright ownership. The ASF licenses this file
  14967. * to you under the Apache License, Version 2.0 (the
  14968. * "License"); you may not use this file except in compliance
  14969. * with the License. You may obtain a copy of the License at
  14970. *
  14971. * http://www.apache.org/licenses/LICENSE-2.0
  14972. *
  14973. * Unless required by applicable law or agreed to in writing,
  14974. * software distributed under the License is distributed on an
  14975. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14976. * KIND, either express or implied. See the License for the
  14977. * specific language governing permissions and limitations
  14978. * under the License.
  14979. */
  14980. /**
  14981. * Language: English.
  14982. */
  14983. var langEN = {
  14984. time: {
  14985. month: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  14986. monthAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  14987. dayOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  14988. dayOfWeekAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  14989. },
  14990. legend: {
  14991. selector: {
  14992. all: 'All',
  14993. inverse: 'Inv'
  14994. }
  14995. },
  14996. toolbox: {
  14997. brush: {
  14998. title: {
  14999. rect: 'Box Select',
  15000. polygon: 'Lasso Select',
  15001. lineX: 'Horizontally Select',
  15002. lineY: 'Vertically Select',
  15003. keep: 'Keep Selections',
  15004. clear: 'Clear Selections'
  15005. }
  15006. },
  15007. dataView: {
  15008. title: 'Data View',
  15009. lang: ['Data View', 'Close', 'Refresh']
  15010. },
  15011. dataZoom: {
  15012. title: {
  15013. zoom: 'Zoom',
  15014. back: 'Zoom Reset'
  15015. }
  15016. },
  15017. magicType: {
  15018. title: {
  15019. line: 'Switch to Line Chart',
  15020. bar: 'Switch to Bar Chart',
  15021. stack: 'Stack',
  15022. tiled: 'Tile'
  15023. }
  15024. },
  15025. restore: {
  15026. title: 'Restore'
  15027. },
  15028. saveAsImage: {
  15029. title: 'Save as Image',
  15030. lang: ['Right Click to Save Image']
  15031. }
  15032. },
  15033. series: {
  15034. typeNames: {
  15035. pie: 'Pie chart',
  15036. bar: 'Bar chart',
  15037. line: 'Line chart',
  15038. scatter: 'Scatter plot',
  15039. effectScatter: 'Ripple scatter plot',
  15040. radar: 'Radar chart',
  15041. tree: 'Tree',
  15042. treemap: 'Treemap',
  15043. boxplot: 'Boxplot',
  15044. candlestick: 'Candlestick',
  15045. k: 'K line chart',
  15046. heatmap: 'Heat map',
  15047. map: 'Map',
  15048. parallel: 'Parallel coordinate map',
  15049. lines: 'Line graph',
  15050. graph: 'Relationship graph',
  15051. sankey: 'Sankey diagram',
  15052. funnel: 'Funnel chart',
  15053. gauge: 'Guage',
  15054. pictorialBar: 'Pictorial bar',
  15055. themeRiver: 'Theme River Map',
  15056. sunburst: 'Sunburst'
  15057. }
  15058. },
  15059. aria: {
  15060. general: {
  15061. withTitle: 'This is a chart about "{title}"',
  15062. withoutTitle: 'This is a chart'
  15063. },
  15064. series: {
  15065. single: {
  15066. prefix: '',
  15067. withName: ' with type {seriesType} named {seriesName}.',
  15068. withoutName: ' with type {seriesType}.'
  15069. },
  15070. multiple: {
  15071. prefix: '. It consists of {seriesCount} series count.',
  15072. withName: ' The {seriesId} series is a {seriesType} representing {seriesName}.',
  15073. withoutName: ' The {seriesId} series is a {seriesType}.',
  15074. separator: {
  15075. middle: '',
  15076. end: ''
  15077. }
  15078. }
  15079. },
  15080. data: {
  15081. allData: 'The data is as follows: ',
  15082. partialData: 'The first {displayCnt} items are: ',
  15083. withName: 'the data for {name} is {value}',
  15084. withoutName: '{value}',
  15085. separator: {
  15086. middle: ', ',
  15087. end: '. '
  15088. }
  15089. }
  15090. }
  15091. };
  15092. /*
  15093. * Licensed to the Apache Software Foundation (ASF) under one
  15094. * or more contributor license agreements. See the NOTICE file
  15095. * distributed with this work for additional information
  15096. * regarding copyright ownership. The ASF licenses this file
  15097. * to you under the Apache License, Version 2.0 (the
  15098. * "License"); you may not use this file except in compliance
  15099. * with the License. You may obtain a copy of the License at
  15100. *
  15101. * http://www.apache.org/licenses/LICENSE-2.0
  15102. *
  15103. * Unless required by applicable law or agreed to in writing,
  15104. * software distributed under the License is distributed on an
  15105. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15106. * KIND, either express or implied. See the License for the
  15107. * specific language governing permissions and limitations
  15108. * under the License.
  15109. */
  15110. /**
  15111. * AUTO-GENERATED FILE. DO NOT MODIFY.
  15112. */
  15113. /*
  15114. * Licensed to the Apache Software Foundation (ASF) under one
  15115. * or more contributor license agreements. See the NOTICE file
  15116. * distributed with this work for additional information
  15117. * regarding copyright ownership. The ASF licenses this file
  15118. * to you under the Apache License, Version 2.0 (the
  15119. * "License"); you may not use this file except in compliance
  15120. * with the License. You may obtain a copy of the License at
  15121. *
  15122. * http://www.apache.org/licenses/LICENSE-2.0
  15123. *
  15124. * Unless required by applicable law or agreed to in writing,
  15125. * software distributed under the License is distributed on an
  15126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15127. * KIND, either express or implied. See the License for the
  15128. * specific language governing permissions and limitations
  15129. * under the License.
  15130. */
  15131. var langZH = {
  15132. time: {
  15133. month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  15134. monthAbbr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  15135. dayOfWeek: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
  15136. dayOfWeekAbbr: ['日', '一', '二', '三', '四', '五', '六']
  15137. },
  15138. legend: {
  15139. selector: {
  15140. all: '全选',
  15141. inverse: '反选'
  15142. }
  15143. },
  15144. toolbox: {
  15145. brush: {
  15146. title: {
  15147. rect: '矩形选择',
  15148. polygon: '圈选',
  15149. lineX: '横向选择',
  15150. lineY: '纵向选择',
  15151. keep: '保持选择',
  15152. clear: '清除选择'
  15153. }
  15154. },
  15155. dataView: {
  15156. title: '数据视图',
  15157. lang: ['数据视图', '关闭', '刷新']
  15158. },
  15159. dataZoom: {
  15160. title: {
  15161. zoom: '区域缩放',
  15162. back: '区域缩放还原'
  15163. }
  15164. },
  15165. magicType: {
  15166. title: {
  15167. line: '切换为折线图',
  15168. bar: '切换为柱状图',
  15169. stack: '切换为堆叠',
  15170. tiled: '切换为平铺'
  15171. }
  15172. },
  15173. restore: {
  15174. title: '还原'
  15175. },
  15176. saveAsImage: {
  15177. title: '保存为图片',
  15178. lang: ['右键另存为图片']
  15179. }
  15180. },
  15181. series: {
  15182. typeNames: {
  15183. pie: '饼图',
  15184. bar: '柱状图',
  15185. line: '折线图',
  15186. scatter: '散点图',
  15187. effectScatter: '涟漪散点图',
  15188. radar: '雷达图',
  15189. tree: '树图',
  15190. treemap: '矩形树图',
  15191. boxplot: '箱型图',
  15192. candlestick: 'K线图',
  15193. k: 'K线图',
  15194. heatmap: '热力图',
  15195. map: '地图',
  15196. parallel: '平行坐标图',
  15197. lines: '线图',
  15198. graph: '关系图',
  15199. sankey: '桑基图',
  15200. funnel: '漏斗图',
  15201. gauge: '仪表盘图',
  15202. pictorialBar: '象形柱图',
  15203. themeRiver: '主题河流图',
  15204. sunburst: '旭日图'
  15205. }
  15206. },
  15207. aria: {
  15208. general: {
  15209. withTitle: '这是一个关于“{title}”的图表。',
  15210. withoutTitle: '这是一个图表,'
  15211. },
  15212. series: {
  15213. single: {
  15214. prefix: '',
  15215. withName: '图表类型是{seriesType},表示{seriesName}。',
  15216. withoutName: '图表类型是{seriesType}。'
  15217. },
  15218. multiple: {
  15219. prefix: '它由{seriesCount}个图表系列组成。',
  15220. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  15221. withoutName: '第{seriesId}个系列是一个{seriesType},',
  15222. separator: {
  15223. middle: ';',
  15224. end: '。'
  15225. }
  15226. }
  15227. },
  15228. data: {
  15229. allData: '其数据是——',
  15230. partialData: '其中,前{displayCnt}项是——',
  15231. withName: '{name}的数据是{value}',
  15232. withoutName: '{value}',
  15233. separator: {
  15234. middle: ',',
  15235. end: ''
  15236. }
  15237. }
  15238. }
  15239. };
  15240. var LOCALE_ZH = 'ZH';
  15241. var LOCALE_EN = 'EN';
  15242. var DEFAULT_LOCALE = LOCALE_EN;
  15243. var localeStorage = {};
  15244. var localeModels = {};
  15245. var SYSTEM_LANG = !env.domSupported ? DEFAULT_LOCALE : function () {
  15246. var langStr = (
  15247. /* eslint-disable-next-line */
  15248. document.documentElement.lang || navigator.language || navigator.browserLanguage).toUpperCase();
  15249. return langStr.indexOf(LOCALE_ZH) > -1 ? LOCALE_ZH : DEFAULT_LOCALE;
  15250. }();
  15251. function registerLocale(locale, localeObj) {
  15252. locale = locale.toUpperCase();
  15253. localeModels[locale] = new Model(localeObj);
  15254. localeStorage[locale] = localeObj;
  15255. } // export function getLocale(locale: string) {
  15256. // return localeStorage[locale];
  15257. // }
  15258. function createLocaleObject(locale) {
  15259. if (isString(locale)) {
  15260. var localeObj = localeStorage[locale.toUpperCase()] || {};
  15261. if (locale === LOCALE_ZH || locale === LOCALE_EN) {
  15262. return clone(localeObj);
  15263. } else {
  15264. return merge(clone(localeObj), clone(localeStorage[DEFAULT_LOCALE]), false);
  15265. }
  15266. } else {
  15267. return merge(clone(locale), clone(localeStorage[DEFAULT_LOCALE]), false);
  15268. }
  15269. }
  15270. function getLocaleModel(lang) {
  15271. return localeModels[lang];
  15272. }
  15273. function getDefaultLocaleModel() {
  15274. return localeModels[DEFAULT_LOCALE];
  15275. } // Default locale
  15276. registerLocale(LOCALE_EN, langEN);
  15277. registerLocale(LOCALE_ZH, langZH);
  15278. var ONE_SECOND = 1000;
  15279. var ONE_MINUTE = ONE_SECOND * 60;
  15280. var ONE_HOUR = ONE_MINUTE * 60;
  15281. var ONE_DAY = ONE_HOUR * 24;
  15282. var ONE_YEAR = ONE_DAY * 365;
  15283. var defaultLeveledFormatter = {
  15284. year: '{yyyy}',
  15285. month: '{MMM}',
  15286. day: '{d}',
  15287. hour: '{HH}:{mm}',
  15288. minute: '{HH}:{mm}',
  15289. second: '{HH}:{mm}:{ss}',
  15290. millisecond: '{hh}:{mm}:{ss} {SSS}',
  15291. none: '{yyyy}-{MM}-{dd} {hh}:{mm}:{ss} {SSS}'
  15292. };
  15293. var fullDayFormatter = '{yyyy}-{MM}-{dd}';
  15294. var fullLeveledFormatter = {
  15295. year: '{yyyy}',
  15296. month: '{yyyy}-{MM}',
  15297. day: fullDayFormatter,
  15298. hour: fullDayFormatter + ' ' + defaultLeveledFormatter.hour,
  15299. minute: fullDayFormatter + ' ' + defaultLeveledFormatter.minute,
  15300. second: fullDayFormatter + ' ' + defaultLeveledFormatter.second,
  15301. millisecond: defaultLeveledFormatter.none
  15302. };
  15303. var primaryTimeUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond'];
  15304. var timeUnits = ['year', 'half-year', 'quarter', 'month', 'week', 'half-week', 'day', 'half-day', 'quarter-day', 'hour', 'minute', 'second', 'millisecond'];
  15305. function pad(str, len) {
  15306. str += '';
  15307. return '0000'.substr(0, len - str.length) + str;
  15308. }
  15309. function getPrimaryTimeUnit(timeUnit) {
  15310. switch (timeUnit) {
  15311. case 'half-year':
  15312. case 'quarter':
  15313. return 'month';
  15314. case 'week':
  15315. case 'half-week':
  15316. return 'day';
  15317. case 'half-day':
  15318. case 'quarter-day':
  15319. return 'hour';
  15320. default:
  15321. // year, minutes, second, milliseconds
  15322. return timeUnit;
  15323. }
  15324. }
  15325. function isPrimaryTimeUnit(timeUnit) {
  15326. return timeUnit === getPrimaryTimeUnit(timeUnit);
  15327. }
  15328. function getDefaultFormatPrecisionOfInterval(timeUnit) {
  15329. switch (timeUnit) {
  15330. case 'year':
  15331. case 'month':
  15332. return 'day';
  15333. case 'millisecond':
  15334. return 'millisecond';
  15335. default:
  15336. // Also for day, hour, minute, second
  15337. return 'second';
  15338. }
  15339. }
  15340. function format( // Note: The result based on `isUTC` are totally different, which can not be just simply
  15341. // substituted by the result without `isUTC`. So we make the param `isUTC` mandatory.
  15342. time, template, isUTC, lang) {
  15343. var date = parseDate(time);
  15344. var y = date[fullYearGetterName(isUTC)]();
  15345. var M = date[monthGetterName(isUTC)]() + 1;
  15346. var q = Math.floor((M - 1) / 4) + 1;
  15347. var d = date[dateGetterName(isUTC)]();
  15348. var e = date['get' + (isUTC ? 'UTC' : '') + 'Day']();
  15349. var H = date[hoursGetterName(isUTC)]();
  15350. var h = (H - 1) % 12 + 1;
  15351. var m = date[minutesGetterName(isUTC)]();
  15352. var s = date[secondsGetterName(isUTC)]();
  15353. var S = date[millisecondsGetterName(isUTC)]();
  15354. var localeModel = lang instanceof Model ? lang : getLocaleModel(lang || SYSTEM_LANG) || getDefaultLocaleModel();
  15355. var timeModel = localeModel.getModel('time');
  15356. var month = timeModel.get('month');
  15357. var monthAbbr = timeModel.get('monthAbbr');
  15358. var dayOfWeek = timeModel.get('dayOfWeek');
  15359. var dayOfWeekAbbr = timeModel.get('dayOfWeekAbbr');
  15360. return (template || '').replace(/{yyyy}/g, y + '').replace(/{yy}/g, y % 100 + '').replace(/{Q}/g, q + '').replace(/{MMMM}/g, month[M - 1]).replace(/{MMM}/g, monthAbbr[M - 1]).replace(/{MM}/g, pad(M, 2)).replace(/{M}/g, M + '').replace(/{dd}/g, pad(d, 2)).replace(/{d}/g, d + '').replace(/{eeee}/g, dayOfWeek[e]).replace(/{ee}/g, dayOfWeekAbbr[e]).replace(/{e}/g, e + '').replace(/{HH}/g, pad(H, 2)).replace(/{H}/g, H + '').replace(/{hh}/g, pad(h + '', 2)).replace(/{h}/g, h + '').replace(/{mm}/g, pad(m, 2)).replace(/{m}/g, m + '').replace(/{ss}/g, pad(s, 2)).replace(/{s}/g, s + '').replace(/{SSS}/g, pad(S, 3)).replace(/{S}/g, S + '');
  15361. }
  15362. function leveledFormat(tick, idx, formatter, lang, isUTC) {
  15363. var template = null;
  15364. if (typeof formatter === 'string') {
  15365. // Single formatter for all units at all levels
  15366. template = formatter;
  15367. } else if (typeof formatter === 'function') {
  15368. // Callback formatter
  15369. template = formatter(tick.value, idx, {
  15370. level: tick.level
  15371. });
  15372. } else {
  15373. var defaults$1 = extend({}, defaultLeveledFormatter);
  15374. if (tick.level > 0) {
  15375. for (var i = 0; i < primaryTimeUnits.length; ++i) {
  15376. defaults$1[primaryTimeUnits[i]] = "{primary|" + defaults$1[primaryTimeUnits[i]] + "}";
  15377. }
  15378. }
  15379. var mergedFormatter = formatter ? formatter.inherit === false ? formatter // Use formatter with bigger units
  15380. : defaults(formatter, defaults$1) : defaults$1;
  15381. var unit = getUnitFromValue(tick.value, isUTC);
  15382. if (mergedFormatter[unit]) {
  15383. template = mergedFormatter[unit];
  15384. } else if (mergedFormatter.inherit) {
  15385. // Unit formatter is not defined and should inherit from bigger units
  15386. var targetId = timeUnits.indexOf(unit);
  15387. for (var i = targetId - 1; i >= 0; --i) {
  15388. if (mergedFormatter[unit]) {
  15389. template = mergedFormatter[unit];
  15390. break;
  15391. }
  15392. }
  15393. template = template || defaults$1.none;
  15394. }
  15395. if (isArray(template)) {
  15396. var levelId = tick.level == null ? 0 : tick.level >= 0 ? tick.level : template.length + tick.level;
  15397. levelId = Math.min(levelId, template.length - 1);
  15398. template = template[levelId];
  15399. }
  15400. }
  15401. return format(new Date(tick.value), template, isUTC, lang);
  15402. }
  15403. function getUnitFromValue(value, isUTC) {
  15404. var date = parseDate(value);
  15405. var M = date[monthGetterName(isUTC)]() + 1;
  15406. var d = date[dateGetterName(isUTC)]();
  15407. var h = date[hoursGetterName(isUTC)]();
  15408. var m = date[minutesGetterName(isUTC)]();
  15409. var s = date[secondsGetterName(isUTC)]();
  15410. var S = date[millisecondsGetterName(isUTC)]();
  15411. var isSecond = S === 0;
  15412. var isMinute = isSecond && s === 0;
  15413. var isHour = isMinute && m === 0;
  15414. var isDay = isHour && h === 0;
  15415. var isMonth = isDay && d === 1;
  15416. var isYear = isMonth && M === 1;
  15417. if (isYear) {
  15418. return 'year';
  15419. } else if (isMonth) {
  15420. return 'month';
  15421. } else if (isDay) {
  15422. return 'day';
  15423. } else if (isHour) {
  15424. return 'hour';
  15425. } else if (isMinute) {
  15426. return 'minute';
  15427. } else if (isSecond) {
  15428. return 'second';
  15429. } else {
  15430. return 'millisecond';
  15431. }
  15432. }
  15433. function getUnitValue(value, unit, isUTC) {
  15434. var date = typeof value === 'number' ? parseDate(value) : value;
  15435. unit = unit || getUnitFromValue(value, isUTC);
  15436. switch (unit) {
  15437. case 'year':
  15438. return date[fullYearGetterName(isUTC)]();
  15439. case 'half-year':
  15440. return date[monthGetterName(isUTC)]() >= 6 ? 1 : 0;
  15441. case 'quarter':
  15442. return Math.floor((date[monthGetterName(isUTC)]() + 1) / 4);
  15443. case 'month':
  15444. return date[monthGetterName(isUTC)]();
  15445. case 'day':
  15446. return date[dateGetterName(isUTC)]();
  15447. case 'half-day':
  15448. return date[hoursGetterName(isUTC)]() / 24;
  15449. case 'hour':
  15450. return date[hoursGetterName(isUTC)]();
  15451. case 'minute':
  15452. return date[minutesGetterName(isUTC)]();
  15453. case 'second':
  15454. return date[secondsGetterName(isUTC)]();
  15455. case 'millisecond':
  15456. return date[millisecondsGetterName(isUTC)]();
  15457. }
  15458. }
  15459. function fullYearGetterName(isUTC) {
  15460. return isUTC ? 'getUTCFullYear' : 'getFullYear';
  15461. }
  15462. function monthGetterName(isUTC) {
  15463. return isUTC ? 'getUTCMonth' : 'getMonth';
  15464. }
  15465. function dateGetterName(isUTC) {
  15466. return isUTC ? 'getUTCDate' : 'getDate';
  15467. }
  15468. function hoursGetterName(isUTC) {
  15469. return isUTC ? 'getUTCHours' : 'getHours';
  15470. }
  15471. function minutesGetterName(isUTC) {
  15472. return isUTC ? 'getUTCMinutes' : 'getMinutes';
  15473. }
  15474. function secondsGetterName(isUTC) {
  15475. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15476. }
  15477. function millisecondsGetterName(isUTC) {
  15478. return isUTC ? 'getUTCSeconds' : 'getSeconds';
  15479. }
  15480. function fullYearSetterName(isUTC) {
  15481. return isUTC ? 'setUTCFullYear' : 'setFullYear';
  15482. }
  15483. function monthSetterName(isUTC) {
  15484. return isUTC ? 'setUTCMonth' : 'setMonth';
  15485. }
  15486. function dateSetterName(isUTC) {
  15487. return isUTC ? 'setUTCDate' : 'setDate';
  15488. }
  15489. function hoursSetterName(isUTC) {
  15490. return isUTC ? 'setUTCHours' : 'setHours';
  15491. }
  15492. function minutesSetterName(isUTC) {
  15493. return isUTC ? 'setUTCMinutes' : 'setMinutes';
  15494. }
  15495. function secondsSetterName(isUTC) {
  15496. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15497. }
  15498. function millisecondsSetterName(isUTC) {
  15499. return isUTC ? 'setUTCSeconds' : 'setSeconds';
  15500. }
  15501. function getTextRect(text, font, align, verticalAlign, padding, rich, truncate, lineHeight) {
  15502. deprecateLog('getTextRect is deprecated.');
  15503. var textEl = new ZRText({
  15504. style: {
  15505. text: text,
  15506. font: font,
  15507. align: align,
  15508. verticalAlign: verticalAlign,
  15509. padding: padding,
  15510. rich: rich,
  15511. overflow: truncate ? 'truncate' : null,
  15512. lineHeight: lineHeight
  15513. }
  15514. });
  15515. return textEl.getBoundingRect();
  15516. }
  15517. /**
  15518. * Add a comma each three digit.
  15519. */
  15520. function addCommas(x) {
  15521. if (!isNumeric(x)) {
  15522. return isString(x) ? x : '-';
  15523. }
  15524. var parts = (x + '').split('.');
  15525. return parts[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (parts.length > 1 ? '.' + parts[1] : '');
  15526. }
  15527. function toCamelCase(str, upperCaseFirst) {
  15528. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  15529. return group1.toUpperCase();
  15530. });
  15531. if (upperCaseFirst && str) {
  15532. str = str.charAt(0).toUpperCase() + str.slice(1);
  15533. }
  15534. return str;
  15535. }
  15536. var normalizeCssArray$1 = normalizeCssArray;
  15537. var replaceReg = /([&<>"'])/g;
  15538. var replaceMap = {
  15539. '&': '&amp;',
  15540. '<': '&lt;',
  15541. '>': '&gt;',
  15542. '"': '&quot;',
  15543. '\'': '&#39;'
  15544. };
  15545. function encodeHTML(source) {
  15546. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  15547. return replaceMap[c];
  15548. });
  15549. }
  15550. /**
  15551. * Make value user readable for tooltip and label.
  15552. * "User readable":
  15553. * Try to not print programmer-specific text like NaN, Infinity, null, undefined.
  15554. * Avoid to display an empty string, which users can not recognize there is
  15555. * a value and it might look like a bug.
  15556. */
  15557. function makeValueReadable(value, valueType, useUTC) {
  15558. var USER_READABLE_DEFUALT_TIME_PATTERN = 'yyyy-MM-dd hh:mm:ss';
  15559. function stringToUserReadable(str) {
  15560. return str && trim(str) ? str : '-';
  15561. }
  15562. function isNumberUserReadable(num) {
  15563. return !!(num != null && !isNaN(num) && isFinite(num));
  15564. }
  15565. var isTypeTime = valueType === 'time';
  15566. var isValueDate = value instanceof Date;
  15567. if (isTypeTime || isValueDate) {
  15568. var date = isTypeTime ? parseDate(value) : value;
  15569. if (!isNaN(+date)) {
  15570. return format(date, USER_READABLE_DEFUALT_TIME_PATTERN, useUTC);
  15571. } else if (isValueDate) {
  15572. return '-';
  15573. } // In other cases, continue to try to display the value in the following code.
  15574. }
  15575. if (valueType === 'ordinal') {
  15576. return isStringSafe(value) ? stringToUserReadable(value) : isNumber(value) ? isNumberUserReadable(value) ? value + '' : '-' : '-';
  15577. } // By default.
  15578. var numericResult = numericToNumber(value);
  15579. return isNumberUserReadable(numericResult) ? addCommas(numericResult) : isStringSafe(value) ? stringToUserReadable(value) : '-';
  15580. }
  15581. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15582. var wrapVar = function (varName, seriesIdx) {
  15583. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15584. };
  15585. /**
  15586. * Template formatter
  15587. * @param {Array.<Object>|Object} paramsList
  15588. */
  15589. function formatTpl(tpl, paramsList, encode) {
  15590. if (!isArray(paramsList)) {
  15591. paramsList = [paramsList];
  15592. }
  15593. var seriesLen = paramsList.length;
  15594. if (!seriesLen) {
  15595. return '';
  15596. }
  15597. var $vars = paramsList[0].$vars || [];
  15598. for (var i = 0; i < $vars.length; i++) {
  15599. var alias = TPL_VAR_ALIAS[i];
  15600. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15601. }
  15602. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15603. for (var k = 0; k < $vars.length; k++) {
  15604. var val = paramsList[seriesIdx][$vars[k]];
  15605. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  15606. }
  15607. }
  15608. return tpl;
  15609. }
  15610. /**
  15611. * simple Template formatter
  15612. */
  15613. function formatTplSimple(tpl, param, encode) {
  15614. each(param, function (value, key) {
  15615. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  15616. });
  15617. return tpl;
  15618. }
  15619. function getTooltipMarker(inOpt, extraCssText) {
  15620. var opt = isString(inOpt) ? {
  15621. color: inOpt,
  15622. extraCssText: extraCssText
  15623. } : inOpt || {};
  15624. var color = opt.color;
  15625. var type = opt.type;
  15626. extraCssText = opt.extraCssText;
  15627. var renderMode = opt.renderMode || 'html';
  15628. if (!color) {
  15629. return '';
  15630. }
  15631. if (renderMode === 'html') {
  15632. 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
  15633. + 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>';
  15634. } else {
  15635. // Should better not to auto generate style name by auto-increment number here.
  15636. // Because this util is usually called in tooltip formatter, which is probably
  15637. // called repeatly when mouse move and the auto-increment number increases fast.
  15638. // Users can make their own style name by theirselves, make it unique and readable.
  15639. var markerId = opt.markerId || 'markerX';
  15640. return {
  15641. renderMode: renderMode,
  15642. content: '{' + markerId + '|} ',
  15643. style: type === 'subItem' ? {
  15644. width: 4,
  15645. height: 4,
  15646. borderRadius: 2,
  15647. backgroundColor: color
  15648. } : {
  15649. width: 10,
  15650. height: 10,
  15651. borderRadius: 5,
  15652. backgroundColor: color
  15653. }
  15654. };
  15655. }
  15656. }
  15657. /**
  15658. * @deprecated Use `time/format` instead.
  15659. * ISO Date format
  15660. * @param {string} tpl
  15661. * @param {number} value
  15662. * @param {boolean} [isUTC=false] Default in local time.
  15663. * see `module:echarts/scale/Time`
  15664. * and `module:echarts/util/number#parseDate`.
  15665. * @inner
  15666. */
  15667. function formatTime(tpl, value, isUTC) {
  15668. if ("development" !== 'production') {
  15669. deprecateReplaceLog('echarts.format.formatTime', 'echarts.time.format');
  15670. }
  15671. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  15672. tpl = 'MM-dd\nyyyy';
  15673. }
  15674. var date = parseDate(value);
  15675. var utc = isUTC ? 'UTC' : '';
  15676. var y = date['get' + utc + 'FullYear']();
  15677. var M = date['get' + utc + 'Month']() + 1;
  15678. var d = date['get' + utc + 'Date']();
  15679. var h = date['get' + utc + 'Hours']();
  15680. var m = date['get' + utc + 'Minutes']();
  15681. var s = date['get' + utc + 'Seconds']();
  15682. var S = date['get' + utc + 'Milliseconds']();
  15683. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100 + '').replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  15684. return tpl;
  15685. }
  15686. /**
  15687. * Capital first
  15688. * @param {string} str
  15689. * @return {string}
  15690. */
  15691. function capitalFirst(str) {
  15692. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15693. }
  15694. /**
  15695. * @return Never be null/undefined.
  15696. */
  15697. function convertToColorString(color, defaultColor) {
  15698. defaultColor = defaultColor || 'transparent';
  15699. return isString(color) ? color : isObject(color) ? color.colorStops && (color.colorStops[0] || {}).color || defaultColor : defaultColor;
  15700. }
  15701. /**
  15702. * open new tab
  15703. * @param link url
  15704. * @param target blank or self
  15705. */
  15706. function windowOpen(link, target) {
  15707. /* global window */
  15708. if (target === '_blank' || target === 'blank') {
  15709. var blank = window.open();
  15710. blank.opener = null;
  15711. blank.location.href = link;
  15712. } else {
  15713. window.open(link, target);
  15714. }
  15715. }
  15716. var each$1 = each;
  15717. /**
  15718. * @public
  15719. */
  15720. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  15721. /**
  15722. * @public
  15723. */
  15724. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  15725. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15726. var x = 0;
  15727. var y = 0;
  15728. if (maxWidth == null) {
  15729. maxWidth = Infinity;
  15730. }
  15731. if (maxHeight == null) {
  15732. maxHeight = Infinity;
  15733. }
  15734. var currentLineMaxSize = 0;
  15735. group.eachChild(function (child, idx) {
  15736. var rect = child.getBoundingRect();
  15737. var nextChild = group.childAt(idx + 1);
  15738. var nextChildRect = nextChild && nextChild.getBoundingRect();
  15739. var nextX;
  15740. var nextY;
  15741. if (orient === 'horizontal') {
  15742. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  15743. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  15744. // FIXME compare before adding gap?
  15745. if (nextX > maxWidth || child.newline) {
  15746. x = 0;
  15747. nextX = moveX;
  15748. y += currentLineMaxSize + gap;
  15749. currentLineMaxSize = rect.height;
  15750. } else {
  15751. // FIXME: consider rect.y is not `0`?
  15752. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  15753. }
  15754. } else {
  15755. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  15756. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  15757. if (nextY > maxHeight || child.newline) {
  15758. x += currentLineMaxSize + gap;
  15759. y = 0;
  15760. nextY = moveY;
  15761. currentLineMaxSize = rect.width;
  15762. } else {
  15763. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  15764. }
  15765. }
  15766. if (child.newline) {
  15767. return;
  15768. }
  15769. child.x = x;
  15770. child.y = y;
  15771. child.markRedraw();
  15772. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  15773. });
  15774. }
  15775. /**
  15776. * VBox or HBox layouting
  15777. * @param {string} orient
  15778. * @param {module:zrender/graphic/Group} group
  15779. * @param {number} gap
  15780. * @param {number} [width=Infinity]
  15781. * @param {number} [height=Infinity]
  15782. */
  15783. var box = boxLayout;
  15784. /**
  15785. * VBox layouting
  15786. * @param {module:zrender/graphic/Group} group
  15787. * @param {number} gap
  15788. * @param {number} [width=Infinity]
  15789. * @param {number} [height=Infinity]
  15790. */
  15791. var vbox = curry(boxLayout, 'vertical');
  15792. /**
  15793. * HBox layouting
  15794. * @param {module:zrender/graphic/Group} group
  15795. * @param {number} gap
  15796. * @param {number} [width=Infinity]
  15797. * @param {number} [height=Infinity]
  15798. */
  15799. var hbox = curry(boxLayout, 'horizontal');
  15800. /**
  15801. * If x or x2 is not specified or 'center' 'left' 'right',
  15802. * the width would be as long as possible.
  15803. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  15804. * the height would be as long as possible.
  15805. */
  15806. function getAvailableSize(positionInfo, containerRect, margin) {
  15807. var containerWidth = containerRect.width;
  15808. var containerHeight = containerRect.height;
  15809. var x = parsePercent$1(positionInfo.left, containerWidth);
  15810. var y = parsePercent$1(positionInfo.top, containerHeight);
  15811. var x2 = parsePercent$1(positionInfo.right, containerWidth);
  15812. var y2 = parsePercent$1(positionInfo.bottom, containerHeight);
  15813. (isNaN(x) || isNaN(parseFloat(positionInfo.left))) && (x = 0);
  15814. (isNaN(x2) || isNaN(parseFloat(positionInfo.right))) && (x2 = containerWidth);
  15815. (isNaN(y) || isNaN(parseFloat(positionInfo.top))) && (y = 0);
  15816. (isNaN(y2) || isNaN(parseFloat(positionInfo.bottom))) && (y2 = containerHeight);
  15817. margin = normalizeCssArray$1(margin || 0);
  15818. return {
  15819. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  15820. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  15821. };
  15822. }
  15823. /**
  15824. * Parse position info.
  15825. */
  15826. function getLayoutRect(positionInfo, containerRect, margin) {
  15827. margin = normalizeCssArray$1(margin || 0);
  15828. var containerWidth = containerRect.width;
  15829. var containerHeight = containerRect.height;
  15830. var left = parsePercent$1(positionInfo.left, containerWidth);
  15831. var top = parsePercent$1(positionInfo.top, containerHeight);
  15832. var right = parsePercent$1(positionInfo.right, containerWidth);
  15833. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  15834. var width = parsePercent$1(positionInfo.width, containerWidth);
  15835. var height = parsePercent$1(positionInfo.height, containerHeight);
  15836. var verticalMargin = margin[2] + margin[0];
  15837. var horizontalMargin = margin[1] + margin[3];
  15838. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  15839. if (isNaN(width)) {
  15840. width = containerWidth - right - horizontalMargin - left;
  15841. }
  15842. if (isNaN(height)) {
  15843. height = containerHeight - bottom - verticalMargin - top;
  15844. }
  15845. if (aspect != null) {
  15846. // If width and height are not given
  15847. // 1. Graph should not exceeds the container
  15848. // 2. Aspect must be keeped
  15849. // 3. Graph should take the space as more as possible
  15850. // FIXME
  15851. // Margin is not considered, because there is no case that both
  15852. // using margin and aspect so far.
  15853. if (isNaN(width) && isNaN(height)) {
  15854. if (aspect > containerWidth / containerHeight) {
  15855. width = containerWidth * 0.8;
  15856. } else {
  15857. height = containerHeight * 0.8;
  15858. }
  15859. } // Calculate width or height with given aspect
  15860. if (isNaN(width)) {
  15861. width = aspect * height;
  15862. }
  15863. if (isNaN(height)) {
  15864. height = width / aspect;
  15865. }
  15866. } // If left is not specified, calculate left from right and width
  15867. if (isNaN(left)) {
  15868. left = containerWidth - right - width - horizontalMargin;
  15869. }
  15870. if (isNaN(top)) {
  15871. top = containerHeight - bottom - height - verticalMargin;
  15872. } // Align left and top
  15873. switch (positionInfo.left || positionInfo.right) {
  15874. case 'center':
  15875. left = containerWidth / 2 - width / 2 - margin[3];
  15876. break;
  15877. case 'right':
  15878. left = containerWidth - width - horizontalMargin;
  15879. break;
  15880. }
  15881. switch (positionInfo.top || positionInfo.bottom) {
  15882. case 'middle':
  15883. case 'center':
  15884. top = containerHeight / 2 - height / 2 - margin[0];
  15885. break;
  15886. case 'bottom':
  15887. top = containerHeight - height - verticalMargin;
  15888. break;
  15889. } // If something is wrong and left, top, width, height are calculated as NaN
  15890. left = left || 0;
  15891. top = top || 0;
  15892. if (isNaN(width)) {
  15893. // Width may be NaN if only one value is given except width
  15894. width = containerWidth - horizontalMargin - left - (right || 0);
  15895. }
  15896. if (isNaN(height)) {
  15897. // Height may be NaN if only one value is given except height
  15898. height = containerHeight - verticalMargin - top - (bottom || 0);
  15899. }
  15900. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  15901. rect.margin = margin;
  15902. return rect;
  15903. }
  15904. /**
  15905. * Position a zr element in viewport
  15906. * Group position is specified by either
  15907. * {left, top}, {right, bottom}
  15908. * If all properties exists, right and bottom will be igonred.
  15909. *
  15910. * Logic:
  15911. * 1. Scale (against origin point in parent coord)
  15912. * 2. Rotate (against origin point in parent coord)
  15913. * 3. Traslate (with el.position by this method)
  15914. * So this method only fixes the last step 'Traslate', which does not affect
  15915. * scaling and rotating.
  15916. *
  15917. * If be called repeatly with the same input el, the same result will be gotten.
  15918. *
  15919. * @param el Should have `getBoundingRect` method.
  15920. * @param positionInfo
  15921. * @param positionInfo.left
  15922. * @param positionInfo.top
  15923. * @param positionInfo.right
  15924. * @param positionInfo.bottom
  15925. * @param positionInfo.width Only for opt.boundingModel: 'raw'
  15926. * @param positionInfo.height Only for opt.boundingModel: 'raw'
  15927. * @param containerRect
  15928. * @param margin
  15929. * @param opt
  15930. * @param opt.hv Only horizontal or only vertical. Default to be [1, 1]
  15931. * @param opt.boundingMode
  15932. * Specify how to calculate boundingRect when locating.
  15933. * 'all': Position the boundingRect that is transformed and uioned
  15934. * both itself and its descendants.
  15935. * This mode simplies confine the elements in the bounding
  15936. * of their container (e.g., using 'right: 0').
  15937. * 'raw': Position the boundingRect that is not transformed and only itself.
  15938. * This mode is useful when you want a element can overflow its
  15939. * container. (Consider a rotated circle needs to be located in a corner.)
  15940. * In this mode positionInfo.width/height can only be number.
  15941. */
  15942. function positionElement(el, positionInfo, containerRect, margin, opt) {
  15943. var h = !opt || !opt.hv || opt.hv[0];
  15944. var v = !opt || !opt.hv || opt.hv[1];
  15945. var boundingMode = opt && opt.boundingMode || 'all';
  15946. if (!h && !v) {
  15947. return;
  15948. }
  15949. var rect;
  15950. if (boundingMode === 'raw') {
  15951. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  15952. } else {
  15953. rect = el.getBoundingRect();
  15954. if (el.needLocalTransform()) {
  15955. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  15956. // which should not be modified.
  15957. rect = rect.clone();
  15958. rect.applyTransform(transform);
  15959. }
  15960. } // The real width and height can not be specified but calculated by the given el.
  15961. var layoutRect = getLayoutRect(defaults({
  15962. width: rect.width,
  15963. height: rect.height
  15964. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  15965. // (see zrender/core/Transformable#getLocalTransform),
  15966. // we can just only modify el.position to get final result.
  15967. var dx = h ? layoutRect.x - rect.x : 0;
  15968. var dy = v ? layoutRect.y - rect.y : 0;
  15969. if (boundingMode === 'raw') {
  15970. el.x = dx;
  15971. el.y = dy;
  15972. } else {
  15973. el.x += dx;
  15974. el.y += dy;
  15975. }
  15976. el.markRedraw();
  15977. }
  15978. /**
  15979. * @param option Contains some of the properties in HV_NAMES.
  15980. * @param hvIdx 0: horizontal; 1: vertical.
  15981. */
  15982. function sizeCalculable(option, hvIdx) {
  15983. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  15984. }
  15985. function fetchLayoutMode(ins) {
  15986. var layoutMode = ins.layoutMode || ins.constructor.layoutMode;
  15987. return isObject(layoutMode) ? layoutMode : layoutMode ? {
  15988. type: layoutMode
  15989. } : null;
  15990. }
  15991. /**
  15992. * Consider Case:
  15993. * When default option has {left: 0, width: 100}, and we set {right: 0}
  15994. * through setOption or media query, using normal zrUtil.merge will cause
  15995. * {right: 0} does not take effect.
  15996. *
  15997. * @example
  15998. * ComponentModel.extend({
  15999. * init: function () {
  16000. * ...
  16001. * let inputPositionParams = layout.getLayoutParams(option);
  16002. * this.mergeOption(inputPositionParams);
  16003. * },
  16004. * mergeOption: function (newOption) {
  16005. * newOption && zrUtil.merge(thisOption, newOption, true);
  16006. * layout.mergeLayoutParam(thisOption, newOption);
  16007. * }
  16008. * });
  16009. *
  16010. * @param targetOption
  16011. * @param newOption
  16012. * @param opt
  16013. */
  16014. function mergeLayoutParam(targetOption, newOption, opt) {
  16015. var ignoreSize = opt && opt.ignoreSize;
  16016. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16017. var hResult = merge(HV_NAMES[0], 0);
  16018. var vResult = merge(HV_NAMES[1], 1);
  16019. copy(HV_NAMES[0], targetOption, hResult);
  16020. copy(HV_NAMES[1], targetOption, vResult);
  16021. function merge(names, hvIdx) {
  16022. var newParams = {};
  16023. var newValueCount = 0;
  16024. var merged = {};
  16025. var mergedValueCount = 0;
  16026. var enoughParamNumber = 2;
  16027. each$1(names, function (name) {
  16028. merged[name] = targetOption[name];
  16029. });
  16030. each$1(names, function (name) {
  16031. // Consider case: newOption.width is null, which is
  16032. // set by user for removing width setting.
  16033. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16034. hasValue(newParams, name) && newValueCount++;
  16035. hasValue(merged, name) && mergedValueCount++;
  16036. });
  16037. if (ignoreSize[hvIdx]) {
  16038. // Only one of left/right is premitted to exist.
  16039. if (hasValue(newOption, names[1])) {
  16040. merged[names[2]] = null;
  16041. } else if (hasValue(newOption, names[2])) {
  16042. merged[names[1]] = null;
  16043. }
  16044. return merged;
  16045. } // Case: newOption: {width: ..., right: ...},
  16046. // or targetOption: {right: ...} and newOption: {width: ...},
  16047. // There is no conflict when merged only has params count
  16048. // little than enoughParamNumber.
  16049. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16050. return merged;
  16051. } // Case: newOption: {width: ..., right: ...},
  16052. // Than we can make sure user only want those two, and ignore
  16053. // all origin params in targetOption.
  16054. else if (newValueCount >= enoughParamNumber) {
  16055. return newParams;
  16056. } else {
  16057. // Chose another param from targetOption by priority.
  16058. for (var i = 0; i < names.length; i++) {
  16059. var name_1 = names[i];
  16060. if (!hasProp(newParams, name_1) && hasProp(targetOption, name_1)) {
  16061. newParams[name_1] = targetOption[name_1];
  16062. break;
  16063. }
  16064. }
  16065. return newParams;
  16066. }
  16067. }
  16068. function hasProp(obj, name) {
  16069. return obj.hasOwnProperty(name);
  16070. }
  16071. function hasValue(obj, name) {
  16072. return obj[name] != null && obj[name] !== 'auto';
  16073. }
  16074. function copy(names, target, source) {
  16075. each$1(names, function (name) {
  16076. target[name] = source[name];
  16077. });
  16078. }
  16079. }
  16080. /**
  16081. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16082. */
  16083. function getLayoutParams(source) {
  16084. return copyLayoutParams({}, source);
  16085. }
  16086. /**
  16087. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16088. * @param {Object} source
  16089. * @return {Object} Result contains those props.
  16090. */
  16091. function copyLayoutParams(target, source) {
  16092. source && target && each$1(LOCATION_PARAMS, function (name) {
  16093. source.hasOwnProperty(name) && (target[name] = source[name]);
  16094. });
  16095. return target;
  16096. }
  16097. var inner = makeInner();
  16098. var ComponentModel =
  16099. /** @class */
  16100. function (_super) {
  16101. __extends(ComponentModel, _super);
  16102. function ComponentModel(option, parentModel, ecModel) {
  16103. var _this = _super.call(this, option, parentModel, ecModel) || this;
  16104. _this.uid = getUID('ec_cpt_model');
  16105. return _this;
  16106. }
  16107. ComponentModel.prototype.init = function (option, parentModel, ecModel) {
  16108. this.mergeDefaultAndTheme(option, ecModel);
  16109. };
  16110. ComponentModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  16111. var layoutMode = fetchLayoutMode(this);
  16112. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16113. var themeModel = ecModel.getTheme();
  16114. merge(option, themeModel.get(this.mainType));
  16115. merge(option, this.getDefaultOption());
  16116. if (layoutMode) {
  16117. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16118. }
  16119. };
  16120. ComponentModel.prototype.mergeOption = function (option, ecModel) {
  16121. merge(this.option, option, true);
  16122. var layoutMode = fetchLayoutMode(this);
  16123. if (layoutMode) {
  16124. mergeLayoutParam(this.option, option, layoutMode);
  16125. }
  16126. };
  16127. /**
  16128. * Called immediately after `init` or `mergeOption` of this instance called.
  16129. */
  16130. ComponentModel.prototype.optionUpdated = function (newCptOption, isInit) {};
  16131. /**
  16132. * [How to declare defaultOption]:
  16133. *
  16134. * (A) If using class declaration in typescript (since echarts 5):
  16135. * ```ts
  16136. * import {ComponentOption} from '../model/option';
  16137. * export interface XxxOption extends ComponentOption {
  16138. * aaa: number
  16139. * }
  16140. * export class XxxModel extends Component {
  16141. * static type = 'xxx';
  16142. * static defaultOption: XxxOption = {
  16143. * aaa: 123
  16144. * }
  16145. * }
  16146. * Component.registerClass(XxxModel);
  16147. * ```
  16148. * ```ts
  16149. * import {inheritDefaultOption} from '../util/component';
  16150. * import {XxxModel, XxxOption} from './XxxModel';
  16151. * export interface XxxSubOption extends XxxOption {
  16152. * bbb: number
  16153. * }
  16154. * class XxxSubModel extends XxxModel {
  16155. * static defaultOption: XxxSubOption = inheritDefaultOption(XxxModel.defaultOption, {
  16156. * bbb: 456
  16157. * })
  16158. * fn() {
  16159. * let opt = this.getDefaultOption();
  16160. * // opt is {aaa: 123, bbb: 456}
  16161. * }
  16162. * }
  16163. * ```
  16164. *
  16165. * (B) If using class extend (previous approach in echarts 3 & 4):
  16166. * ```js
  16167. * let XxxComponent = Component.extend({
  16168. * defaultOption: {
  16169. * xx: 123
  16170. * }
  16171. * })
  16172. * ```
  16173. * ```js
  16174. * let XxxSubComponent = XxxComponent.extend({
  16175. * defaultOption: {
  16176. * yy: 456
  16177. * },
  16178. * fn: function () {
  16179. * let opt = this.getDefaultOption();
  16180. * // opt is {xx: 123, yy: 456}
  16181. * }
  16182. * })
  16183. * ```
  16184. */
  16185. ComponentModel.prototype.getDefaultOption = function () {
  16186. var ctor = this.constructor; // If using class declaration, it is different to travel super class
  16187. // in legacy env and auto merge defaultOption. So if using class
  16188. // declaration, defaultOption should be merged manually.
  16189. if (!isExtendedClass(ctor)) {
  16190. // When using ts class, defaultOption must be declared as static.
  16191. return ctor.defaultOption;
  16192. } // FIXME: remove this approach?
  16193. var fields = inner(this);
  16194. if (!fields.defaultOption) {
  16195. var optList = [];
  16196. var clz = ctor;
  16197. while (clz) {
  16198. var opt = clz.prototype.defaultOption;
  16199. opt && optList.push(opt);
  16200. clz = clz.superClass;
  16201. }
  16202. var defaultOption = {};
  16203. for (var i = optList.length - 1; i >= 0; i--) {
  16204. defaultOption = merge(defaultOption, optList[i], true);
  16205. }
  16206. fields.defaultOption = defaultOption;
  16207. }
  16208. return fields.defaultOption;
  16209. };
  16210. /**
  16211. * Notice: always force to input param `useDefault` in case that forget to consider it.
  16212. * The same behavior as `modelUtil.parseFinder`.
  16213. *
  16214. * @param useDefault In many cases like series refer axis and axis refer grid,
  16215. * If axis index / axis id not specified, use the first target as default.
  16216. * In other cases like dataZoom refer axis, if not specified, measn no refer.
  16217. */
  16218. ComponentModel.prototype.getReferringComponents = function (mainType, opt) {
  16219. var indexKey = mainType + 'Index';
  16220. var idKey = mainType + 'Id';
  16221. return queryReferringComponents(this.ecModel, mainType, {
  16222. index: this.get(indexKey, true),
  16223. id: this.get(idKey, true)
  16224. }, opt);
  16225. };
  16226. ComponentModel.prototype.getBoxLayoutParams = function () {
  16227. // Consider itself having box layout configs.
  16228. var boxLayoutModel = this;
  16229. return {
  16230. left: boxLayoutModel.get('left'),
  16231. top: boxLayoutModel.get('top'),
  16232. right: boxLayoutModel.get('right'),
  16233. bottom: boxLayoutModel.get('bottom'),
  16234. width: boxLayoutModel.get('width'),
  16235. height: boxLayoutModel.get('height')
  16236. };
  16237. };
  16238. ComponentModel.protoInitialize = function () {
  16239. var proto = ComponentModel.prototype;
  16240. proto.type = 'component';
  16241. proto.id = '';
  16242. proto.name = '';
  16243. proto.mainType = '';
  16244. proto.subType = '';
  16245. proto.componentIndex = 0;
  16246. }();
  16247. return ComponentModel;
  16248. }(Model);
  16249. mountExtend(ComponentModel, Model);
  16250. enableClassManagement(ComponentModel);
  16251. enableSubTypeDefaulter(ComponentModel);
  16252. enableTopologicalTravel(ComponentModel, getDependencies);
  16253. function getDependencies(componentType) {
  16254. var deps = [];
  16255. each(ComponentModel.getClassesByMainType(componentType), function (clz) {
  16256. deps = deps.concat(clz.dependencies || clz.prototype.dependencies || []);
  16257. }); // Ensure main type.
  16258. deps = map(deps, function (type) {
  16259. return parseClassType(type).main;
  16260. }); // Hack dataset for convenience.
  16261. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16262. deps.unshift('dataset');
  16263. }
  16264. return deps;
  16265. }
  16266. /*
  16267. * Licensed to the Apache Software Foundation (ASF) under one
  16268. * or more contributor license agreements. See the NOTICE file
  16269. * distributed with this work for additional information
  16270. * regarding copyright ownership. The ASF licenses this file
  16271. * to you under the Apache License, Version 2.0 (the
  16272. * "License"); you may not use this file except in compliance
  16273. * with the License. You may obtain a copy of the License at
  16274. *
  16275. * http://www.apache.org/licenses/LICENSE-2.0
  16276. *
  16277. * Unless required by applicable law or agreed to in writing,
  16278. * software distributed under the License is distributed on an
  16279. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16280. * KIND, either express or implied. See the License for the
  16281. * specific language governing permissions and limitations
  16282. * under the License.
  16283. */
  16284. /**
  16285. * AUTO-GENERATED FILE. DO NOT MODIFY.
  16286. */
  16287. /*
  16288. * Licensed to the Apache Software Foundation (ASF) under one
  16289. * or more contributor license agreements. See the NOTICE file
  16290. * distributed with this work for additional information
  16291. * regarding copyright ownership. The ASF licenses this file
  16292. * to you under the Apache License, Version 2.0 (the
  16293. * "License"); you may not use this file except in compliance
  16294. * with the License. You may obtain a copy of the License at
  16295. *
  16296. * http://www.apache.org/licenses/LICENSE-2.0
  16297. *
  16298. * Unless required by applicable law or agreed to in writing,
  16299. * software distributed under the License is distributed on an
  16300. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16301. * KIND, either express or implied. See the License for the
  16302. * specific language governing permissions and limitations
  16303. * under the License.
  16304. */
  16305. var platform = ''; // Navigator not exists in node
  16306. if (typeof navigator !== 'undefined') {
  16307. /* global navigator */
  16308. platform = navigator.platform || '';
  16309. }
  16310. var decalColor = 'rgba(0, 0, 0, 0.2)';
  16311. var globalDefault = {
  16312. darkMode: 'auto',
  16313. // backgroundColor: 'rgba(0,0,0,0)',
  16314. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16315. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16316. // Light colors:
  16317. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16318. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16319. // Dark colors:
  16320. // color: [
  16321. // '#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83',
  16322. // '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'
  16323. // ],
  16324. color: [// '#51689b', '#ce5c5c', '#fbc357', '#8fbf8f', '#659d84', '#fb8e6a', '#c77288', '#786090', '#91c4c5', '#6890ba'
  16325. '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'],
  16326. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16327. aria: {
  16328. decal: {
  16329. decals: [{
  16330. color: decalColor,
  16331. dashArrayX: [1, 0],
  16332. dashArrayY: [2, 5],
  16333. symbolSize: 1,
  16334. rotation: Math.PI / 6
  16335. }, {
  16336. color: decalColor,
  16337. symbol: 'circle',
  16338. dashArrayX: [[8, 8], [0, 8, 8, 0]],
  16339. dashArrayY: [6, 0],
  16340. symbolSize: 0.8
  16341. }, {
  16342. color: decalColor,
  16343. dashArrayX: [1, 0],
  16344. dashArrayY: [4, 3],
  16345. rotation: -Math.PI / 4
  16346. }, {
  16347. color: decalColor,
  16348. dashArrayX: [[6, 6], [0, 6, 6, 0]],
  16349. dashArrayY: [6, 0]
  16350. }, {
  16351. color: decalColor,
  16352. dashArrayX: [[1, 0], [1, 6]],
  16353. dashArrayY: [1, 0, 6, 0],
  16354. rotation: Math.PI / 4
  16355. }, {
  16356. color: decalColor,
  16357. symbol: 'triangle',
  16358. dashArrayX: [[9, 9], [0, 9, 9, 0]],
  16359. dashArrayY: [7, 2],
  16360. symbolSize: 0.75
  16361. }]
  16362. }
  16363. },
  16364. // If xAxis and yAxis declared, grid is created by default.
  16365. // grid: {},
  16366. textStyle: {
  16367. // color: '#000',
  16368. // decoration: 'none',
  16369. // PENDING
  16370. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16371. // fontFamily: 'Arial, Verdana, sans-serif',
  16372. fontSize: 12,
  16373. fontStyle: 'normal',
  16374. fontWeight: 'normal'
  16375. },
  16376. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16377. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16378. // Default is source-over
  16379. blendMode: null,
  16380. stateAnimation: {
  16381. duration: 300,
  16382. easing: 'cubicOut'
  16383. },
  16384. animation: 'auto',
  16385. animationDuration: 1000,
  16386. animationDurationUpdate: 500,
  16387. animationEasing: 'cubicInOut',
  16388. animationEasingUpdate: 'cubicInOut',
  16389. animationThreshold: 2000,
  16390. // Configuration for progressive/incremental rendering
  16391. progressiveThreshold: 3000,
  16392. progressive: 400,
  16393. // Threshold of if use single hover layer to optimize.
  16394. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16395. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16396. // which is unexpected.
  16397. // see example <echarts/test/heatmap-large.html>.
  16398. hoverLayerThreshold: 3000,
  16399. // See: module:echarts/scale/Time
  16400. useUTC: false
  16401. };
  16402. var VISUAL_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']);
  16403. var SOURCE_FORMAT_ORIGINAL = 'original';
  16404. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16405. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16406. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16407. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16408. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16409. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16410. var SERIES_LAYOUT_BY_ROW = 'row';
  16411. var BE_ORDINAL = {
  16412. Must: 1,
  16413. Might: 2,
  16414. Not: 3 // Other cases
  16415. };
  16416. var innerGlobalModel = makeInner();
  16417. /**
  16418. * MUST be called before mergeOption of all series.
  16419. */
  16420. function resetSourceDefaulter(ecModel) {
  16421. // `datasetMap` is used to make default encode.
  16422. innerGlobalModel(ecModel).datasetMap = createHashMap();
  16423. }
  16424. /**
  16425. * [The strategy of the arrengment of data dimensions for dataset]:
  16426. * "value way": all axes are non-category axes. So series one by one take
  16427. * several (the number is coordSysDims.length) dimensions from dataset.
  16428. * The result of data arrengment of data dimensions like:
  16429. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  16430. * "category way": at least one axis is category axis. So the the first data
  16431. * dimension is always mapped to the first category axis and shared by
  16432. * all of the series. The other data dimensions are taken by series like
  16433. * "value way" does.
  16434. * The result of data arrengment of data dimensions like:
  16435. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  16436. *
  16437. * @return encode Never be `null/undefined`.
  16438. */
  16439. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  16440. var encode = {};
  16441. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16442. if (!datasetModel || !coordDimensions) {
  16443. return encode;
  16444. }
  16445. var encodeItemName = [];
  16446. var encodeSeriesName = [];
  16447. var ecModel = seriesModel.ecModel;
  16448. var datasetMap = innerGlobalModel(ecModel).datasetMap;
  16449. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  16450. var baseCategoryDimIndex;
  16451. var categoryWayValueDimStart;
  16452. coordDimensions = coordDimensions.slice();
  16453. each(coordDimensions, function (coordDimInfoLoose, coordDimIdx) {
  16454. var coordDimInfo = isObject(coordDimInfoLoose) ? coordDimInfoLoose : coordDimensions[coordDimIdx] = {
  16455. name: coordDimInfoLoose
  16456. };
  16457. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  16458. baseCategoryDimIndex = coordDimIdx;
  16459. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimInfo);
  16460. }
  16461. encode[coordDimInfo.name] = [];
  16462. });
  16463. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  16464. categoryWayDim: categoryWayValueDimStart,
  16465. valueWayDim: 0
  16466. }); // TODO
  16467. // Auto detect first time axis and do arrangement.
  16468. each(coordDimensions, function (coordDimInfo, coordDimIdx) {
  16469. var coordDimName = coordDimInfo.name;
  16470. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  16471. if (baseCategoryDimIndex == null) {
  16472. var start = datasetRecord.valueWayDim;
  16473. pushDim(encode[coordDimName], start, count);
  16474. pushDim(encodeSeriesName, start, count);
  16475. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  16476. // especially when encode x y specified.
  16477. // consider: when mutiple series share one dimension
  16478. // category axis, series name should better use
  16479. // the other dimsion name. On the other hand, use
  16480. // both dimensions name.
  16481. } // In category way, the first category axis.
  16482. else if (baseCategoryDimIndex === coordDimIdx) {
  16483. pushDim(encode[coordDimName], 0, count);
  16484. pushDim(encodeItemName, 0, count);
  16485. } // In category way, the other axis.
  16486. else {
  16487. var start = datasetRecord.categoryWayDim;
  16488. pushDim(encode[coordDimName], start, count);
  16489. pushDim(encodeSeriesName, start, count);
  16490. datasetRecord.categoryWayDim += count;
  16491. }
  16492. });
  16493. function pushDim(dimIdxArr, idxFrom, idxCount) {
  16494. for (var i = 0; i < idxCount; i++) {
  16495. dimIdxArr.push(idxFrom + i);
  16496. }
  16497. }
  16498. function getDataDimCountOnCoordDim(coordDimInfo) {
  16499. var dimsDef = coordDimInfo.dimsDef;
  16500. return dimsDef ? dimsDef.length : 1;
  16501. }
  16502. encodeItemName.length && (encode.itemName = encodeItemName);
  16503. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  16504. return encode;
  16505. }
  16506. /**
  16507. * Work for data like [{name: ..., value: ...}, ...].
  16508. *
  16509. * @return encode Never be `null/undefined`.
  16510. */
  16511. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  16512. var encode = {};
  16513. var datasetModel = querySeriesUpstreamDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  16514. if (!datasetModel) {
  16515. return encode;
  16516. }
  16517. var sourceFormat = source.sourceFormat;
  16518. var dimensionsDefine = source.dimensionsDefine;
  16519. var potentialNameDimIndex;
  16520. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16521. each(dimensionsDefine, function (dim, idx) {
  16522. if ((isObject(dim) ? dim.name : dim) === 'name') {
  16523. potentialNameDimIndex = idx;
  16524. }
  16525. });
  16526. }
  16527. var idxResult = function () {
  16528. var idxRes0 = {};
  16529. var idxRes1 = {};
  16530. var guessRecords = []; // 5 is an experience value.
  16531. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  16532. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  16533. guessRecords.push(guessResult);
  16534. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  16535. // and then find a name dim with the priority:
  16536. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  16537. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  16538. idxRes0.v = i;
  16539. }
  16540. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  16541. idxRes0.n = i;
  16542. }
  16543. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  16544. return idxRes0;
  16545. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  16546. // find the first BE_ORDINAL.Might as the value dim,
  16547. // and then find a name dim with the priority:
  16548. // "other dim" > "the value dim itself".
  16549. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  16550. // treated as number.
  16551. if (!isPureNumber) {
  16552. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  16553. idxRes1.v = i;
  16554. }
  16555. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  16556. idxRes1.n = i;
  16557. }
  16558. }
  16559. }
  16560. function fulfilled(idxResult) {
  16561. return idxResult.v != null && idxResult.n != null;
  16562. }
  16563. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  16564. }();
  16565. if (idxResult) {
  16566. encode.value = [idxResult.v]; // `potentialNameDimIndex` has highest priority.
  16567. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  16568. // So we dont set encodeLabel here.
  16569. encode.itemName = [nameDimIndex];
  16570. encode.seriesName = [nameDimIndex];
  16571. }
  16572. return encode;
  16573. }
  16574. /**
  16575. * @return If return null/undefined, indicate that should not use datasetModel.
  16576. */
  16577. function querySeriesUpstreamDatasetModel(seriesModel) {
  16578. // Caution: consider the scenario:
  16579. // A dataset is declared and a series is not expected to use the dataset,
  16580. // and at the beginning `setOption({series: { noData })` (just prepare other
  16581. // option but no data), then `setOption({series: {data: [...]}); In this case,
  16582. // the user should set an empty array to avoid that dataset is used by default.
  16583. var thisData = seriesModel.get('data', true);
  16584. if (!thisData) {
  16585. return queryReferringComponents(seriesModel.ecModel, 'dataset', {
  16586. index: seriesModel.get('datasetIndex', true),
  16587. id: seriesModel.get('datasetId', true)
  16588. }, SINGLE_REFERRING).models[0];
  16589. }
  16590. }
  16591. /**
  16592. * @return Always return an array event empty.
  16593. */
  16594. function queryDatasetUpstreamDatasetModels(datasetModel) {
  16595. // Only these attributes declared, we by defualt reference to `datasetIndex: 0`.
  16596. // Otherwise, no reference.
  16597. if (!datasetModel.get('transform', true) && !datasetModel.get('fromTransformResult', true)) {
  16598. return [];
  16599. }
  16600. return queryReferringComponents(datasetModel.ecModel, 'dataset', {
  16601. index: datasetModel.get('fromDatasetIndex', true),
  16602. id: datasetModel.get('fromDatasetId', true)
  16603. }, SINGLE_REFERRING).models;
  16604. }
  16605. /**
  16606. * The rule should not be complex, otherwise user might not
  16607. * be able to known where the data is wrong.
  16608. * The code is ugly, but how to make it neat?
  16609. */
  16610. function guessOrdinal(source, dimIndex) {
  16611. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  16612. } // dimIndex may be overflow source data.
  16613. // return {BE_ORDINAL}
  16614. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  16615. var result; // Experience value.
  16616. var maxLoop = 5;
  16617. if (isTypedArray(data)) {
  16618. return BE_ORDINAL.Not;
  16619. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  16620. // always exists in source.
  16621. var dimName;
  16622. var dimType;
  16623. if (dimensionsDefine) {
  16624. var dimDefItem = dimensionsDefine[dimIndex];
  16625. if (isObject(dimDefItem)) {
  16626. dimName = dimDefItem.name;
  16627. dimType = dimDefItem.type;
  16628. } else if (isString(dimDefItem)) {
  16629. dimName = dimDefItem;
  16630. }
  16631. }
  16632. if (dimType != null) {
  16633. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  16634. }
  16635. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  16636. var dataArrayRows = data;
  16637. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  16638. var sample = dataArrayRows[dimIndex];
  16639. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  16640. if ((result = detectValue(sample[startIndex + i])) != null) {
  16641. return result;
  16642. }
  16643. }
  16644. } else {
  16645. for (var i = 0; i < dataArrayRows.length && i < maxLoop; i++) {
  16646. var row = dataArrayRows[startIndex + i];
  16647. if (row && (result = detectValue(row[dimIndex])) != null) {
  16648. return result;
  16649. }
  16650. }
  16651. }
  16652. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  16653. var dataObjectRows = data;
  16654. if (!dimName) {
  16655. return BE_ORDINAL.Not;
  16656. }
  16657. for (var i = 0; i < dataObjectRows.length && i < maxLoop; i++) {
  16658. var item = dataObjectRows[i];
  16659. if (item && (result = detectValue(item[dimName])) != null) {
  16660. return result;
  16661. }
  16662. }
  16663. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  16664. var dataKeyedColumns = data;
  16665. if (!dimName) {
  16666. return BE_ORDINAL.Not;
  16667. }
  16668. var sample = dataKeyedColumns[dimName];
  16669. if (!sample || isTypedArray(sample)) {
  16670. return BE_ORDINAL.Not;
  16671. }
  16672. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  16673. if ((result = detectValue(sample[i])) != null) {
  16674. return result;
  16675. }
  16676. }
  16677. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  16678. var dataOriginal = data;
  16679. for (var i = 0; i < dataOriginal.length && i < maxLoop; i++) {
  16680. var item = dataOriginal[i];
  16681. var val = getDataItemValue(item);
  16682. if (!isArray(val)) {
  16683. return BE_ORDINAL.Not;
  16684. }
  16685. if ((result = detectValue(val[dimIndex])) != null) {
  16686. return result;
  16687. }
  16688. }
  16689. }
  16690. function detectValue(val) {
  16691. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  16692. // `isFinit('')` get `true`.
  16693. if (val != null && isFinite(val) && val !== '') {
  16694. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  16695. } else if (beStr && val !== '-') {
  16696. return BE_ORDINAL.Must;
  16697. }
  16698. }
  16699. return BE_ORDINAL.Not;
  16700. }
  16701. var internalOptionCreatorMap = createHashMap();
  16702. function registerInternalOptionCreator(mainType, creator) {
  16703. assert(internalOptionCreatorMap.get(mainType) == null && creator);
  16704. internalOptionCreatorMap.set(mainType, creator);
  16705. }
  16706. function concatInternalOptions(ecModel, mainType, newCmptOptionList) {
  16707. var internalOptionCreator = internalOptionCreatorMap.get(mainType);
  16708. if (!internalOptionCreator) {
  16709. return newCmptOptionList;
  16710. }
  16711. var internalOptions = internalOptionCreator(ecModel);
  16712. if (!internalOptions) {
  16713. return newCmptOptionList;
  16714. }
  16715. if ("development" !== 'production') {
  16716. for (var i = 0; i < internalOptions.length; i++) {
  16717. assert(isComponentIdInternal(internalOptions[i]));
  16718. }
  16719. }
  16720. return newCmptOptionList.concat(internalOptions);
  16721. }
  16722. var innerColor = makeInner();
  16723. var innerDecal = makeInner();
  16724. var PaletteMixin =
  16725. /** @class */
  16726. function () {
  16727. function PaletteMixin() {}
  16728. PaletteMixin.prototype.getColorFromPalette = function (name, scope, requestNum) {
  16729. var defaultPalette = normalizeToArray(this.get('color', true));
  16730. var layeredPalette = this.get('colorLayer', true);
  16731. return getFromPalette(this, innerColor, defaultPalette, layeredPalette, name, scope, requestNum);
  16732. };
  16733. PaletteMixin.prototype.clearColorPalette = function () {
  16734. clearPalette(this, innerColor);
  16735. };
  16736. return PaletteMixin;
  16737. }();
  16738. function getDecalFromPalette(ecModel, name, scope, requestNum) {
  16739. var defaultDecals = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  16740. return getFromPalette(ecModel, innerDecal, defaultDecals, null, name, scope, requestNum);
  16741. }
  16742. function getNearestPalette(palettes, requestColorNum) {
  16743. var paletteNum = palettes.length; // TODO palettes must be in order
  16744. for (var i = 0; i < paletteNum; i++) {
  16745. if (palettes[i].length > requestColorNum) {
  16746. return palettes[i];
  16747. }
  16748. }
  16749. return palettes[paletteNum - 1];
  16750. }
  16751. /**
  16752. * @param name MUST NOT be null/undefined. Otherwise call this function
  16753. * twise with the same parameters will get different result.
  16754. * @param scope default this.
  16755. * @return Can be null/undefined
  16756. */
  16757. function getFromPalette(that, inner, defaultPalette, layeredPalette, name, scope, requestNum) {
  16758. scope = scope || that;
  16759. var scopeFields = inner(scope);
  16760. var paletteIdx = scopeFields.paletteIdx || 0;
  16761. var paletteNameMap = scopeFields.paletteNameMap = scopeFields.paletteNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16762. if (paletteNameMap.hasOwnProperty(name)) {
  16763. return paletteNameMap[name];
  16764. }
  16765. var palette = requestNum == null || !layeredPalette ? defaultPalette : getNearestPalette(layeredPalette, requestNum); // In case can't find in layered color palette.
  16766. palette = palette || defaultPalette;
  16767. if (!palette || !palette.length) {
  16768. return;
  16769. }
  16770. var pickedPaletteItem = palette[paletteIdx];
  16771. if (name) {
  16772. paletteNameMap[name] = pickedPaletteItem;
  16773. }
  16774. scopeFields.paletteIdx = (paletteIdx + 1) % palette.length;
  16775. return pickedPaletteItem;
  16776. }
  16777. function clearPalette(that, inner) {
  16778. inner(that).paletteIdx = 0;
  16779. inner(that).paletteNameMap = {};
  16780. }
  16781. // Internal method names:
  16782. // -----------------------
  16783. var reCreateSeriesIndices;
  16784. var assertSeriesInitialized;
  16785. var initBase;
  16786. var OPTION_INNER_KEY = '\0_ec_inner';
  16787. var OPTION_INNER_VALUE = 1;
  16788. var GlobalModel =
  16789. /** @class */
  16790. function (_super) {
  16791. __extends(GlobalModel, _super);
  16792. function GlobalModel() {
  16793. return _super !== null && _super.apply(this, arguments) || this;
  16794. }
  16795. GlobalModel.prototype.init = function (option, parentModel, ecModel, theme, locale, optionManager) {
  16796. theme = theme || {};
  16797. this.option = null; // Mark as not initialized.
  16798. this._theme = new Model(theme);
  16799. this._locale = new Model(locale);
  16800. this._optionManager = optionManager;
  16801. };
  16802. GlobalModel.prototype.setOption = function (option, opts, optionPreprocessorFuncs) {
  16803. if ("development" !== 'production') {
  16804. assert(option != null, 'option is null/undefined');
  16805. assert(option[OPTION_INNER_KEY] !== OPTION_INNER_VALUE, 'please use chart.getOption()');
  16806. }
  16807. var innerOpt = normalizeSetOptionInput(opts);
  16808. this._optionManager.setOption(option, optionPreprocessorFuncs, innerOpt);
  16809. this._resetOption(null, innerOpt);
  16810. };
  16811. /**
  16812. * @param type null/undefined: reset all.
  16813. * 'recreate': force recreate all.
  16814. * 'timeline': only reset timeline option
  16815. * 'media': only reset media query option
  16816. * @return Whether option changed.
  16817. */
  16818. GlobalModel.prototype.resetOption = function (type, opt) {
  16819. return this._resetOption(type, normalizeSetOptionInput(opt));
  16820. };
  16821. GlobalModel.prototype._resetOption = function (type, opt) {
  16822. var optionChanged = false;
  16823. var optionManager = this._optionManager;
  16824. if (!type || type === 'recreate') {
  16825. var baseOption = optionManager.mountOption(type === 'recreate');
  16826. if (!this.option || type === 'recreate') {
  16827. initBase(this, baseOption);
  16828. } else {
  16829. this.restoreData();
  16830. this._mergeOption(baseOption, opt);
  16831. }
  16832. optionChanged = true;
  16833. }
  16834. if (type === 'timeline' || type === 'media') {
  16835. this.restoreData();
  16836. } // By design, if `setOption(option2)` at the second time, and `option2` is a `ECUnitOption`,
  16837. // it should better not have the same props with `MediaUnit['option']`.
  16838. // Becuase either `option2` or `MediaUnit['option']` will be always merged to "current option"
  16839. // rather than original "baseOption". If they both override a prop, the result might be
  16840. // unexpected when media state changed after `setOption` called.
  16841. // If we really need to modify a props in each `MediaUnit['option']`, use the full version
  16842. // (`{baseOption, media}`) in `setOption`.
  16843. // For `timeline`, the case is the same.
  16844. if (!type || type === 'recreate' || type === 'timeline') {
  16845. var timelineOption = optionManager.getTimelineOption(this);
  16846. if (timelineOption) {
  16847. optionChanged = true;
  16848. this._mergeOption(timelineOption, opt);
  16849. }
  16850. }
  16851. if (!type || type === 'recreate' || type === 'media') {
  16852. var mediaOptions = optionManager.getMediaOption(this);
  16853. if (mediaOptions.length) {
  16854. each(mediaOptions, function (mediaOption) {
  16855. optionChanged = true;
  16856. this._mergeOption(mediaOption, opt);
  16857. }, this);
  16858. }
  16859. }
  16860. return optionChanged;
  16861. };
  16862. GlobalModel.prototype.mergeOption = function (option) {
  16863. this._mergeOption(option, null);
  16864. };
  16865. GlobalModel.prototype._mergeOption = function (newOption, opt) {
  16866. var option = this.option;
  16867. var componentsMap = this._componentsMap;
  16868. var componentsCount = this._componentsCount;
  16869. var newCmptTypes = [];
  16870. var newCmptTypeMap = createHashMap();
  16871. var replaceMergeMainTypeMap = opt && opt.replaceMergeMainTypeMap;
  16872. resetSourceDefaulter(this); // If no component class, merge directly.
  16873. // For example: color, animaiton options, etc.
  16874. each(newOption, function (componentOption, mainType) {
  16875. if (componentOption == null) {
  16876. return;
  16877. }
  16878. if (!ComponentModel.hasClass(mainType)) {
  16879. // globalSettingTask.dirty();
  16880. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  16881. } else if (mainType) {
  16882. newCmptTypes.push(mainType);
  16883. newCmptTypeMap.set(mainType, true);
  16884. }
  16885. });
  16886. if (replaceMergeMainTypeMap) {
  16887. // If there is a mainType `xxx` in `replaceMerge` but not declared in option,
  16888. // we trade it as it is declared in option as `{xxx: []}`. Because:
  16889. // (1) for normal merge, `{xxx: null/undefined}` are the same meaning as `{xxx: []}`.
  16890. // (2) some preprocessor may convert some of `{xxx: null/undefined}` to `{xxx: []}`.
  16891. replaceMergeMainTypeMap.each(function (val, mainTypeInReplaceMerge) {
  16892. if (ComponentModel.hasClass(mainTypeInReplaceMerge) && !newCmptTypeMap.get(mainTypeInReplaceMerge)) {
  16893. newCmptTypes.push(mainTypeInReplaceMerge);
  16894. newCmptTypeMap.set(mainTypeInReplaceMerge, true);
  16895. }
  16896. });
  16897. }
  16898. ComponentModel.topologicalTravel(newCmptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  16899. function visitComponent(mainType) {
  16900. var newCmptOptionList = concatInternalOptions(this, mainType, normalizeToArray(newOption[mainType]));
  16901. var oldCmptList = componentsMap.get(mainType);
  16902. var mergeMode = // `!oldCmptList` means init. See the comment in `mappingToExists`
  16903. !oldCmptList ? 'replaceAll' : replaceMergeMainTypeMap && replaceMergeMainTypeMap.get(mainType) ? 'replaceMerge' : 'normalMerge';
  16904. var mappingResult = mappingToExists(oldCmptList, newCmptOptionList, mergeMode); // Set mainType and complete subType.
  16905. setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel); // Empty it before the travel, in order to prevent `this._componentsMap`
  16906. // from being used in the `init`/`mergeOption`/`optionUpdated` of some
  16907. // components, which is probably incorrect logic.
  16908. option[mainType] = null;
  16909. componentsMap.set(mainType, null);
  16910. componentsCount.set(mainType, 0);
  16911. var optionsByMainType = [];
  16912. var cmptsByMainType = [];
  16913. var cmptsCountByMainType = 0;
  16914. each(mappingResult, function (resultItem, index) {
  16915. var componentModel = resultItem.existing;
  16916. var newCmptOption = resultItem.newOption;
  16917. if (!newCmptOption) {
  16918. if (componentModel) {
  16919. // Consider where is no new option and should be merged using {},
  16920. // see removeEdgeAndAdd in topologicalTravel and
  16921. // ComponentModel.getAllClassMainTypes.
  16922. componentModel.mergeOption({}, this);
  16923. componentModel.optionUpdated({}, false);
  16924. } // If no both `resultItem.exist` and `resultItem.option`,
  16925. // either it is in `replaceMerge` and not matched by any id,
  16926. // or it has been removed in previous `replaceMerge` and left a "hole" in this component index.
  16927. } else {
  16928. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, true);
  16929. if (componentModel && componentModel.constructor === ComponentModelClass) {
  16930. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  16931. componentModel.mergeOption(newCmptOption, this);
  16932. componentModel.optionUpdated(newCmptOption, false);
  16933. } else {
  16934. // PENDING Global as parent ?
  16935. var extraOpt = extend({
  16936. componentIndex: index
  16937. }, resultItem.keyInfo);
  16938. componentModel = new ComponentModelClass(newCmptOption, this, this, extraOpt); // Assign `keyInfo`
  16939. extend(componentModel, extraOpt);
  16940. if (resultItem.brandNew) {
  16941. componentModel.__requireNewView = true;
  16942. }
  16943. componentModel.init(newCmptOption, this, this); // Call optionUpdated after init.
  16944. // newCmptOption has been used as componentModel.option
  16945. // and may be merged with theme and default, so pass null
  16946. // to avoid confusion.
  16947. componentModel.optionUpdated(null, true);
  16948. }
  16949. }
  16950. if (componentModel) {
  16951. optionsByMainType.push(componentModel.option);
  16952. cmptsByMainType.push(componentModel);
  16953. cmptsCountByMainType++;
  16954. } else {
  16955. // Always do assign to avoid elided item in array.
  16956. optionsByMainType.push(void 0);
  16957. cmptsByMainType.push(void 0);
  16958. }
  16959. }, this);
  16960. option[mainType] = optionsByMainType;
  16961. componentsMap.set(mainType, cmptsByMainType);
  16962. componentsCount.set(mainType, cmptsCountByMainType); // Backup series for filtering.
  16963. if (mainType === 'series') {
  16964. reCreateSeriesIndices(this);
  16965. }
  16966. } // If no series declared, ensure `_seriesIndices` initialized.
  16967. if (!this._seriesIndices) {
  16968. reCreateSeriesIndices(this);
  16969. }
  16970. };
  16971. /**
  16972. * Get option for output (cloned option and inner info removed)
  16973. */
  16974. GlobalModel.prototype.getOption = function () {
  16975. var option = clone(this.option);
  16976. each(option, function (optInMainType, mainType) {
  16977. if (ComponentModel.hasClass(mainType)) {
  16978. var opts = normalizeToArray(optInMainType); // Inner cmpts need to be removed.
  16979. // Inner cmpts might not be at last since ec5.0, but still
  16980. // compatible for users: if inner cmpt at last, splice the returned array.
  16981. var realLen = opts.length;
  16982. var metNonInner = false;
  16983. for (var i = realLen - 1; i >= 0; i--) {
  16984. // Remove options with inner id.
  16985. if (opts[i] && !isComponentIdInternal(opts[i])) {
  16986. metNonInner = true;
  16987. } else {
  16988. opts[i] = null;
  16989. !metNonInner && realLen--;
  16990. }
  16991. }
  16992. opts.length = realLen;
  16993. option[mainType] = opts;
  16994. }
  16995. });
  16996. delete option[OPTION_INNER_KEY];
  16997. return option;
  16998. };
  16999. GlobalModel.prototype.getTheme = function () {
  17000. return this._theme;
  17001. };
  17002. GlobalModel.prototype.getLocaleModel = function () {
  17003. return this._locale;
  17004. };
  17005. GlobalModel.prototype.getLocale = function (localePosition) {
  17006. var locale = this.getLocaleModel();
  17007. return locale.get(localePosition);
  17008. };
  17009. GlobalModel.prototype.setUpdatePayload = function (payload) {
  17010. this._payload = payload;
  17011. };
  17012. GlobalModel.prototype.getUpdatePayload = function () {
  17013. return this._payload;
  17014. };
  17015. /**
  17016. * @param idx If not specified, return the first one.
  17017. */
  17018. GlobalModel.prototype.getComponent = function (mainType, idx) {
  17019. var list = this._componentsMap.get(mainType);
  17020. if (list) {
  17021. var cmpt = list[idx || 0];
  17022. if (cmpt) {
  17023. return cmpt;
  17024. } else if (idx == null) {
  17025. for (var i = 0; i < list.length; i++) {
  17026. if (list[i]) {
  17027. return list[i];
  17028. }
  17029. }
  17030. }
  17031. }
  17032. };
  17033. /**
  17034. * @return Never be null/undefined.
  17035. */
  17036. GlobalModel.prototype.queryComponents = function (condition) {
  17037. var mainType = condition.mainType;
  17038. if (!mainType) {
  17039. return [];
  17040. }
  17041. var index = condition.index;
  17042. var id = condition.id;
  17043. var name = condition.name;
  17044. var cmpts = this._componentsMap.get(mainType);
  17045. if (!cmpts || !cmpts.length) {
  17046. return [];
  17047. }
  17048. var result;
  17049. if (index != null) {
  17050. result = [];
  17051. each(normalizeToArray(index), function (idx) {
  17052. cmpts[idx] && result.push(cmpts[idx]);
  17053. });
  17054. } else if (id != null) {
  17055. result = queryByIdOrName('id', id, cmpts);
  17056. } else if (name != null) {
  17057. result = queryByIdOrName('name', name, cmpts);
  17058. } else {
  17059. // Return all non-empty components in that mainType
  17060. result = filter(cmpts, function (cmpt) {
  17061. return !!cmpt;
  17062. });
  17063. }
  17064. return filterBySubType(result, condition);
  17065. };
  17066. /**
  17067. * The interface is different from queryComponents,
  17068. * which is convenient for inner usage.
  17069. *
  17070. * @usage
  17071. * let result = findComponents(
  17072. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17073. * );
  17074. * let result = findComponents(
  17075. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17076. * );
  17077. * let result = findComponents(
  17078. * {mainType: 'series',
  17079. * filter: function (model, index) {...}}
  17080. * );
  17081. * // result like [component0, componnet1, ...]
  17082. */
  17083. GlobalModel.prototype.findComponents = function (condition) {
  17084. var query = condition.query;
  17085. var mainType = condition.mainType;
  17086. var queryCond = getQueryCond(query);
  17087. var result = queryCond ? this.queryComponents(queryCond) // Retrieve all non-empty components.
  17088. : filter(this._componentsMap.get(mainType), function (cmpt) {
  17089. return !!cmpt;
  17090. });
  17091. return doFilter(filterBySubType(result, condition));
  17092. function getQueryCond(q) {
  17093. var indexAttr = mainType + 'Index';
  17094. var idAttr = mainType + 'Id';
  17095. var nameAttr = mainType + 'Name';
  17096. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17097. mainType: mainType,
  17098. // subType will be filtered finally.
  17099. index: q[indexAttr],
  17100. id: q[idAttr],
  17101. name: q[nameAttr]
  17102. } : null;
  17103. }
  17104. function doFilter(res) {
  17105. return condition.filter ? filter(res, condition.filter) : res;
  17106. }
  17107. };
  17108. GlobalModel.prototype.eachComponent = function (mainType, cb, context) {
  17109. var componentsMap = this._componentsMap;
  17110. if (isFunction(mainType)) {
  17111. var ctxForAll_1 = cb;
  17112. var cbForAll_1 = mainType;
  17113. componentsMap.each(function (cmpts, componentType) {
  17114. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17115. var cmpt = cmpts[i];
  17116. cmpt && cbForAll_1.call(ctxForAll_1, componentType, cmpt, cmpt.componentIndex);
  17117. }
  17118. });
  17119. } else {
  17120. var cmpts = isString(mainType) ? componentsMap.get(mainType) : isObject(mainType) ? this.findComponents(mainType) : null;
  17121. for (var i = 0; cmpts && i < cmpts.length; i++) {
  17122. var cmpt = cmpts[i];
  17123. cmpt && cb.call(context, cmpt, cmpt.componentIndex);
  17124. }
  17125. }
  17126. };
  17127. /**
  17128. * Get series list before filtered by name.
  17129. */
  17130. GlobalModel.prototype.getSeriesByName = function (name) {
  17131. var nameStr = convertOptionIdName(name, null);
  17132. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17133. return !!oneSeries && nameStr != null && oneSeries.name === nameStr;
  17134. });
  17135. };
  17136. /**
  17137. * Get series list before filtered by index.
  17138. */
  17139. GlobalModel.prototype.getSeriesByIndex = function (seriesIndex) {
  17140. return this._componentsMap.get('series')[seriesIndex];
  17141. };
  17142. /**
  17143. * Get series list before filtered by type.
  17144. * FIXME: rename to getRawSeriesByType?
  17145. */
  17146. GlobalModel.prototype.getSeriesByType = function (subType) {
  17147. return filter(this._componentsMap.get('series'), function (oneSeries) {
  17148. return !!oneSeries && oneSeries.subType === subType;
  17149. });
  17150. };
  17151. /**
  17152. * Get all series before filtered.
  17153. */
  17154. GlobalModel.prototype.getSeries = function () {
  17155. return filter(this._componentsMap.get('series').slice(), function (oneSeries) {
  17156. return !!oneSeries;
  17157. });
  17158. };
  17159. /**
  17160. * Count series before filtered.
  17161. */
  17162. GlobalModel.prototype.getSeriesCount = function () {
  17163. return this._componentsCount.get('series');
  17164. };
  17165. /**
  17166. * After filtering, series may be different
  17167. * frome raw series.
  17168. */
  17169. GlobalModel.prototype.eachSeries = function (cb, context) {
  17170. assertSeriesInitialized(this);
  17171. each(this._seriesIndices, function (rawSeriesIndex) {
  17172. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17173. cb.call(context, series, rawSeriesIndex);
  17174. }, this);
  17175. };
  17176. /**
  17177. * Iterate raw series before filtered.
  17178. *
  17179. * @param {Function} cb
  17180. * @param {*} context
  17181. */
  17182. GlobalModel.prototype.eachRawSeries = function (cb, context) {
  17183. each(this._componentsMap.get('series'), function (series) {
  17184. series && cb.call(context, series, series.componentIndex);
  17185. });
  17186. };
  17187. /**
  17188. * After filtering, series may be different.
  17189. * frome raw series.
  17190. */
  17191. GlobalModel.prototype.eachSeriesByType = function (subType, cb, context) {
  17192. assertSeriesInitialized(this);
  17193. each(this._seriesIndices, function (rawSeriesIndex) {
  17194. var series = this._componentsMap.get('series')[rawSeriesIndex];
  17195. if (series.subType === subType) {
  17196. cb.call(context, series, rawSeriesIndex);
  17197. }
  17198. }, this);
  17199. };
  17200. /**
  17201. * Iterate raw series before filtered of given type.
  17202. */
  17203. GlobalModel.prototype.eachRawSeriesByType = function (subType, cb, context) {
  17204. return each(this.getSeriesByType(subType), cb, context);
  17205. };
  17206. GlobalModel.prototype.isSeriesFiltered = function (seriesModel) {
  17207. assertSeriesInitialized(this);
  17208. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  17209. };
  17210. GlobalModel.prototype.getCurrentSeriesIndices = function () {
  17211. return (this._seriesIndices || []).slice();
  17212. };
  17213. GlobalModel.prototype.filterSeries = function (cb, context) {
  17214. assertSeriesInitialized(this);
  17215. var newSeriesIndices = [];
  17216. each(this._seriesIndices, function (seriesRawIdx) {
  17217. var series = this._componentsMap.get('series')[seriesRawIdx];
  17218. cb.call(context, series, seriesRawIdx) && newSeriesIndices.push(seriesRawIdx);
  17219. }, this);
  17220. this._seriesIndices = newSeriesIndices;
  17221. this._seriesIndicesMap = createHashMap(newSeriesIndices);
  17222. };
  17223. GlobalModel.prototype.restoreData = function (payload) {
  17224. reCreateSeriesIndices(this);
  17225. var componentsMap = this._componentsMap;
  17226. var componentTypes = [];
  17227. componentsMap.each(function (components, componentType) {
  17228. if (ComponentModel.hasClass(componentType)) {
  17229. componentTypes.push(componentType);
  17230. }
  17231. });
  17232. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType) {
  17233. each(componentsMap.get(componentType), function (component) {
  17234. if (component && (componentType !== 'series' || !isNotTargetSeries(component, payload))) {
  17235. component.restoreData();
  17236. }
  17237. });
  17238. });
  17239. };
  17240. GlobalModel.internalField = function () {
  17241. reCreateSeriesIndices = function (ecModel) {
  17242. var seriesIndices = ecModel._seriesIndices = [];
  17243. each(ecModel._componentsMap.get('series'), function (series) {
  17244. // series may have been removed by `replaceMerge`.
  17245. series && seriesIndices.push(series.componentIndex);
  17246. });
  17247. ecModel._seriesIndicesMap = createHashMap(seriesIndices);
  17248. };
  17249. assertSeriesInitialized = function (ecModel) {
  17250. // Components that use _seriesIndices should depends on series component,
  17251. // which make sure that their initialization is after series.
  17252. if ("development" !== 'production') {
  17253. if (!ecModel._seriesIndices) {
  17254. throw new Error('Option should contains series.');
  17255. }
  17256. }
  17257. };
  17258. initBase = function (ecModel, baseOption) {
  17259. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  17260. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  17261. ecModel.option = {};
  17262. ecModel.option[OPTION_INNER_KEY] = OPTION_INNER_VALUE; // Init with series: [], in case of calling findSeries method
  17263. // before series initialized.
  17264. ecModel._componentsMap = createHashMap({
  17265. series: []
  17266. });
  17267. ecModel._componentsCount = createHashMap(); // If user spefied `option.aria`, aria will be enable. This detection should be
  17268. // performed before theme and globalDefault merge.
  17269. var airaOption = baseOption.aria;
  17270. if (isObject(airaOption) && airaOption.enabled == null) {
  17271. airaOption.enabled = true;
  17272. }
  17273. mergeTheme(baseOption, ecModel._theme.option); // TODO Needs clone when merging to the unexisted property
  17274. merge(baseOption, globalDefault, false);
  17275. ecModel._mergeOption(baseOption, null);
  17276. };
  17277. }();
  17278. return GlobalModel;
  17279. }(Model);
  17280. function isNotTargetSeries(seriesModel, payload) {
  17281. if (payload) {
  17282. var index = payload.seriesIndex;
  17283. var id = payload.seriesId;
  17284. var name_1 = payload.seriesName;
  17285. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name_1 != null && seriesModel.name !== name_1;
  17286. }
  17287. }
  17288. function mergeTheme(option, theme) {
  17289. // PENDING
  17290. // NOT use `colorLayer` in theme if option has `color`
  17291. var notMergeColorLayer = option.color && !option.colorLayer;
  17292. each(theme, function (themeItem, name) {
  17293. if (name === 'colorLayer' && notMergeColorLayer) {
  17294. return;
  17295. } // If it is component model mainType, the model handles that merge later.
  17296. // otherwise, merge them here.
  17297. if (!ComponentModel.hasClass(name)) {
  17298. if (typeof themeItem === 'object') {
  17299. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  17300. } else {
  17301. if (option[name] == null) {
  17302. option[name] = themeItem;
  17303. }
  17304. }
  17305. }
  17306. });
  17307. }
  17308. function queryByIdOrName(attr, idOrName, cmpts) {
  17309. // Here is a break from echarts4: string and number are
  17310. // treated as equal.
  17311. if (isArray(idOrName)) {
  17312. var keyMap_1 = createHashMap();
  17313. each(idOrName, function (idOrNameItem) {
  17314. if (idOrNameItem != null) {
  17315. var idName = convertOptionIdName(idOrNameItem, null);
  17316. idName != null && keyMap_1.set(idOrNameItem, true);
  17317. }
  17318. });
  17319. return filter(cmpts, function (cmpt) {
  17320. return cmpt && keyMap_1.get(cmpt[attr]);
  17321. });
  17322. } else {
  17323. var idName_1 = convertOptionIdName(idOrName, null);
  17324. return filter(cmpts, function (cmpt) {
  17325. return cmpt && idName_1 != null && cmpt[attr] === idName_1;
  17326. });
  17327. }
  17328. }
  17329. function filterBySubType(components, condition) {
  17330. // Using hasOwnProperty for restrict. Consider
  17331. // subType is undefined in user payload.
  17332. return condition.hasOwnProperty('subType') ? filter(components, function (cmpt) {
  17333. return cmpt && cmpt.subType === condition.subType;
  17334. }) : components;
  17335. }
  17336. function normalizeSetOptionInput(opts) {
  17337. var replaceMergeMainTypeMap = createHashMap();
  17338. opts && each(normalizeToArray(opts.replaceMerge), function (mainType) {
  17339. if ("development" !== 'production') {
  17340. assert(ComponentModel.hasClass(mainType), '"' + mainType + '" is not valid component main type in "replaceMerge"');
  17341. }
  17342. replaceMergeMainTypeMap.set(mainType, true);
  17343. });
  17344. return {
  17345. replaceMergeMainTypeMap: replaceMergeMainTypeMap
  17346. };
  17347. }
  17348. mixin(GlobalModel, PaletteMixin);
  17349. var availableMethods = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', // 'getModel',
  17350. 'getOption', // 'getViewOfComponentModel',
  17351. // 'getViewOfSeriesModel',
  17352. 'getId', 'updateLabelLayout'];
  17353. var ExtensionAPI =
  17354. /** @class */
  17355. function () {
  17356. function ExtensionAPI(ecInstance) {
  17357. each(availableMethods, function (methodName) {
  17358. this[methodName] = bind(ecInstance[methodName], ecInstance);
  17359. }, this);
  17360. }
  17361. return ExtensionAPI;
  17362. }();
  17363. var coordinateSystemCreators = {};
  17364. var CoordinateSystemManager =
  17365. /** @class */
  17366. function () {
  17367. function CoordinateSystemManager() {
  17368. this._coordinateSystems = [];
  17369. }
  17370. CoordinateSystemManager.prototype.create = function (ecModel, api) {
  17371. var coordinateSystems = [];
  17372. each(coordinateSystemCreators, function (creater, type) {
  17373. var list = creater.create(ecModel, api);
  17374. coordinateSystems = coordinateSystems.concat(list || []);
  17375. });
  17376. this._coordinateSystems = coordinateSystems;
  17377. };
  17378. CoordinateSystemManager.prototype.update = function (ecModel, api) {
  17379. each(this._coordinateSystems, function (coordSys) {
  17380. coordSys.update && coordSys.update(ecModel, api);
  17381. });
  17382. };
  17383. CoordinateSystemManager.prototype.getCoordinateSystems = function () {
  17384. return this._coordinateSystems.slice();
  17385. };
  17386. CoordinateSystemManager.register = function (type, creator) {
  17387. coordinateSystemCreators[type] = creator;
  17388. };
  17389. CoordinateSystemManager.get = function (type) {
  17390. return coordinateSystemCreators[type];
  17391. };
  17392. return CoordinateSystemManager;
  17393. }();
  17394. var QUERY_REG = /^(min|max)?(.+)$/; // Key: mainType
  17395. // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>;
  17396. /**
  17397. * TERM EXPLANATIONS:
  17398. * See `ECOption` and `ECUnitOption` in `src/util/types.ts`.
  17399. */
  17400. var OptionManager =
  17401. /** @class */
  17402. function () {
  17403. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  17404. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  17405. // rawOption cloned and backuped when timeline changed, which does no
  17406. // good to performance. What's more, that both timeline and setOption
  17407. // method supply 'notMerge' brings complex and some problems.
  17408. // Consider this case:
  17409. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  17410. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  17411. function OptionManager(api) {
  17412. this._timelineOptions = [];
  17413. this._mediaList = [];
  17414. /**
  17415. * -1, means default.
  17416. * empty means no media.
  17417. */
  17418. this._currentMediaIndices = [];
  17419. this._api = api;
  17420. }
  17421. OptionManager.prototype.setOption = function (rawOption, optionPreprocessorFuncs, opt) {
  17422. if (rawOption) {
  17423. // That set dat primitive is dangerous if user reuse the data when setOption again.
  17424. each(normalizeToArray(rawOption.series), function (series) {
  17425. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  17426. });
  17427. each(normalizeToArray(rawOption.dataset), function (dataset) {
  17428. dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source);
  17429. });
  17430. } // Caution: some series modify option data, if do not clone,
  17431. // it should ensure that the repeat modify correctly
  17432. // (create a new object when modify itself).
  17433. rawOption = clone(rawOption); // FIXME
  17434. // If some property is set in timeline options or media option but
  17435. // not set in baseOption, a warning should be given.
  17436. var optionBackup = this._optionBackup;
  17437. var newParsedOption = parseRawOption(rawOption, optionPreprocessorFuncs, !optionBackup);
  17438. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  17439. if (optionBackup) {
  17440. // FIXME
  17441. // the restore merge solution is essentially incorrect.
  17442. // the mapping can not be 100% consistent with ecModel, which probably brings
  17443. // potential bug!
  17444. // The first merge is delayed, becuase in most cases, users do not call `setOption` twice.
  17445. // let fakeCmptsMap = this._fakeCmptsMap;
  17446. // if (!fakeCmptsMap) {
  17447. // fakeCmptsMap = this._fakeCmptsMap = createHashMap();
  17448. // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null);
  17449. // }
  17450. // mergeToBackupOption(
  17451. // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt
  17452. // );
  17453. // For simplicity, timeline options and media options do not support merge,
  17454. // that is, if you `setOption` twice and both has timeline options, the latter
  17455. // timeline opitons will not be merged to the formers, but just substitude them.
  17456. if (newParsedOption.timelineOptions.length) {
  17457. optionBackup.timelineOptions = newParsedOption.timelineOptions;
  17458. }
  17459. if (newParsedOption.mediaList.length) {
  17460. optionBackup.mediaList = newParsedOption.mediaList;
  17461. }
  17462. if (newParsedOption.mediaDefault) {
  17463. optionBackup.mediaDefault = newParsedOption.mediaDefault;
  17464. }
  17465. } else {
  17466. this._optionBackup = newParsedOption;
  17467. }
  17468. };
  17469. OptionManager.prototype.mountOption = function (isRecreate) {
  17470. var optionBackup = this._optionBackup;
  17471. this._timelineOptions = optionBackup.timelineOptions;
  17472. this._mediaList = optionBackup.mediaList;
  17473. this._mediaDefault = optionBackup.mediaDefault;
  17474. this._currentMediaIndices = [];
  17475. return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  17476. // called, and is merged into every new option by inner method `mergeToBackupOption`
  17477. // each time `setOption` called, can be only used in `isRecreate`, because
  17478. // its reliability is under suspicion. In other cases option merge is
  17479. // performed by `model.mergeOption`.
  17480. ? optionBackup.baseOption : this._newBaseOption);
  17481. };
  17482. OptionManager.prototype.getTimelineOption = function (ecModel) {
  17483. var option;
  17484. var timelineOptions = this._timelineOptions;
  17485. if (timelineOptions.length) {
  17486. // getTimelineOption can only be called after ecModel inited,
  17487. // so we can get currentIndex from timelineModel.
  17488. var timelineModel = ecModel.getComponent('timeline');
  17489. if (timelineModel) {
  17490. option = clone( // FIXME:TS as TimelineModel or quivlant interface
  17491. timelineOptions[timelineModel.getCurrentIndex()]);
  17492. }
  17493. }
  17494. return option;
  17495. };
  17496. OptionManager.prototype.getMediaOption = function (ecModel) {
  17497. var ecWidth = this._api.getWidth();
  17498. var ecHeight = this._api.getHeight();
  17499. var mediaList = this._mediaList;
  17500. var mediaDefault = this._mediaDefault;
  17501. var indices = [];
  17502. var result = []; // No media defined.
  17503. if (!mediaList.length && !mediaDefault) {
  17504. return result;
  17505. } // Multi media may be applied, the latter defined media has higher priority.
  17506. for (var i = 0, len = mediaList.length; i < len; i++) {
  17507. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  17508. indices.push(i);
  17509. }
  17510. } // FIXME
  17511. // Whether mediaDefault should force users to provide? Otherwise
  17512. // the change by media query can not be recorvered.
  17513. if (!indices.length && mediaDefault) {
  17514. indices = [-1];
  17515. }
  17516. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  17517. result = map(indices, function (index) {
  17518. return clone(index === -1 ? mediaDefault.option : mediaList[index].option);
  17519. });
  17520. } // Otherwise return nothing.
  17521. this._currentMediaIndices = indices;
  17522. return result;
  17523. };
  17524. return OptionManager;
  17525. }();
  17526. /**
  17527. * [RAW_OPTION_PATTERNS]
  17528. * (Note: "series: []" represents all other props in `ECUnitOption`)
  17529. *
  17530. * (1) No prop "baseOption" declared:
  17531. * Root option is used as "baseOption" (except prop "options" and "media").
  17532. * ```js
  17533. * option = {
  17534. * series: [],
  17535. * timeline: {},
  17536. * options: [],
  17537. * };
  17538. * option = {
  17539. * series: [],
  17540. * media: {},
  17541. * };
  17542. * option = {
  17543. * series: [],
  17544. * timeline: {},
  17545. * options: [],
  17546. * media: {},
  17547. * }
  17548. * ```
  17549. *
  17550. * (2) Prop "baseOption" declared:
  17551. * If "baseOption" declared, `ECUnitOption` props can only be declared
  17552. * inside "baseOption" except prop "timeline" (compat ec2).
  17553. * ```js
  17554. * option = {
  17555. * baseOption: {
  17556. * timeline: {},
  17557. * series: [],
  17558. * },
  17559. * options: []
  17560. * };
  17561. * option = {
  17562. * baseOption: {
  17563. * series: [],
  17564. * },
  17565. * media: []
  17566. * };
  17567. * option = {
  17568. * baseOption: {
  17569. * timeline: {},
  17570. * series: [],
  17571. * },
  17572. * options: []
  17573. * media: []
  17574. * };
  17575. * option = {
  17576. * // ec3 compat ec2: allow (only) `timeline` declared
  17577. * // outside baseOption. Keep this setting for compat.
  17578. * timeline: {},
  17579. * baseOption: {
  17580. * series: [],
  17581. * },
  17582. * options: [],
  17583. * media: []
  17584. * };
  17585. * ```
  17586. */
  17587. function parseRawOption( // `rawOption` May be modified
  17588. rawOption, optionPreprocessorFuncs, isNew) {
  17589. var mediaList = [];
  17590. var mediaDefault;
  17591. var baseOption;
  17592. var declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above.
  17593. var timelineOnRoot = rawOption.timeline;
  17594. var timelineOptionsOnRoot = rawOption.options;
  17595. var mediaOnRoot = rawOption.media;
  17596. var hasMedia = !!rawOption.media;
  17597. var hasTimeline = !!(timelineOptionsOnRoot || timelineOnRoot || declaredBaseOption && declaredBaseOption.timeline);
  17598. if (declaredBaseOption) {
  17599. baseOption = declaredBaseOption; // For merge option.
  17600. if (!baseOption.timeline) {
  17601. baseOption.timeline = timelineOnRoot;
  17602. }
  17603. } // For convenience, enable to use the root option as the `baseOption`:
  17604. // `{ ...normalOptionProps, media: [{ ... }, { ... }] }`
  17605. else {
  17606. if (hasTimeline || hasMedia) {
  17607. rawOption.options = rawOption.media = null;
  17608. }
  17609. baseOption = rawOption;
  17610. }
  17611. if (hasMedia) {
  17612. if (isArray(mediaOnRoot)) {
  17613. each(mediaOnRoot, function (singleMedia) {
  17614. if ("development" !== 'production') {
  17615. // Real case of wrong config.
  17616. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject(singleMedia.query.option)) {
  17617. error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }');
  17618. }
  17619. }
  17620. if (singleMedia && singleMedia.option) {
  17621. if (singleMedia.query) {
  17622. mediaList.push(singleMedia);
  17623. } else if (!mediaDefault) {
  17624. // Use the first media default.
  17625. mediaDefault = singleMedia;
  17626. }
  17627. }
  17628. });
  17629. } else {
  17630. if ("development" !== 'production') {
  17631. // Real case of wrong config.
  17632. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }');
  17633. }
  17634. }
  17635. }
  17636. doPreprocess(baseOption);
  17637. each(timelineOptionsOnRoot, function (option) {
  17638. return doPreprocess(option);
  17639. });
  17640. each(mediaList, function (media) {
  17641. return doPreprocess(media.option);
  17642. });
  17643. function doPreprocess(option) {
  17644. each(optionPreprocessorFuncs, function (preProcess) {
  17645. preProcess(option, isNew);
  17646. });
  17647. }
  17648. return {
  17649. baseOption: baseOption,
  17650. timelineOptions: timelineOptionsOnRoot || [],
  17651. mediaDefault: mediaDefault,
  17652. mediaList: mediaList
  17653. };
  17654. }
  17655. /**
  17656. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  17657. * Support: width, height, aspectRatio
  17658. * Can use max or min as prefix.
  17659. */
  17660. function applyMediaQuery(query, ecWidth, ecHeight) {
  17661. var realMap = {
  17662. width: ecWidth,
  17663. height: ecHeight,
  17664. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  17665. };
  17666. var applicatable = true;
  17667. each(query, function (value, attr) {
  17668. var matched = attr.match(QUERY_REG);
  17669. if (!matched || !matched[1] || !matched[2]) {
  17670. return;
  17671. }
  17672. var operator = matched[1];
  17673. var realAttr = matched[2].toLowerCase();
  17674. if (!compare(realMap[realAttr], value, operator)) {
  17675. applicatable = false;
  17676. }
  17677. });
  17678. return applicatable;
  17679. }
  17680. function compare(real, expect, operator) {
  17681. if (operator === 'min') {
  17682. return real >= expect;
  17683. } else if (operator === 'max') {
  17684. return real <= expect;
  17685. } else {
  17686. // Equals
  17687. return real === expect;
  17688. }
  17689. }
  17690. function indicesEquals(indices1, indices2) {
  17691. // indices is always order by asc and has only finite number.
  17692. return indices1.join(',') === indices2.join(',');
  17693. }
  17694. var each$2 = each;
  17695. var isObject$1 = isObject;
  17696. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  17697. function compatEC2ItemStyle(opt) {
  17698. var itemStyleOpt = opt && opt.itemStyle;
  17699. if (!itemStyleOpt) {
  17700. return;
  17701. }
  17702. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  17703. var styleName = POSSIBLE_STYLES[i];
  17704. var normalItemStyleOpt = itemStyleOpt.normal;
  17705. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  17706. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  17707. if ("development" !== 'production') {
  17708. deprecateReplaceLog("itemStyle.normal." + styleName, styleName);
  17709. }
  17710. opt[styleName] = opt[styleName] || {};
  17711. if (!opt[styleName].normal) {
  17712. opt[styleName].normal = normalItemStyleOpt[styleName];
  17713. } else {
  17714. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  17715. }
  17716. normalItemStyleOpt[styleName] = null;
  17717. }
  17718. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  17719. if ("development" !== 'production') {
  17720. deprecateReplaceLog("itemStyle.emphasis." + styleName, "emphasis." + styleName);
  17721. }
  17722. opt[styleName] = opt[styleName] || {};
  17723. if (!opt[styleName].emphasis) {
  17724. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  17725. } else {
  17726. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  17727. }
  17728. emphasisItemStyleOpt[styleName] = null;
  17729. }
  17730. }
  17731. }
  17732. function convertNormalEmphasis(opt, optType, useExtend) {
  17733. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  17734. var normalOpt = opt[optType].normal;
  17735. var emphasisOpt = opt[optType].emphasis;
  17736. if (normalOpt) {
  17737. if ("development" !== 'production') {
  17738. // eslint-disable-next-line max-len
  17739. deprecateLog("'normal' hierarchy in " + optType + " has been removed since 4.0. All style properties are configured in " + optType + " directly now.");
  17740. } // Timeline controlStyle has other properties besides normal and emphasis
  17741. if (useExtend) {
  17742. opt[optType].normal = opt[optType].emphasis = null;
  17743. defaults(opt[optType], normalOpt);
  17744. } else {
  17745. opt[optType] = normalOpt;
  17746. }
  17747. }
  17748. if (emphasisOpt) {
  17749. if ("development" !== 'production') {
  17750. deprecateLog(optType + ".emphasis has been changed to emphasis." + optType + " since 4.0");
  17751. }
  17752. opt.emphasis = opt.emphasis || {};
  17753. opt.emphasis[optType] = emphasisOpt; // Also compat the case user mix the style and focus together in ec3 style
  17754. // for example: { itemStyle: { normal: {}, emphasis: {focus, shadowBlur} } }
  17755. if (emphasisOpt.focus) {
  17756. opt.emphasis.focus = emphasisOpt.focus;
  17757. }
  17758. if (emphasisOpt.blurScope) {
  17759. opt.emphasis.blurScope = emphasisOpt.blurScope;
  17760. }
  17761. }
  17762. }
  17763. }
  17764. function removeEC3NormalStatus(opt) {
  17765. convertNormalEmphasis(opt, 'itemStyle');
  17766. convertNormalEmphasis(opt, 'lineStyle');
  17767. convertNormalEmphasis(opt, 'areaStyle');
  17768. convertNormalEmphasis(opt, 'label');
  17769. convertNormalEmphasis(opt, 'labelLine'); // treemap
  17770. convertNormalEmphasis(opt, 'upperLabel'); // graph
  17771. convertNormalEmphasis(opt, 'edgeLabel');
  17772. }
  17773. function compatTextStyle(opt, propName) {
  17774. // Check whether is not object (string\null\undefined ...)
  17775. var labelOptSingle = isObject$1(opt) && opt[propName];
  17776. var textStyle = isObject$1(labelOptSingle) && labelOptSingle.textStyle;
  17777. if (textStyle) {
  17778. if ("development" !== 'production') {
  17779. // eslint-disable-next-line max-len
  17780. deprecateLog("textStyle hierarchy in " + propName + " has been removed since 4.0. All textStyle properties are configured in " + propName + " directly now.");
  17781. }
  17782. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  17783. var textPropName = TEXT_STYLE_OPTIONS[i];
  17784. if (textStyle.hasOwnProperty(textPropName)) {
  17785. labelOptSingle[textPropName] = textStyle[textPropName];
  17786. }
  17787. }
  17788. }
  17789. }
  17790. function compatEC3CommonStyles(opt) {
  17791. if (opt) {
  17792. removeEC3NormalStatus(opt);
  17793. compatTextStyle(opt, 'label');
  17794. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  17795. }
  17796. }
  17797. function processSeries(seriesOpt) {
  17798. if (!isObject$1(seriesOpt)) {
  17799. return;
  17800. }
  17801. compatEC2ItemStyle(seriesOpt);
  17802. removeEC3NormalStatus(seriesOpt);
  17803. compatTextStyle(seriesOpt, 'label'); // treemap
  17804. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  17805. compatTextStyle(seriesOpt, 'edgeLabel');
  17806. if (seriesOpt.emphasis) {
  17807. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  17808. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  17809. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  17810. }
  17811. var markPoint = seriesOpt.markPoint;
  17812. if (markPoint) {
  17813. compatEC2ItemStyle(markPoint);
  17814. compatEC3CommonStyles(markPoint);
  17815. }
  17816. var markLine = seriesOpt.markLine;
  17817. if (markLine) {
  17818. compatEC2ItemStyle(markLine);
  17819. compatEC3CommonStyles(markLine);
  17820. }
  17821. var markArea = seriesOpt.markArea;
  17822. if (markArea) {
  17823. compatEC3CommonStyles(markArea);
  17824. }
  17825. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  17826. // then the backward compat based on option type will not be performed.
  17827. if (seriesOpt.type === 'graph') {
  17828. data = data || seriesOpt.nodes;
  17829. var edgeData = seriesOpt.links || seriesOpt.edges;
  17830. if (edgeData && !isTypedArray(edgeData)) {
  17831. for (var i = 0; i < edgeData.length; i++) {
  17832. compatEC3CommonStyles(edgeData[i]);
  17833. }
  17834. }
  17835. each(seriesOpt.categories, function (opt) {
  17836. removeEC3NormalStatus(opt);
  17837. });
  17838. }
  17839. if (data && !isTypedArray(data)) {
  17840. for (var i = 0; i < data.length; i++) {
  17841. compatEC3CommonStyles(data[i]);
  17842. }
  17843. } // mark point data
  17844. markPoint = seriesOpt.markPoint;
  17845. if (markPoint && markPoint.data) {
  17846. var mpData = markPoint.data;
  17847. for (var i = 0; i < mpData.length; i++) {
  17848. compatEC3CommonStyles(mpData[i]);
  17849. }
  17850. } // mark line data
  17851. markLine = seriesOpt.markLine;
  17852. if (markLine && markLine.data) {
  17853. var mlData = markLine.data;
  17854. for (var i = 0; i < mlData.length; i++) {
  17855. if (isArray(mlData[i])) {
  17856. compatEC3CommonStyles(mlData[i][0]);
  17857. compatEC3CommonStyles(mlData[i][1]);
  17858. } else {
  17859. compatEC3CommonStyles(mlData[i]);
  17860. }
  17861. }
  17862. } // Series
  17863. if (seriesOpt.type === 'gauge') {
  17864. compatTextStyle(seriesOpt, 'axisLabel');
  17865. compatTextStyle(seriesOpt, 'title');
  17866. compatTextStyle(seriesOpt, 'detail');
  17867. } else if (seriesOpt.type === 'treemap') {
  17868. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  17869. each(seriesOpt.levels, function (opt) {
  17870. removeEC3NormalStatus(opt);
  17871. });
  17872. } else if (seriesOpt.type === 'tree') {
  17873. removeEC3NormalStatus(seriesOpt.leaves);
  17874. } // sunburst starts from ec4, so it does not need to compat levels.
  17875. }
  17876. function toArr(o) {
  17877. return isArray(o) ? o : o ? [o] : [];
  17878. }
  17879. function toObj(o) {
  17880. return (isArray(o) ? o[0] : o) || {};
  17881. }
  17882. function globalCompatStyle(option, isTheme) {
  17883. each$2(toArr(option.series), function (seriesOpt) {
  17884. isObject$1(seriesOpt) && processSeries(seriesOpt);
  17885. });
  17886. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  17887. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  17888. each$2(axes, function (axisName) {
  17889. each$2(toArr(option[axisName]), function (axisOpt) {
  17890. if (axisOpt) {
  17891. compatTextStyle(axisOpt, 'axisLabel');
  17892. compatTextStyle(axisOpt.axisPointer, 'label');
  17893. }
  17894. });
  17895. });
  17896. each$2(toArr(option.parallel), function (parallelOpt) {
  17897. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  17898. compatTextStyle(parallelAxisDefault, 'axisLabel');
  17899. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  17900. });
  17901. each$2(toArr(option.calendar), function (calendarOpt) {
  17902. convertNormalEmphasis(calendarOpt, 'itemStyle');
  17903. compatTextStyle(calendarOpt, 'dayLabel');
  17904. compatTextStyle(calendarOpt, 'monthLabel');
  17905. compatTextStyle(calendarOpt, 'yearLabel');
  17906. }); // radar.name.textStyle
  17907. each$2(toArr(option.radar), function (radarOpt) {
  17908. compatTextStyle(radarOpt, 'name'); // Use axisName instead of name because component has name property
  17909. if (radarOpt.name && radarOpt.axisName == null) {
  17910. radarOpt.axisName = radarOpt.name;
  17911. delete radarOpt.name;
  17912. if ("development" !== 'production') {
  17913. deprecateLog('name property in radar component has been changed to axisName');
  17914. }
  17915. }
  17916. if (radarOpt.nameGap != null && radarOpt.axisNameGap == null) {
  17917. radarOpt.axisNameGap = radarOpt.nameGap;
  17918. delete radarOpt.nameGap;
  17919. if ("development" !== 'production') {
  17920. deprecateLog('nameGap property in radar component has been changed to axisNameGap');
  17921. }
  17922. }
  17923. });
  17924. each$2(toArr(option.geo), function (geoOpt) {
  17925. if (isObject$1(geoOpt)) {
  17926. compatEC3CommonStyles(geoOpt);
  17927. each$2(toArr(geoOpt.regions), function (regionObj) {
  17928. compatEC3CommonStyles(regionObj);
  17929. });
  17930. }
  17931. });
  17932. each$2(toArr(option.timeline), function (timelineOpt) {
  17933. compatEC3CommonStyles(timelineOpt);
  17934. convertNormalEmphasis(timelineOpt, 'label');
  17935. convertNormalEmphasis(timelineOpt, 'itemStyle');
  17936. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  17937. var data = timelineOpt.data;
  17938. isArray(data) && each(data, function (item) {
  17939. if (isObject(item)) {
  17940. convertNormalEmphasis(item, 'label');
  17941. convertNormalEmphasis(item, 'itemStyle');
  17942. }
  17943. });
  17944. });
  17945. each$2(toArr(option.toolbox), function (toolboxOpt) {
  17946. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  17947. each$2(toolboxOpt.feature, function (featureOpt) {
  17948. convertNormalEmphasis(featureOpt, 'iconStyle');
  17949. });
  17950. });
  17951. compatTextStyle(toObj(option.axisPointer), 'label');
  17952. compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); // Clean logs
  17953. // storedLogs = {};
  17954. }
  17955. function get(opt, path) {
  17956. var pathArr = path.split(',');
  17957. var obj = opt;
  17958. for (var i = 0; i < pathArr.length; i++) {
  17959. obj = obj && obj[pathArr[i]];
  17960. if (obj == null) {
  17961. break;
  17962. }
  17963. }
  17964. return obj;
  17965. }
  17966. function set$1(opt, path, val, overwrite) {
  17967. var pathArr = path.split(',');
  17968. var obj = opt;
  17969. var key;
  17970. var i = 0;
  17971. for (; i < pathArr.length - 1; i++) {
  17972. key = pathArr[i];
  17973. if (obj[key] == null) {
  17974. obj[key] = {};
  17975. }
  17976. obj = obj[key];
  17977. }
  17978. if (overwrite || obj[pathArr[i]] == null) {
  17979. obj[pathArr[i]] = val;
  17980. }
  17981. }
  17982. function compatLayoutProperties(option) {
  17983. option && each(LAYOUT_PROPERTIES, function (prop) {
  17984. if (prop[0] in option && !(prop[1] in option)) {
  17985. option[prop[1]] = option[prop[0]];
  17986. }
  17987. });
  17988. }
  17989. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  17990. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  17991. var BAR_ITEM_STYLE_MAP = [['borderRadius', 'barBorderRadius'], ['borderColor', 'barBorderColor'], ['borderWidth', 'barBorderWidth']];
  17992. function compatBarItemStyle(option) {
  17993. var itemStyle = option && option.itemStyle;
  17994. if (itemStyle) {
  17995. for (var i = 0; i < BAR_ITEM_STYLE_MAP.length; i++) {
  17996. var oldName = BAR_ITEM_STYLE_MAP[i][1];
  17997. var newName = BAR_ITEM_STYLE_MAP[i][0];
  17998. if (itemStyle[oldName] != null) {
  17999. itemStyle[newName] = itemStyle[oldName];
  18000. if ("development" !== 'production') {
  18001. deprecateReplaceLog(oldName, newName);
  18002. }
  18003. }
  18004. }
  18005. }
  18006. }
  18007. function compatPieLabel(option) {
  18008. if (!option) {
  18009. return;
  18010. }
  18011. if (option.alignTo === 'edge' && option.margin != null && option.edgeDistance == null) {
  18012. if ("development" !== 'production') {
  18013. deprecateReplaceLog('label.margin', 'label.edgeDistance', 'pie');
  18014. }
  18015. option.edgeDistance = option.margin;
  18016. }
  18017. }
  18018. function compatSunburstState(option) {
  18019. if (!option) {
  18020. return;
  18021. }
  18022. if (option.downplay && !option.blur) {
  18023. option.blur = option.downplay;
  18024. if ("development" !== 'production') {
  18025. deprecateReplaceLog('downplay', 'blur', 'sunburst');
  18026. }
  18027. }
  18028. }
  18029. function compatGraphFocus(option) {
  18030. if (!option) {
  18031. return;
  18032. }
  18033. if (option.focusNodeAdjacency != null) {
  18034. option.emphasis = option.emphasis || {};
  18035. if (option.emphasis.focus == null) {
  18036. if ("development" !== 'production') {
  18037. deprecateReplaceLog('focusNodeAdjacency', 'emphasis: { focus: \'adjacency\'}', 'graph/sankey');
  18038. }
  18039. option.emphasis.focus = 'adjacency';
  18040. }
  18041. }
  18042. }
  18043. function traverseTree(data, cb) {
  18044. if (data) {
  18045. for (var i = 0; i < data.length; i++) {
  18046. cb(data[i]);
  18047. data[i] && traverseTree(data[i].children, cb);
  18048. }
  18049. }
  18050. }
  18051. function globalBackwardCompat(option, isTheme) {
  18052. globalCompatStyle(option, isTheme); // Make sure series array for model initialization.
  18053. option.series = normalizeToArray(option.series);
  18054. each(option.series, function (seriesOpt) {
  18055. if (!isObject(seriesOpt)) {
  18056. return;
  18057. }
  18058. var seriesType = seriesOpt.type;
  18059. if (seriesType === 'line') {
  18060. if (seriesOpt.clipOverflow != null) {
  18061. seriesOpt.clip = seriesOpt.clipOverflow;
  18062. if ("development" !== 'production') {
  18063. deprecateReplaceLog('clipOverflow', 'clip', 'line');
  18064. }
  18065. }
  18066. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18067. if (seriesOpt.clockWise != null) {
  18068. seriesOpt.clockwise = seriesOpt.clockWise;
  18069. if ("development" !== 'production') {
  18070. deprecateReplaceLog('clockWise', 'clockwise');
  18071. }
  18072. }
  18073. compatPieLabel(seriesOpt.label);
  18074. var data = seriesOpt.data;
  18075. if (data && !isTypedArray(data)) {
  18076. for (var i = 0; i < data.length; i++) {
  18077. compatPieLabel(data[i]);
  18078. }
  18079. }
  18080. if (seriesOpt.hoverOffset != null) {
  18081. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18082. if (seriesOpt.emphasis.scaleSize = null) {
  18083. if ("development" !== 'production') {
  18084. deprecateReplaceLog('hoverOffset', 'emphasis.scaleSize');
  18085. }
  18086. seriesOpt.emphasis.scaleSize = seriesOpt.hoverOffset;
  18087. }
  18088. }
  18089. } else if (seriesType === 'gauge') {
  18090. var pointerColor = get(seriesOpt, 'pointer.color');
  18091. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18092. } else if (seriesType === 'bar') {
  18093. compatBarItemStyle(seriesOpt);
  18094. compatBarItemStyle(seriesOpt.backgroundStyle);
  18095. compatBarItemStyle(seriesOpt.emphasis);
  18096. var data = seriesOpt.data;
  18097. if (data && !isTypedArray(data)) {
  18098. for (var i = 0; i < data.length; i++) {
  18099. if (typeof data[i] === 'object') {
  18100. compatBarItemStyle(data[i]);
  18101. compatBarItemStyle(data[i] && data[i].emphasis);
  18102. }
  18103. }
  18104. }
  18105. } else if (seriesType === 'sunburst') {
  18106. var highlightPolicy = seriesOpt.highlightPolicy;
  18107. if (highlightPolicy) {
  18108. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18109. if (!seriesOpt.emphasis.focus) {
  18110. seriesOpt.emphasis.focus = highlightPolicy;
  18111. if ("development" !== 'production') {
  18112. deprecateReplaceLog('highlightPolicy', 'emphasis.focus', 'sunburst');
  18113. }
  18114. }
  18115. }
  18116. compatSunburstState(seriesOpt);
  18117. traverseTree(seriesOpt.data, compatSunburstState);
  18118. } else if (seriesType === 'graph' || seriesType === 'sankey') {
  18119. compatGraphFocus(seriesOpt); // TODO nodes, edges?
  18120. } else if (seriesType === 'map') {
  18121. if (seriesOpt.mapType && !seriesOpt.map) {
  18122. if ("development" !== 'production') {
  18123. deprecateReplaceLog('mapType', 'map', 'map');
  18124. }
  18125. seriesOpt.map = seriesOpt.mapType;
  18126. }
  18127. if (seriesOpt.mapLocation) {
  18128. if ("development" !== 'production') {
  18129. deprecateLog('`mapLocation` is not used anymore.');
  18130. }
  18131. defaults(seriesOpt, seriesOpt.mapLocation);
  18132. }
  18133. }
  18134. if (seriesOpt.hoverAnimation != null) {
  18135. seriesOpt.emphasis = seriesOpt.emphasis || {};
  18136. if (seriesOpt.emphasis && seriesOpt.emphasis.scale == null) {
  18137. if ("development" !== 'production') {
  18138. deprecateReplaceLog('hoverAnimation', 'emphasis.scale');
  18139. }
  18140. seriesOpt.emphasis.scale = seriesOpt.hoverAnimation;
  18141. }
  18142. }
  18143. compatLayoutProperties(seriesOpt);
  18144. }); // dataRange has changed to visualMap
  18145. if (option.dataRange) {
  18146. option.visualMap = option.dataRange;
  18147. }
  18148. each(COMPATITABLE_COMPONENTS, function (componentName) {
  18149. var options = option[componentName];
  18150. if (options) {
  18151. if (!isArray(options)) {
  18152. options = [options];
  18153. }
  18154. each(options, function (option) {
  18155. compatLayoutProperties(option);
  18156. });
  18157. }
  18158. });
  18159. }
  18160. // data processing stage is blocked in stream.
  18161. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18162. // (2) Only register once when import repeatly.
  18163. // Should be executed after series filtered and before stack calculation.
  18164. function dataStack(ecModel) {
  18165. var stackInfoMap = createHashMap();
  18166. ecModel.eachSeries(function (seriesModel) {
  18167. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18168. if (stack) {
  18169. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18170. var data = seriesModel.getData();
  18171. var stackInfo = {
  18172. // Used for calculate axis extent automatically.
  18173. // TODO: Type getCalculationInfo return more specific type?
  18174. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  18175. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  18176. stackedDimension: data.getCalculationInfo('stackedDimension'),
  18177. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  18178. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  18179. data: data,
  18180. seriesModel: seriesModel
  18181. }; // If stacked on axis that do not support data stack.
  18182. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  18183. return;
  18184. }
  18185. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  18186. stackInfoList.push(stackInfo);
  18187. }
  18188. });
  18189. stackInfoMap.each(calculateStack);
  18190. }
  18191. function calculateStack(stackInfoList) {
  18192. each(stackInfoList, function (targetStackInfo, idxInStack) {
  18193. var resultVal = [];
  18194. var resultNaN = [NaN, NaN];
  18195. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  18196. var targetData = targetStackInfo.data;
  18197. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  18198. // depending on legend selection.
  18199. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  18200. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  18201. // should also be NaN, to draw a appropriate belt area.
  18202. if (isNaN(sum)) {
  18203. return resultNaN;
  18204. }
  18205. var byValue;
  18206. var stackedDataRawIndex;
  18207. if (isStackedByIndex) {
  18208. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  18209. } else {
  18210. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  18211. } // If stackOver is NaN, chart view will render point on value start.
  18212. var stackedOver = NaN;
  18213. for (var j = idxInStack - 1; j >= 0; j--) {
  18214. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  18215. if (!isStackedByIndex) {
  18216. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  18217. }
  18218. if (stackedDataRawIndex >= 0) {
  18219. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  18220. if (sum >= 0 && val > 0 || // Positive stack
  18221. sum <= 0 && val < 0 // Negative stack
  18222. ) {
  18223. sum += val;
  18224. stackedOver = val;
  18225. break;
  18226. }
  18227. }
  18228. }
  18229. resultVal[0] = sum;
  18230. resultVal[1] = stackedOver;
  18231. return resultVal;
  18232. });
  18233. targetData.hostModel.setData(newData); // Update for consequent calculation
  18234. targetStackInfo.data = newData;
  18235. });
  18236. }
  18237. var SourceImpl =
  18238. /** @class */
  18239. function () {
  18240. // readonly frozen: boolean;
  18241. function SourceImpl(fields) {
  18242. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  18243. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN; // Visit config
  18244. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  18245. this.startIndex = fields.startIndex || 0;
  18246. this.dimensionsDefine = fields.dimensionsDefine;
  18247. this.dimensionsDetectedCount = fields.dimensionsDetectedCount;
  18248. this.encodeDefine = fields.encodeDefine;
  18249. this.metaRawOption = fields.metaRawOption;
  18250. }
  18251. return SourceImpl;
  18252. }();
  18253. function isSourceInstance(val) {
  18254. return val instanceof SourceImpl;
  18255. }
  18256. function createSource(sourceData, thisMetaRawOption, // can be null. If not provided, auto detect it from `sourceData`.
  18257. sourceFormat, encodeDefine // can be null
  18258. ) {
  18259. sourceFormat = sourceFormat || detectSourceFormat(sourceData);
  18260. var seriesLayoutBy = thisMetaRawOption.seriesLayoutBy;
  18261. var determined = determineSourceDimensions(sourceData, sourceFormat, seriesLayoutBy, thisMetaRawOption.sourceHeader, thisMetaRawOption.dimensions);
  18262. var source = new SourceImpl({
  18263. data: sourceData,
  18264. sourceFormat: sourceFormat,
  18265. seriesLayoutBy: seriesLayoutBy,
  18266. dimensionsDefine: determined.dimensionsDefine,
  18267. startIndex: determined.startIndex,
  18268. dimensionsDetectedCount: determined.dimensionsDetectedCount,
  18269. encodeDefine: makeEncodeDefine(encodeDefine),
  18270. metaRawOption: clone(thisMetaRawOption)
  18271. });
  18272. return source;
  18273. }
  18274. /**
  18275. * Wrap original series data for some compatibility cases.
  18276. */
  18277. function createSourceFromSeriesDataOption(data) {
  18278. return new SourceImpl({
  18279. data: data,
  18280. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL
  18281. });
  18282. }
  18283. /**
  18284. * Clone source but excludes source data.
  18285. */
  18286. function cloneSourceShallow(source) {
  18287. return new SourceImpl({
  18288. data: source.data,
  18289. sourceFormat: source.sourceFormat,
  18290. seriesLayoutBy: source.seriesLayoutBy,
  18291. dimensionsDefine: clone(source.dimensionsDefine),
  18292. startIndex: source.startIndex,
  18293. dimensionsDetectedCount: source.dimensionsDetectedCount,
  18294. encodeDefine: makeEncodeDefine(source.encodeDefine)
  18295. });
  18296. }
  18297. function makeEncodeDefine(encodeDefine) {
  18298. // null means user not specify `series.encode`.
  18299. return encodeDefine ? createHashMap(encodeDefine) : null;
  18300. }
  18301. /**
  18302. * Note: An empty array will be detected as `SOURCE_FORMAT_ARRAY_ROWS`.
  18303. */
  18304. function detectSourceFormat(data) {
  18305. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  18306. if (isTypedArray(data)) {
  18307. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  18308. } else if (isArray(data)) {
  18309. // FIXME Whether tolerate null in top level array?
  18310. if (data.length === 0) {
  18311. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18312. }
  18313. for (var i = 0, len = data.length; i < len; i++) {
  18314. var item = data[i];
  18315. if (item == null) {
  18316. continue;
  18317. } else if (isArray(item)) {
  18318. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  18319. break;
  18320. } else if (isObject(item)) {
  18321. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  18322. break;
  18323. }
  18324. }
  18325. } else if (isObject(data)) {
  18326. for (var key in data) {
  18327. if (hasOwn(data, key) && isArrayLike(data[key])) {
  18328. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  18329. break;
  18330. }
  18331. }
  18332. }
  18333. return sourceFormat;
  18334. }
  18335. /**
  18336. * Determine the source definitions from data standalone dimensions definitions
  18337. * are not specified.
  18338. */
  18339. function determineSourceDimensions(data, sourceFormat, seriesLayoutBy, sourceHeader, // standalone raw dimensions definition, like:
  18340. // {
  18341. // dimensions: ['aa', 'bb', { name: 'cc', type: 'time' }]
  18342. // }
  18343. // in `dataset` or `series`
  18344. dimensionsDefine) {
  18345. var dimensionsDetectedCount;
  18346. var startIndex; // PEDING: could data be null/undefined here?
  18347. // currently, if `dataset.source` not specified, error thrown.
  18348. // if `series.data` not specified, nothing rendered without error thrown.
  18349. // Should test these cases.
  18350. if (!data) {
  18351. return {
  18352. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18353. startIndex: startIndex,
  18354. dimensionsDetectedCount: dimensionsDetectedCount
  18355. };
  18356. }
  18357. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  18358. var dataArrayRows = data; // Rule: Most of the first line are string: it is header.
  18359. // Caution: consider a line with 5 string and 1 number,
  18360. // it still can not be sure it is a head, because the
  18361. // 5 string may be 5 values of category columns.
  18362. if (sourceHeader === 'auto' || sourceHeader == null) {
  18363. arrayRowsTravelFirst(function (val) {
  18364. // '-' is regarded as null/undefined.
  18365. if (val != null && val !== '-') {
  18366. if (isString(val)) {
  18367. startIndex == null && (startIndex = 1);
  18368. } else {
  18369. startIndex = 0;
  18370. }
  18371. } // 10 is an experience number, avoid long loop.
  18372. }, seriesLayoutBy, dataArrayRows, 10);
  18373. } else {
  18374. startIndex = isNumber(sourceHeader) ? sourceHeader : sourceHeader ? 1 : 0;
  18375. }
  18376. if (!dimensionsDefine && startIndex === 1) {
  18377. dimensionsDefine = [];
  18378. arrayRowsTravelFirst(function (val, index) {
  18379. dimensionsDefine[index] = val != null ? val + '' : '';
  18380. }, seriesLayoutBy, dataArrayRows, Infinity);
  18381. }
  18382. dimensionsDetectedCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? dataArrayRows.length : dataArrayRows[0] ? dataArrayRows[0].length : null;
  18383. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  18384. if (!dimensionsDefine) {
  18385. dimensionsDefine = objectRowsCollectDimensions(data);
  18386. }
  18387. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  18388. if (!dimensionsDefine) {
  18389. dimensionsDefine = [];
  18390. each(data, function (colArr, key) {
  18391. dimensionsDefine.push(key);
  18392. });
  18393. }
  18394. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  18395. var value0 = getDataItemValue(data[0]);
  18396. dimensionsDetectedCount = isArray(value0) && value0.length || 1;
  18397. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18398. if ("development" !== 'production') {
  18399. assert(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  18400. }
  18401. }
  18402. return {
  18403. startIndex: startIndex,
  18404. dimensionsDefine: normalizeDimensionsOption(dimensionsDefine),
  18405. dimensionsDetectedCount: dimensionsDetectedCount
  18406. };
  18407. }
  18408. function objectRowsCollectDimensions(data) {
  18409. var firstIndex = 0;
  18410. var obj;
  18411. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  18412. if (obj) {
  18413. var dimensions_1 = [];
  18414. each(obj, function (value, key) {
  18415. dimensions_1.push(key);
  18416. });
  18417. return dimensions_1;
  18418. }
  18419. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  18420. // which is reasonable. But dimension name is duplicated.
  18421. // Returns undefined or an array contains only object without null/undefiend or string.
  18422. function normalizeDimensionsOption(dimensionsDefine) {
  18423. if (!dimensionsDefine) {
  18424. // The meaning of null/undefined is different from empty array.
  18425. return;
  18426. }
  18427. var nameMap = createHashMap();
  18428. return map(dimensionsDefine, function (rawItem, index) {
  18429. rawItem = isObject(rawItem) ? rawItem : {
  18430. name: rawItem
  18431. }; // Other fields will be discarded.
  18432. var item = {
  18433. name: rawItem.name,
  18434. displayName: rawItem.displayName,
  18435. type: rawItem.type
  18436. }; // User can set null in dimensions.
  18437. // We dont auto specify name, othewise a given name may
  18438. // cause it be refered unexpectedly.
  18439. if (item.name == null) {
  18440. return item;
  18441. } // Also consider number form like 2012.
  18442. item.name += ''; // User may also specify displayName.
  18443. // displayName will always exists except user not
  18444. // specified or dim name is not specified or detected.
  18445. // (A auto generated dim name will not be used as
  18446. // displayName).
  18447. if (item.displayName == null) {
  18448. item.displayName = item.name;
  18449. }
  18450. var exist = nameMap.get(item.name);
  18451. if (!exist) {
  18452. nameMap.set(item.name, {
  18453. count: 1
  18454. });
  18455. } else {
  18456. item.name += '-' + exist.count++;
  18457. }
  18458. return item;
  18459. });
  18460. }
  18461. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  18462. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  18463. for (var i = 0; i < data.length && i < maxLoop; i++) {
  18464. cb(data[i] ? data[i][0] : null, i);
  18465. }
  18466. } else {
  18467. var value0 = data[0] || [];
  18468. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  18469. cb(value0[i], i);
  18470. }
  18471. }
  18472. }
  18473. /*
  18474. * Licensed to the Apache Software Foundation (ASF) under one
  18475. * or more contributor license agreements. See the NOTICE file
  18476. * distributed with this work for additional information
  18477. * regarding copyright ownership. The ASF licenses this file
  18478. * to you under the Apache License, Version 2.0 (the
  18479. * "License"); you may not use this file except in compliance
  18480. * with the License. You may obtain a copy of the License at
  18481. *
  18482. * http://www.apache.org/licenses/LICENSE-2.0
  18483. *
  18484. * Unless required by applicable law or agreed to in writing,
  18485. * software distributed under the License is distributed on an
  18486. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18487. * KIND, either express or implied. See the License for the
  18488. * specific language governing permissions and limitations
  18489. * under the License.
  18490. */
  18491. /**
  18492. * AUTO-GENERATED FILE. DO NOT MODIFY.
  18493. */
  18494. /*
  18495. * Licensed to the Apache Software Foundation (ASF) under one
  18496. * or more contributor license agreements. See the NOTICE file
  18497. * distributed with this work for additional information
  18498. * regarding copyright ownership. The ASF licenses this file
  18499. * to you under the Apache License, Version 2.0 (the
  18500. * "License"); you may not use this file except in compliance
  18501. * with the License. You may obtain a copy of the License at
  18502. *
  18503. * http://www.apache.org/licenses/LICENSE-2.0
  18504. *
  18505. * Unless required by applicable law or agreed to in writing,
  18506. * software distributed under the License is distributed on an
  18507. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18508. * KIND, either express or implied. See the License for the
  18509. * specific language governing permissions and limitations
  18510. * under the License.
  18511. */
  18512. var _a, _b, _c; // TODO
  18513. var providerMethods;
  18514. var mountMethods;
  18515. /**
  18516. * If normal array used, mutable chunk size is supported.
  18517. * If typed array used, chunk size must be fixed.
  18518. */
  18519. var DefaultDataProvider =
  18520. /** @class */
  18521. function () {
  18522. function DefaultDataProvider(sourceParam, dimSize) {
  18523. // let source: Source;
  18524. var source = !isSourceInstance(sourceParam) ? createSourceFromSeriesDataOption(sourceParam) : sourceParam; // declare source is Source;
  18525. this._source = source;
  18526. var data = this._data = source.data; // Typed array. TODO IE10+?
  18527. if (source.sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18528. if ("development" !== 'production') {
  18529. if (dimSize == null) {
  18530. throw new Error('Typed array data must specify dimension size');
  18531. }
  18532. }
  18533. this._offset = 0;
  18534. this._dimSize = dimSize;
  18535. this._data = data;
  18536. }
  18537. mountMethods(this, data, source);
  18538. }
  18539. DefaultDataProvider.prototype.getSource = function () {
  18540. return this._source;
  18541. };
  18542. DefaultDataProvider.prototype.count = function () {
  18543. return 0;
  18544. };
  18545. DefaultDataProvider.prototype.getItem = function (idx, out) {
  18546. return;
  18547. };
  18548. DefaultDataProvider.prototype.appendData = function (newData) {};
  18549. DefaultDataProvider.prototype.clean = function () {};
  18550. DefaultDataProvider.protoInitialize = function () {
  18551. // PENDING: To avoid potential incompat (e.g., prototype
  18552. // is visited somewhere), still init them on prototype.
  18553. var proto = DefaultDataProvider.prototype;
  18554. proto.pure = false;
  18555. proto.persistent = true;
  18556. }();
  18557. DefaultDataProvider.internalField = function () {
  18558. var _a;
  18559. mountMethods = function (provider, data, source) {
  18560. var sourceFormat = source.sourceFormat;
  18561. var seriesLayoutBy = source.seriesLayoutBy;
  18562. var startIndex = source.startIndex;
  18563. var dimsDef = source.dimensionsDefine;
  18564. var methods = providerMethods[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18565. if ("development" !== 'production') {
  18566. assert(methods, 'Invalide sourceFormat: ' + sourceFormat);
  18567. }
  18568. extend(provider, methods);
  18569. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  18570. provider.getItem = getItemForTypedArray;
  18571. provider.count = countForTypedArray;
  18572. provider.fillStorage = fillStorageForTypedArray;
  18573. } else {
  18574. var rawItemGetter = getRawSourceItemGetter(sourceFormat, seriesLayoutBy);
  18575. provider.getItem = bind(rawItemGetter, null, data, startIndex, dimsDef);
  18576. var rawCounter = getRawSourceDataCounter(sourceFormat, seriesLayoutBy);
  18577. provider.count = bind(rawCounter, null, data, startIndex, dimsDef);
  18578. }
  18579. };
  18580. var getItemForTypedArray = function (idx, out) {
  18581. idx = idx - this._offset;
  18582. out = out || [];
  18583. var data = this._data;
  18584. var dimSize = this._dimSize;
  18585. var offset = dimSize * idx;
  18586. for (var i = 0; i < dimSize; i++) {
  18587. out[i] = data[offset + i];
  18588. }
  18589. return out;
  18590. };
  18591. var fillStorageForTypedArray = function (start, end, storage, extent) {
  18592. var data = this._data;
  18593. var dimSize = this._dimSize;
  18594. for (var dim = 0; dim < dimSize; dim++) {
  18595. var dimExtent = extent[dim];
  18596. var min = dimExtent[0] == null ? Infinity : dimExtent[0];
  18597. var max = dimExtent[1] == null ? -Infinity : dimExtent[1];
  18598. var count = end - start;
  18599. var arr = storage[dim];
  18600. for (var i = 0; i < count; i++) {
  18601. // appendData with TypedArray will always do replace in provider.
  18602. var val = data[i * dimSize + dim];
  18603. arr[start + i] = val;
  18604. val < min && (min = val);
  18605. val > max && (max = val);
  18606. }
  18607. dimExtent[0] = min;
  18608. dimExtent[1] = max;
  18609. }
  18610. };
  18611. var countForTypedArray = function () {
  18612. return this._data ? this._data.length / this._dimSize : 0;
  18613. };
  18614. providerMethods = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = {
  18615. pure: true,
  18616. appendData: appendDataSimply
  18617. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = {
  18618. pure: true,
  18619. appendData: function () {
  18620. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  18621. }
  18622. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = {
  18623. pure: true,
  18624. appendData: appendDataSimply
  18625. }, _a[SOURCE_FORMAT_KEYED_COLUMNS] = {
  18626. pure: true,
  18627. appendData: function (newData) {
  18628. var data = this._data;
  18629. each(newData, function (newCol, key) {
  18630. var oldCol = data[key] || (data[key] = []);
  18631. for (var i = 0; i < (newCol || []).length; i++) {
  18632. oldCol.push(newCol[i]);
  18633. }
  18634. });
  18635. }
  18636. }, _a[SOURCE_FORMAT_ORIGINAL] = {
  18637. appendData: appendDataSimply
  18638. }, _a[SOURCE_FORMAT_TYPED_ARRAY] = {
  18639. persistent: false,
  18640. pure: true,
  18641. appendData: function (newData) {
  18642. if ("development" !== 'production') {
  18643. assert(isTypedArray(newData), 'Added data must be TypedArray if data in initialization is TypedArray');
  18644. }
  18645. this._data = newData;
  18646. },
  18647. // Clean self if data is already used.
  18648. clean: function () {
  18649. // PENDING
  18650. this._offset += this.count();
  18651. this._data = null;
  18652. }
  18653. }, _a);
  18654. function appendDataSimply(newData) {
  18655. for (var i = 0; i < newData.length; i++) {
  18656. this._data.push(newData[i]);
  18657. }
  18658. }
  18659. }();
  18660. return DefaultDataProvider;
  18661. }();
  18662. var getItemSimply = function (rawData, startIndex, dimsDef, idx) {
  18663. return rawData[idx];
  18664. };
  18665. var rawSourceItemGetterMap = (_a = {}, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef, idx) {
  18666. return rawData[idx + startIndex];
  18667. }, _a[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef, idx) {
  18668. idx += startIndex;
  18669. var item = [];
  18670. var data = rawData;
  18671. for (var i = 0; i < data.length; i++) {
  18672. var row = data[i];
  18673. item.push(row ? row[idx] : null);
  18674. }
  18675. return item;
  18676. }, _a[SOURCE_FORMAT_OBJECT_ROWS] = getItemSimply, _a[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef, idx) {
  18677. var item = [];
  18678. for (var i = 0; i < dimsDef.length; i++) {
  18679. var dimName = dimsDef[i].name;
  18680. if ("development" !== 'production') {
  18681. if (dimName == null) {
  18682. throw new Error();
  18683. }
  18684. }
  18685. var col = rawData[dimName];
  18686. item.push(col ? col[idx] : null);
  18687. }
  18688. return item;
  18689. }, _a[SOURCE_FORMAT_ORIGINAL] = getItemSimply, _a);
  18690. function getRawSourceItemGetter(sourceFormat, seriesLayoutBy) {
  18691. var method = rawSourceItemGetterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18692. if ("development" !== 'production') {
  18693. assert(method, 'Do not suppport get item on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18694. }
  18695. return method;
  18696. }
  18697. var countSimply = function (rawData, startIndex, dimsDef) {
  18698. return rawData.length;
  18699. };
  18700. var rawSourceDataCounterMap = (_b = {}, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_COLUMN] = function (rawData, startIndex, dimsDef) {
  18701. return Math.max(0, rawData.length - startIndex);
  18702. }, _b[SOURCE_FORMAT_ARRAY_ROWS + '_' + SERIES_LAYOUT_BY_ROW] = function (rawData, startIndex, dimsDef) {
  18703. var row = rawData[0];
  18704. return row ? Math.max(0, row.length - startIndex) : 0;
  18705. }, _b[SOURCE_FORMAT_OBJECT_ROWS] = countSimply, _b[SOURCE_FORMAT_KEYED_COLUMNS] = function (rawData, startIndex, dimsDef) {
  18706. var dimName = dimsDef[0].name;
  18707. if ("development" !== 'production') {
  18708. if (dimName == null) {
  18709. throw new Error();
  18710. }
  18711. }
  18712. var col = rawData[dimName];
  18713. return col ? col.length : 0;
  18714. }, _b[SOURCE_FORMAT_ORIGINAL] = countSimply, _b);
  18715. function getRawSourceDataCounter(sourceFormat, seriesLayoutBy) {
  18716. var method = rawSourceDataCounterMap[getMethodMapKey(sourceFormat, seriesLayoutBy)];
  18717. if ("development" !== 'production') {
  18718. assert(method, 'Do not suppport count on "' + sourceFormat + '", "' + seriesLayoutBy + '".');
  18719. }
  18720. return method;
  18721. }
  18722. var getRawValueSimply = function (dataItem, dimIndex, dimName) {
  18723. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  18724. };
  18725. var rawSourceValueGetterMap = (_c = {}, _c[SOURCE_FORMAT_ARRAY_ROWS] = getRawValueSimply, _c[SOURCE_FORMAT_OBJECT_ROWS] = function (dataItem, dimIndex, dimName) {
  18726. return dimIndex != null ? dataItem[dimName] : dataItem;
  18727. }, _c[SOURCE_FORMAT_KEYED_COLUMNS] = getRawValueSimply, _c[SOURCE_FORMAT_ORIGINAL] = function (dataItem, dimIndex, dimName) {
  18728. // FIXME: In some case (markpoint in geo (geo-map.html)),
  18729. // dataItem is {coord: [...]}
  18730. var value = getDataItemValue(dataItem);
  18731. return dimIndex == null || !(value instanceof Array) ? value : value[dimIndex];
  18732. }, _c[SOURCE_FORMAT_TYPED_ARRAY] = getRawValueSimply, _c);
  18733. function getRawSourceValueGetter(sourceFormat) {
  18734. var method = rawSourceValueGetterMap[sourceFormat];
  18735. if ("development" !== 'production') {
  18736. assert(method, 'Do not suppport get value on "' + sourceFormat + '".');
  18737. }
  18738. return method;
  18739. }
  18740. function getMethodMapKey(sourceFormat, seriesLayoutBy) {
  18741. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + seriesLayoutBy : sourceFormat;
  18742. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  18743. // Consider persistent.
  18744. // Caution: why use raw value to display on label or tooltip?
  18745. // A reason is to avoid format. For example time value we do not know
  18746. // how to format is expected. More over, if stack is used, calculated
  18747. // value may be 0.91000000001, which have brings trouble to display.
  18748. // TODO: consider how to treat null/undefined/NaN when display?
  18749. function retrieveRawValue(data, dataIndex, dim // If dimIndex is null/undefined, return OptionDataItem.
  18750. // Otherwise, return OptionDataValue.
  18751. ) {
  18752. if (!data) {
  18753. return;
  18754. } // Consider data may be not persistent.
  18755. var dataItem = data.getRawDataItem(dataIndex);
  18756. if (dataItem == null) {
  18757. return;
  18758. }
  18759. var sourceFormat = data.getProvider().getSource().sourceFormat;
  18760. var dimName;
  18761. var dimIndex;
  18762. var dimInfo = data.getDimensionInfo(dim);
  18763. if (dimInfo) {
  18764. dimName = dimInfo.name;
  18765. dimIndex = dimInfo.index;
  18766. }
  18767. return getRawSourceValueGetter(sourceFormat)(dataItem, dimIndex, dimName);
  18768. }
  18769. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  18770. var DataFormatMixin =
  18771. /** @class */
  18772. function () {
  18773. function DataFormatMixin() {}
  18774. /**
  18775. * Get params for formatter
  18776. */
  18777. DataFormatMixin.prototype.getDataParams = function (dataIndex, dataType) {
  18778. var data = this.getData(dataType);
  18779. var rawValue = this.getRawValue(dataIndex, dataType);
  18780. var rawDataIndex = data.getRawIndex(dataIndex);
  18781. var name = data.getName(dataIndex);
  18782. var itemOpt = data.getRawDataItem(dataIndex);
  18783. var style = data.getItemVisual(dataIndex, 'style');
  18784. var color = style && style[data.getItemVisual(dataIndex, 'drawType') || 'fill'];
  18785. var borderColor = style && style.stroke;
  18786. var mainType = this.mainType;
  18787. var isSeries = mainType === 'series';
  18788. var userOutput = data.userOutput;
  18789. return {
  18790. componentType: mainType,
  18791. componentSubType: this.subType,
  18792. componentIndex: this.componentIndex,
  18793. seriesType: isSeries ? this.subType : null,
  18794. seriesIndex: this.seriesIndex,
  18795. seriesId: isSeries ? this.id : null,
  18796. seriesName: isSeries ? this.name : null,
  18797. name: name,
  18798. dataIndex: rawDataIndex,
  18799. data: itemOpt,
  18800. dataType: dataType,
  18801. value: rawValue,
  18802. color: color,
  18803. borderColor: borderColor,
  18804. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  18805. encode: userOutput ? userOutput.encode : null,
  18806. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  18807. $vars: ['seriesName', 'name', 'value']
  18808. };
  18809. };
  18810. /**
  18811. * Format label
  18812. * @param dataIndex
  18813. * @param status 'normal' by default
  18814. * @param dataType
  18815. * @param labelDimIndex Only used in some chart that
  18816. * use formatter in different dimensions, like radar.
  18817. * @param formatter Formatter given outside.
  18818. * @return return null/undefined if no formatter
  18819. */
  18820. DataFormatMixin.prototype.getFormattedLabel = function (dataIndex, status, dataType, labelDimIndex, formatter, extendParams) {
  18821. status = status || 'normal';
  18822. var data = this.getData(dataType);
  18823. var params = this.getDataParams(dataIndex, dataType);
  18824. if (extendParams) {
  18825. params.value = extendParams.interpolatedValue;
  18826. }
  18827. if (labelDimIndex != null && isArray(params.value)) {
  18828. params.value = params.value[labelDimIndex];
  18829. }
  18830. if (!formatter) {
  18831. var itemModel = data.getItemModel(dataIndex); // @ts-ignore
  18832. formatter = itemModel.get(status === 'normal' ? ['label', 'formatter'] : [status, 'label', 'formatter']);
  18833. }
  18834. if (typeof formatter === 'function') {
  18835. params.status = status;
  18836. params.dimensionIndex = labelDimIndex;
  18837. return formatter(params);
  18838. } else if (typeof formatter === 'string') {
  18839. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  18840. // Do not support '}' in dim name util have to.
  18841. return str.replace(DIMENSION_LABEL_REG, function (origin, dimStr) {
  18842. var len = dimStr.length;
  18843. var dimLoose = dimStr.charAt(0) === '[' && dimStr.charAt(len - 1) === ']' ? +dimStr.slice(1, len - 1) // Also support: '[]' => 0
  18844. : dimStr;
  18845. var val = retrieveRawValue(data, dataIndex, dimLoose);
  18846. if (extendParams && isArray(extendParams.interpolatedValue)) {
  18847. var dimInfo = data.getDimensionInfo(dimLoose);
  18848. if (dimInfo) {
  18849. val = extendParams.interpolatedValue[dimInfo.index];
  18850. }
  18851. }
  18852. return val != null ? val + '' : '';
  18853. });
  18854. }
  18855. };
  18856. /**
  18857. * Get raw value in option
  18858. */
  18859. DataFormatMixin.prototype.getRawValue = function (idx, dataType) {
  18860. return retrieveRawValue(this.getData(dataType), idx);
  18861. };
  18862. /**
  18863. * Should be implemented.
  18864. * @param {number} dataIndex
  18865. * @param {boolean} [multipleSeries=false]
  18866. * @param {string} [dataType]
  18867. */
  18868. DataFormatMixin.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  18869. // Empty function
  18870. return;
  18871. };
  18872. return DataFormatMixin;
  18873. }();
  18874. // but guess little chance has been used outside. Do we need to backward
  18875. // compat it?
  18876. // type TooltipFormatResultLegacyObject = {
  18877. // // `html` means the markup language text, either in 'html' or 'richText'.
  18878. // // The name `html` is not appropriate becuase in 'richText' it is not a HTML
  18879. // // string. But still support it for backward compat.
  18880. // html: string;
  18881. // markers: Dictionary<ColorString>;
  18882. // };
  18883. /**
  18884. * For backward compat, normalize the return from `formatTooltip`.
  18885. */
  18886. function normalizeTooltipFormatResult(result // markersExisting: Dictionary<ColorString>
  18887. ) {
  18888. var markupText; // let markers: Dictionary<ColorString>;
  18889. var markupFragment;
  18890. if (isObject(result)) {
  18891. if (result.type) {
  18892. markupFragment = result;
  18893. } else {
  18894. if ("development" !== 'production') {
  18895. console.warn('The return type of `formatTooltip` is not supported: ' + makePrintable(result));
  18896. }
  18897. } // else {
  18898. // markupText = (result as TooltipFormatResultLegacyObject).html;
  18899. // markers = (result as TooltipFormatResultLegacyObject).markers;
  18900. // if (markersExisting) {
  18901. // markers = zrUtil.merge(markersExisting, markers);
  18902. // }
  18903. // }
  18904. } else {
  18905. markupText = result;
  18906. }
  18907. return {
  18908. markupText: markupText,
  18909. // markers: markers || markersExisting,
  18910. markupFragment: markupFragment
  18911. };
  18912. }
  18913. /**
  18914. * @param {Object} define
  18915. * @return See the return of `createTask`.
  18916. */
  18917. function createTask(define) {
  18918. return new Task(define);
  18919. }
  18920. var Task =
  18921. /** @class */
  18922. function () {
  18923. function Task(define) {
  18924. define = define || {};
  18925. this._reset = define.reset;
  18926. this._plan = define.plan;
  18927. this._count = define.count;
  18928. this._onDirty = define.onDirty;
  18929. this._dirty = true;
  18930. }
  18931. /**
  18932. * @param step Specified step.
  18933. * @param skip Skip customer perform call.
  18934. * @param modBy Sampling window size.
  18935. * @param modDataCount Sampling count.
  18936. * @return whether unfinished.
  18937. */
  18938. Task.prototype.perform = function (performArgs) {
  18939. var upTask = this._upstream;
  18940. var skip = performArgs && performArgs.skip; // TODO some refactor.
  18941. // Pull data. Must pull data each time, because context.data
  18942. // may be updated by Series.setData.
  18943. if (this._dirty && upTask) {
  18944. var context = this.context;
  18945. context.data = context.outputData = upTask.context.outputData;
  18946. }
  18947. if (this.__pipeline) {
  18948. this.__pipeline.currentTask = this;
  18949. }
  18950. var planResult;
  18951. if (this._plan && !skip) {
  18952. planResult = this._plan(this.context);
  18953. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  18954. // elements uniformed distributed when progress, especially when moving or zooming.
  18955. var lastModBy = normalizeModBy(this._modBy);
  18956. var lastModDataCount = this._modDataCount || 0;
  18957. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  18958. var modDataCount = performArgs && performArgs.modDataCount || 0;
  18959. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  18960. planResult = 'reset';
  18961. }
  18962. function normalizeModBy(val) {
  18963. !(val >= 1) && (val = 1); // jshint ignore:line
  18964. return val;
  18965. }
  18966. var forceFirstProgress;
  18967. if (this._dirty || planResult === 'reset') {
  18968. this._dirty = false;
  18969. forceFirstProgress = this._doReset(skip);
  18970. }
  18971. this._modBy = modBy;
  18972. this._modDataCount = modDataCount;
  18973. var step = performArgs && performArgs.step;
  18974. if (upTask) {
  18975. if ("development" !== 'production') {
  18976. assert(upTask._outputDueEnd != null);
  18977. }
  18978. this._dueEnd = upTask._outputDueEnd;
  18979. } // DataTask or overallTask
  18980. else {
  18981. if ("development" !== 'production') {
  18982. assert(!this._progress || this._count);
  18983. }
  18984. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  18985. } // Note: Stubs, that its host overall task let it has progress, has progress.
  18986. // If no progress, pass index from upstream to downstream each time plan called.
  18987. if (this._progress) {
  18988. var start = this._dueIndex;
  18989. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  18990. if (!skip && (forceFirstProgress || start < end)) {
  18991. var progress = this._progress;
  18992. if (isArray(progress)) {
  18993. for (var i = 0; i < progress.length; i++) {
  18994. this._doProgress(progress[i], start, end, modBy, modDataCount);
  18995. }
  18996. } else {
  18997. this._doProgress(progress, start, end, modBy, modDataCount);
  18998. }
  18999. }
  19000. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19001. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19002. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19003. if ("development" !== 'production') {
  19004. // ??? Can not rollback.
  19005. assert(outputDueEnd >= this._outputDueEnd);
  19006. }
  19007. this._outputDueEnd = outputDueEnd;
  19008. } else {
  19009. // (1) Some overall task has no progress.
  19010. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19011. // This should always be performed so it can be passed to downstream.
  19012. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19013. }
  19014. return this.unfinished();
  19015. };
  19016. Task.prototype.dirty = function () {
  19017. this._dirty = true;
  19018. this._onDirty && this._onDirty(this.context);
  19019. };
  19020. Task.prototype._doProgress = function (progress, start, end, modBy, modDataCount) {
  19021. iterator.reset(start, end, modBy, modDataCount);
  19022. this._callingProgress = progress;
  19023. this._callingProgress({
  19024. start: start,
  19025. end: end,
  19026. count: end - start,
  19027. next: iterator.next
  19028. }, this.context);
  19029. };
  19030. Task.prototype._doReset = function (skip) {
  19031. this._dueIndex = this._outputDueEnd = this._dueEnd = 0;
  19032. this._settedOutputEnd = null;
  19033. var progress;
  19034. var forceFirstProgress;
  19035. if (!skip && this._reset) {
  19036. progress = this._reset(this.context);
  19037. if (progress && progress.progress) {
  19038. forceFirstProgress = progress.forceFirstProgress;
  19039. progress = progress.progress;
  19040. } // To simplify no progress checking, array must has item.
  19041. if (isArray(progress) && !progress.length) {
  19042. progress = null;
  19043. }
  19044. }
  19045. this._progress = progress;
  19046. this._modBy = this._modDataCount = null;
  19047. var downstream = this._downstream;
  19048. downstream && downstream.dirty();
  19049. return forceFirstProgress;
  19050. };
  19051. Task.prototype.unfinished = function () {
  19052. return this._progress && this._dueIndex < this._dueEnd;
  19053. };
  19054. /**
  19055. * @param downTask The downstream task.
  19056. * @return The downstream task.
  19057. */
  19058. Task.prototype.pipe = function (downTask) {
  19059. if ("development" !== 'production') {
  19060. assert(downTask && !downTask._disposed && downTask !== this);
  19061. } // If already downstream, do not dirty downTask.
  19062. if (this._downstream !== downTask || this._dirty) {
  19063. this._downstream = downTask;
  19064. downTask._upstream = this;
  19065. downTask.dirty();
  19066. }
  19067. };
  19068. Task.prototype.dispose = function () {
  19069. if (this._disposed) {
  19070. return;
  19071. }
  19072. this._upstream && (this._upstream._downstream = null);
  19073. this._downstream && (this._downstream._upstream = null);
  19074. this._dirty = false;
  19075. this._disposed = true;
  19076. };
  19077. Task.prototype.getUpstream = function () {
  19078. return this._upstream;
  19079. };
  19080. Task.prototype.getDownstream = function () {
  19081. return this._downstream;
  19082. };
  19083. Task.prototype.setOutputEnd = function (end) {
  19084. // This only happend in dataTask, dataZoom, map, currently.
  19085. // where dataZoom do not set end each time, but only set
  19086. // when reset. So we should record the setted end, in case
  19087. // that the stub of dataZoom perform again and earse the
  19088. // setted end by upstream.
  19089. this._outputDueEnd = this._settedOutputEnd = end;
  19090. };
  19091. return Task;
  19092. }();
  19093. var iterator = function () {
  19094. var end;
  19095. var current;
  19096. var modBy;
  19097. var modDataCount;
  19098. var winCount;
  19099. var it = {
  19100. reset: function (s, e, sStep, sCount) {
  19101. current = s;
  19102. end = e;
  19103. modBy = sStep;
  19104. modDataCount = sCount;
  19105. winCount = Math.ceil(modDataCount / modBy);
  19106. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19107. }
  19108. };
  19109. return it;
  19110. function sequentialNext() {
  19111. return current < end ? current++ : null;
  19112. }
  19113. function modNext() {
  19114. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19115. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19116. // Use normal linear rendering mode.
  19117. : current;
  19118. current++;
  19119. return result;
  19120. }
  19121. }(); ///////////////////////////////////////////////////////////
  19122. // For stream debug (Should be commented out after used!)
  19123. // @usage: printTask(this, 'begin');
  19124. // @usage: printTask(this, null, {someExtraProp});
  19125. // @usage: Use `__idxInPipeline` as conditional breakpiont.
  19126. //
  19127. // window.printTask = function (task: any, prefix: string, extra: { [key: string]: unknown }): void {
  19128. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19129. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19130. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19131. // let props = [];
  19132. // if (task.__pipeline) {
  19133. // let val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19134. // props.push({text: '__idxInPipeline/total', value: val});
  19135. // } else {
  19136. // let stubCount = 0;
  19137. // task.agentStubMap.each(() => stubCount++);
  19138. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19139. // }
  19140. // props.push({text: 'uid', value: task.uidDebug});
  19141. // if (task.__pipeline) {
  19142. // props.push({text: 'pipelineId', value: task.__pipeline.id});
  19143. // task.agent && props.push(
  19144. // {text: 'stubFor', value: task.agent.uidDebug}
  19145. // );
  19146. // }
  19147. // props.push(
  19148. // {text: 'dirty', value: task._dirty},
  19149. // {text: 'dueIndex', value: task._dueIndex},
  19150. // {text: 'dueEnd', value: task._dueEnd},
  19151. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19152. // );
  19153. // if (extra) {
  19154. // Object.keys(extra).forEach(key => {
  19155. // props.push({text: key, value: extra[key]});
  19156. // });
  19157. // }
  19158. // let args = ['color: blue'];
  19159. // let msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19160. // args.push('color: green', 'color: red'),
  19161. // `${item.text}: %c${item.value}`
  19162. // )).join('%c, ');
  19163. // console.log.apply(console, [msg].concat(args));
  19164. // // console.log(this);
  19165. // };
  19166. // window.printPipeline = function (task: any, prefix: string) {
  19167. // const pipeline = task.__pipeline;
  19168. // let currTask = pipeline.head;
  19169. // while (currTask) {
  19170. // window.printTask(currTask, prefix);
  19171. // currTask = currTask._downstream;
  19172. // }
  19173. // };
  19174. // window.showChain = function (chainHeadTask) {
  19175. // var chain = [];
  19176. // var task = chainHeadTask;
  19177. // while (task) {
  19178. // chain.push({
  19179. // task: task,
  19180. // up: task._upstream,
  19181. // down: task._downstream,
  19182. // idxInPipeline: task.__idxInPipeline
  19183. // });
  19184. // task = task._downstream;
  19185. // }
  19186. // return chain;
  19187. // };
  19188. // window.findTaskInChain = function (task, chainHeadTask) {
  19189. // let chain = window.showChain(chainHeadTask);
  19190. // let result = [];
  19191. // for (let i = 0; i < chain.length; i++) {
  19192. // let chainItem = chain[i];
  19193. // if (chainItem.task === task) {
  19194. // result.push(i);
  19195. // }
  19196. // }
  19197. // return result;
  19198. // };
  19199. // window.printChainAEachInChainB = function (chainHeadTaskA, chainHeadTaskB) {
  19200. // let chainA = window.showChain(chainHeadTaskA);
  19201. // for (let i = 0; i < chainA.length; i++) {
  19202. // console.log('chainAIdx:', i, 'inChainB:', window.findTaskInChain(chainA[i].task, chainHeadTaskB));
  19203. // }
  19204. // };
  19205. /**
  19206. * Convert raw the value in to inner value in List.
  19207. *
  19208. * [Performance sensitive]
  19209. *
  19210. * [Caution]: this is the key logic of user value parser.
  19211. * For backward compatibiliy, do not modify it until have to!
  19212. */
  19213. function parseDataValue(value, // For high performance, do not omit the second param.
  19214. opt) {
  19215. // Performance sensitive.
  19216. var dimType = opt && opt.type;
  19217. if (dimType === 'ordinal') {
  19218. // If given value is a category string
  19219. var ordinalMeta = opt && opt.ordinalMeta;
  19220. return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value;
  19221. }
  19222. if (dimType === 'time' // spead up when using timestamp
  19223. && typeof value !== 'number' && value != null && value !== '-') {
  19224. value = +parseDate(value);
  19225. } // dimType defaults 'number'.
  19226. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19227. // parse to NaN.
  19228. // number-like string (like ' 123 ') can be converted to a number.
  19229. // where null/undefined or other string will be converted to NaN.
  19230. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19231. // If object, also parse to NaN
  19232. : +value;
  19233. }
  19234. var valueParserMap = createHashMap({
  19235. 'number': function (val) {
  19236. // Do not use `numericToNumber` here. We have by defualt `numericToNumber`.
  19237. // Here the number parser can have loose rule:
  19238. // enable to cut suffix: "120px" => 120, "14%" => 14.
  19239. return parseFloat(val);
  19240. },
  19241. 'time': function (val) {
  19242. // return timestamp.
  19243. return +parseDate(val);
  19244. },
  19245. 'trim': function (val) {
  19246. return typeof val === 'string' ? trim(val) : val;
  19247. }
  19248. });
  19249. function getRawValueParser(type) {
  19250. return valueParserMap.get(type);
  19251. }
  19252. var ORDER_COMPARISON_OP_MAP = {
  19253. lt: function (lval, rval) {
  19254. return lval < rval;
  19255. },
  19256. lte: function (lval, rval) {
  19257. return lval <= rval;
  19258. },
  19259. gt: function (lval, rval) {
  19260. return lval > rval;
  19261. },
  19262. gte: function (lval, rval) {
  19263. return lval >= rval;
  19264. }
  19265. };
  19266. var FilterOrderComparator =
  19267. /** @class */
  19268. function () {
  19269. function FilterOrderComparator(op, rval) {
  19270. if (typeof rval !== 'number') {
  19271. var errMsg = '';
  19272. if ("development" !== 'production') {
  19273. errMsg = 'rvalue of "<", ">", "<=", ">=" can only be number in filter.';
  19274. }
  19275. throwError(errMsg);
  19276. }
  19277. this._opFn = ORDER_COMPARISON_OP_MAP[op];
  19278. this._rvalFloat = numericToNumber(rval);
  19279. } // Performance sensitive.
  19280. FilterOrderComparator.prototype.evaluate = function (lval) {
  19281. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19282. return typeof lval === 'number' ? this._opFn(lval, this._rvalFloat) : this._opFn(numericToNumber(lval), this._rvalFloat);
  19283. };
  19284. return FilterOrderComparator;
  19285. }();
  19286. var SortOrderComparator =
  19287. /** @class */
  19288. function () {
  19289. /**
  19290. * @param order by defualt: 'asc'
  19291. * @param incomparable by defualt: Always on the tail.
  19292. * That is, if 'asc' => 'max', if 'desc' => 'min'
  19293. * See the definition of "incomparable" in [SORT_COMPARISON_RULE]
  19294. */
  19295. function SortOrderComparator(order, incomparable) {
  19296. var isDesc = order === 'desc';
  19297. this._resultLT = isDesc ? 1 : -1;
  19298. if (incomparable == null) {
  19299. incomparable = isDesc ? 'min' : 'max';
  19300. }
  19301. this._incomparable = incomparable === 'min' ? -Infinity : Infinity;
  19302. } // See [SORT_COMPARISON_RULE].
  19303. // Performance sensitive.
  19304. SortOrderComparator.prototype.evaluate = function (lval, rval) {
  19305. // Most cases is 'number', and typeof maybe 10 times faseter than parseFloat.
  19306. var lvalTypeof = typeof lval;
  19307. var rvalTypeof = typeof rval;
  19308. var lvalFloat = lvalTypeof === 'number' ? lval : numericToNumber(lval);
  19309. var rvalFloat = rvalTypeof === 'number' ? rval : numericToNumber(rval);
  19310. var lvalNotNumeric = isNaN(lvalFloat);
  19311. var rvalNotNumeric = isNaN(rvalFloat);
  19312. if (lvalNotNumeric) {
  19313. lvalFloat = this._incomparable;
  19314. }
  19315. if (rvalNotNumeric) {
  19316. rvalFloat = this._incomparable;
  19317. }
  19318. if (lvalNotNumeric && rvalNotNumeric) {
  19319. var lvalIsStr = lvalTypeof === 'string';
  19320. var rvalIsStr = rvalTypeof === 'string';
  19321. if (lvalIsStr) {
  19322. lvalFloat = rvalIsStr ? lval : 0;
  19323. }
  19324. if (rvalIsStr) {
  19325. rvalFloat = lvalIsStr ? rval : 0;
  19326. }
  19327. }
  19328. return lvalFloat < rvalFloat ? this._resultLT : lvalFloat > rvalFloat ? -this._resultLT : 0;
  19329. };
  19330. return SortOrderComparator;
  19331. }();
  19332. var FilterEqualityComparator =
  19333. /** @class */
  19334. function () {
  19335. function FilterEqualityComparator(isEq, rval) {
  19336. this._rval = rval;
  19337. this._isEQ = isEq;
  19338. this._rvalTypeof = typeof rval;
  19339. this._rvalFloat = numericToNumber(rval);
  19340. } // Performance sensitive.
  19341. FilterEqualityComparator.prototype.evaluate = function (lval) {
  19342. var eqResult = lval === this._rval;
  19343. if (!eqResult) {
  19344. var lvalTypeof = typeof lval;
  19345. if (lvalTypeof !== this._rvalTypeof && (lvalTypeof === 'number' || this._rvalTypeof === 'number')) {
  19346. eqResult = numericToNumber(lval) === this._rvalFloat;
  19347. }
  19348. }
  19349. return this._isEQ ? eqResult : !eqResult;
  19350. };
  19351. return FilterEqualityComparator;
  19352. }();
  19353. /**
  19354. * [FILTER_COMPARISON_RULE]
  19355. * `lt`|`lte`|`gt`|`gte`:
  19356. * + rval must be a number. And lval will be converted to number (`numericToNumber`) to compare.
  19357. * `eq`:
  19358. * + If same type, compare with `===`.
  19359. * + If there is one number, convert to number (`numericToNumber`) to compare.
  19360. * + Else return `false`.
  19361. * `ne`:
  19362. * + Not `eq`.
  19363. *
  19364. *
  19365. * [SORT_COMPARISON_RULE]
  19366. * All the values are grouped into three categories:
  19367. * + "numeric" (number and numeric string)
  19368. * + "non-numeric-string" (string that excluding numeric string)
  19369. * + "others"
  19370. * "numeric" vs "numeric": values are ordered by number order.
  19371. * "non-numeric-string" vs "non-numeric-string": values are ordered by ES spec (#sec-abstract-relational-comparison).
  19372. * "others" vs "others": do not change order (always return 0).
  19373. * "numeric" vs "non-numeric-string": "non-numeric-string" is treated as "incomparable".
  19374. * "number" vs "others": "others" is treated as "incomparable".
  19375. * "non-numeric-string" vs "others": "others" is treated as "incomparable".
  19376. * "incomparable" will be seen as -Infinity or Infinity (depends on the settings).
  19377. * MEMO:
  19378. * non-numeric string sort make sence when need to put the items with the same tag together.
  19379. * But if we support string sort, we still need to avoid the misleading like `'2' > '12'`,
  19380. * So we treat "numeric-string" sorted by number order rather than string comparison.
  19381. *
  19382. *
  19383. * [CHECK_LIST_OF_THE_RULE_DESIGN]
  19384. * + Do not support string comparison until required. And also need to
  19385. * void the misleading of "2" > "12".
  19386. * + Should avoid the misleading case:
  19387. * `" 22 " gte "22"` is `true` but `" 22 " eq "22"` is `false`.
  19388. * + JS bad case should be avoided: null <= 0, [] <= 0, ' ' <= 0, ...
  19389. * + Only "numeric" can be converted to comparable number, otherwise converted to NaN.
  19390. * See `util/number.ts#numericToNumber`.
  19391. *
  19392. * @return If `op` is not `RelationalOperator`, return null;
  19393. */
  19394. function createFilterComparator(op, rval) {
  19395. return op === 'eq' || op === 'ne' ? new FilterEqualityComparator(op === 'eq', rval) : hasOwn(ORDER_COMPARISON_OP_MAP, op) ? new FilterOrderComparator(op, rval) : null;
  19396. }
  19397. /**
  19398. * TODO: disable writable.
  19399. * This structure will be exposed to users.
  19400. */
  19401. var ExternalSource =
  19402. /** @class */
  19403. function () {
  19404. function ExternalSource() {}
  19405. ExternalSource.prototype.getRawData = function () {
  19406. // Only built-in transform available.
  19407. throw new Error('not supported');
  19408. };
  19409. ExternalSource.prototype.getRawDataItem = function (dataIndex) {
  19410. // Only built-in transform available.
  19411. throw new Error('not supported');
  19412. };
  19413. ExternalSource.prototype.cloneRawData = function () {
  19414. return;
  19415. };
  19416. /**
  19417. * @return If dimension not found, return null/undefined.
  19418. */
  19419. ExternalSource.prototype.getDimensionInfo = function (dim) {
  19420. return;
  19421. };
  19422. /**
  19423. * dimensions defined if and only if either:
  19424. * (a) dataset.dimensions are declared.
  19425. * (b) dataset data include dimensions definitions in data (detected or via specified `sourceHeader`).
  19426. * If dimensions are defined, `dimensionInfoAll` is corresponding to
  19427. * the defined dimensions.
  19428. * Otherwise, `dimensionInfoAll` is determined by data columns.
  19429. * @return Always return an array (even empty array).
  19430. */
  19431. ExternalSource.prototype.cloneAllDimensionInfo = function () {
  19432. return;
  19433. };
  19434. ExternalSource.prototype.count = function () {
  19435. return;
  19436. };
  19437. /**
  19438. * Only support by dimension index.
  19439. * No need to support by dimension name in transform function,
  19440. * becuase transform function is not case-specific, no need to use name literally.
  19441. */
  19442. ExternalSource.prototype.retrieveValue = function (dataIndex, dimIndex) {
  19443. return;
  19444. };
  19445. ExternalSource.prototype.retrieveValueFromItem = function (dataItem, dimIndex) {
  19446. return;
  19447. };
  19448. ExternalSource.prototype.convertValue = function (rawVal, dimInfo) {
  19449. return parseDataValue(rawVal, dimInfo);
  19450. };
  19451. return ExternalSource;
  19452. }();
  19453. function createExternalSource(internalSource, externalTransform) {
  19454. var extSource = new ExternalSource();
  19455. var data = internalSource.data;
  19456. var sourceFormat = extSource.sourceFormat = internalSource.sourceFormat;
  19457. var sourceHeaderCount = internalSource.startIndex;
  19458. var errMsg = '';
  19459. if (internalSource.seriesLayoutBy !== SERIES_LAYOUT_BY_COLUMN) {
  19460. // For the logic simplicity in transformer, only 'culumn' is
  19461. // supported in data transform. Otherwise, the `dimensionsDefine`
  19462. // might be detected by 'row', which probably confuses users.
  19463. if ("development" !== 'production') {
  19464. errMsg = '`seriesLayoutBy` of upstream dataset can only be "column" in data transform.';
  19465. }
  19466. throwError(errMsg);
  19467. } // [MEMO]
  19468. // Create a new dimensions structure for exposing.
  19469. // Do not expose all dimension info to users directly.
  19470. // Becuase the dimension is probably auto detected from data and not might reliable.
  19471. // Should not lead the transformers to think that is relialbe and return it.
  19472. // See [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19473. var dimensions = [];
  19474. var dimsByName = {};
  19475. var dimsDef = internalSource.dimensionsDefine;
  19476. if (dimsDef) {
  19477. each(dimsDef, function (dimDef, idx) {
  19478. var name = dimDef.name;
  19479. var dimDefExt = {
  19480. index: idx,
  19481. name: name,
  19482. displayName: dimDef.displayName
  19483. };
  19484. dimensions.push(dimDefExt); // Users probably not sepcify dimension name. For simplicity, data transform
  19485. // do not generate dimension name.
  19486. if (name != null) {
  19487. // Dimension name should not be duplicated.
  19488. // For simplicity, data transform forbid name duplication, do not generate
  19489. // new name like module `completeDimensions.ts` did, but just tell users.
  19490. var errMsg_1 = '';
  19491. if (hasOwn(dimsByName, name)) {
  19492. if ("development" !== 'production') {
  19493. errMsg_1 = 'dimension name "' + name + '" duplicated.';
  19494. }
  19495. throwError(errMsg_1);
  19496. }
  19497. dimsByName[name] = dimDefExt;
  19498. }
  19499. });
  19500. } // If dimension definitions are not defined and can not be detected.
  19501. // e.g., pure data `[[11, 22], ...]`.
  19502. else {
  19503. for (var i = 0; i < internalSource.dimensionsDetectedCount || 0; i++) {
  19504. // Do not generete name or anything others. The consequence process in
  19505. // `transform` or `series` probably have there own name generation strategry.
  19506. dimensions.push({
  19507. index: i
  19508. });
  19509. }
  19510. } // Implement public methods:
  19511. var rawItemGetter = getRawSourceItemGetter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19512. if (externalTransform.__isBuiltIn) {
  19513. extSource.getRawDataItem = function (dataIndex) {
  19514. return rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19515. };
  19516. extSource.getRawData = bind(getRawData, null, internalSource);
  19517. }
  19518. extSource.cloneRawData = bind(cloneRawData, null, internalSource);
  19519. var rawCounter = getRawSourceDataCounter(sourceFormat, SERIES_LAYOUT_BY_COLUMN);
  19520. extSource.count = bind(rawCounter, null, data, sourceHeaderCount, dimensions);
  19521. var rawValueGetter = getRawSourceValueGetter(sourceFormat);
  19522. extSource.retrieveValue = function (dataIndex, dimIndex) {
  19523. var rawItem = rawItemGetter(data, sourceHeaderCount, dimensions, dataIndex);
  19524. return retrieveValueFromItem(rawItem, dimIndex);
  19525. };
  19526. var retrieveValueFromItem = extSource.retrieveValueFromItem = function (dataItem, dimIndex) {
  19527. if (dataItem == null) {
  19528. return;
  19529. }
  19530. var dimDef = dimensions[dimIndex]; // When `dimIndex` is `null`, `rawValueGetter` return the whole item.
  19531. if (dimDef) {
  19532. return rawValueGetter(dataItem, dimIndex, dimDef.name);
  19533. }
  19534. };
  19535. extSource.getDimensionInfo = bind(getDimensionInfo, null, dimensions, dimsByName);
  19536. extSource.cloneAllDimensionInfo = bind(cloneAllDimensionInfo, null, dimensions);
  19537. return extSource;
  19538. }
  19539. function getRawData(upstream) {
  19540. var sourceFormat = upstream.sourceFormat;
  19541. if (!isSupportedSourceFormat(sourceFormat)) {
  19542. var errMsg = '';
  19543. if ("development" !== 'production') {
  19544. errMsg = '`getRawData` is not supported in source format ' + sourceFormat;
  19545. }
  19546. throwError(errMsg);
  19547. }
  19548. return upstream.data;
  19549. }
  19550. function cloneRawData(upstream) {
  19551. var sourceFormat = upstream.sourceFormat;
  19552. var data = upstream.data;
  19553. if (!isSupportedSourceFormat(sourceFormat)) {
  19554. var errMsg = '';
  19555. if ("development" !== 'production') {
  19556. errMsg = '`cloneRawData` is not supported in source format ' + sourceFormat;
  19557. }
  19558. throwError(errMsg);
  19559. }
  19560. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  19561. var result = [];
  19562. for (var i = 0, len = data.length; i < len; i++) {
  19563. // Not strictly clone for performance
  19564. result.push(data[i].slice());
  19565. }
  19566. return result;
  19567. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  19568. var result = [];
  19569. for (var i = 0, len = data.length; i < len; i++) {
  19570. // Not strictly clone for performance
  19571. result.push(extend({}, data[i]));
  19572. }
  19573. return result;
  19574. }
  19575. }
  19576. function getDimensionInfo(dimensions, dimsByName, dim) {
  19577. if (dim == null) {
  19578. return;
  19579. } // Keep the same logic as `List::getDimension` did.
  19580. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  19581. || !isNaN(dim) && !hasOwn(dimsByName, dim)) {
  19582. return dimensions[dim];
  19583. } else if (hasOwn(dimsByName, dim)) {
  19584. return dimsByName[dim];
  19585. }
  19586. }
  19587. function cloneAllDimensionInfo(dimensions) {
  19588. return clone(dimensions);
  19589. }
  19590. var externalTransformMap = createHashMap();
  19591. function registerExternalTransform(externalTransform) {
  19592. externalTransform = clone(externalTransform);
  19593. var type = externalTransform.type;
  19594. var errMsg = '';
  19595. if (!type) {
  19596. if ("development" !== 'production') {
  19597. errMsg = 'Must have a `type` when `registerTransform`.';
  19598. }
  19599. throwError(errMsg);
  19600. }
  19601. var typeParsed = type.split(':');
  19602. if (typeParsed.length !== 2) {
  19603. if ("development" !== 'production') {
  19604. errMsg = 'Name must include namespace like "ns:regression".';
  19605. }
  19606. throwError(errMsg);
  19607. } // Namespace 'echarts:xxx' is official namespace, where the transforms should
  19608. // be called directly via 'xxx' rather than 'echarts:xxx'.
  19609. var isBuiltIn = false;
  19610. if (typeParsed[0] === 'echarts') {
  19611. type = typeParsed[1];
  19612. isBuiltIn = true;
  19613. }
  19614. externalTransform.__isBuiltIn = isBuiltIn;
  19615. externalTransformMap.set(type, externalTransform);
  19616. }
  19617. function applyDataTransform(rawTransOption, sourceList, infoForPrint) {
  19618. var pipedTransOption = normalizeToArray(rawTransOption);
  19619. var pipeLen = pipedTransOption.length;
  19620. var errMsg = '';
  19621. if (!pipeLen) {
  19622. if ("development" !== 'production') {
  19623. errMsg = 'If `transform` declared, it should at least contain one transform.';
  19624. }
  19625. throwError(errMsg);
  19626. }
  19627. for (var i = 0, len = pipeLen; i < len; i++) {
  19628. var transOption = pipedTransOption[i];
  19629. sourceList = applySingleDataTransform(transOption, sourceList, infoForPrint, pipeLen === 1 ? null : i); // piped transform only support single input, except the fist one.
  19630. // piped transform only support single output, except the last one.
  19631. if (i !== len - 1) {
  19632. sourceList.length = Math.max(sourceList.length, 1);
  19633. }
  19634. }
  19635. return sourceList;
  19636. }
  19637. function applySingleDataTransform(transOption, upSourceList, infoForPrint, // If `pipeIndex` is null/undefined, no piped transform.
  19638. pipeIndex) {
  19639. var errMsg = '';
  19640. if (!upSourceList.length) {
  19641. if ("development" !== 'production') {
  19642. errMsg = 'Must have at least one upstream dataset.';
  19643. }
  19644. throwError(errMsg);
  19645. }
  19646. if (!isObject(transOption)) {
  19647. if ("development" !== 'production') {
  19648. errMsg = 'transform declaration must be an object rather than ' + typeof transOption + '.';
  19649. }
  19650. throwError(errMsg);
  19651. }
  19652. var transType = transOption.type;
  19653. var externalTransform = externalTransformMap.get(transType);
  19654. if (!externalTransform) {
  19655. if ("development" !== 'production') {
  19656. errMsg = 'Can not find transform on type "' + transType + '".';
  19657. }
  19658. throwError(errMsg);
  19659. } // Prepare source
  19660. var extUpSourceList = map(upSourceList, function (upSource) {
  19661. return createExternalSource(upSource, externalTransform);
  19662. });
  19663. var resultList = normalizeToArray(externalTransform.transform({
  19664. upstream: extUpSourceList[0],
  19665. upstreamList: extUpSourceList,
  19666. config: clone(transOption.config)
  19667. }));
  19668. if ("development" !== 'production') {
  19669. if (transOption.print) {
  19670. var printStrArr = map(resultList, function (extSource) {
  19671. var pipeIndexStr = pipeIndex != null ? ' === pipe index: ' + pipeIndex : '';
  19672. return ['=== dataset index: ' + infoForPrint.datasetIndex + pipeIndexStr + ' ===', '- transform result data:', makePrintable(extSource.data), '- transform result dimensions:', makePrintable(extSource.dimensions)].join('\n');
  19673. }).join('\n');
  19674. consoleLog(printStrArr);
  19675. }
  19676. }
  19677. return map(resultList, function (result, resultIndex) {
  19678. var errMsg = '';
  19679. if (!isObject(result)) {
  19680. if ("development" !== 'production') {
  19681. errMsg = 'A transform should not return some empty results.';
  19682. }
  19683. throwError(errMsg);
  19684. }
  19685. if (!result.data) {
  19686. if ("development" !== 'production') {
  19687. errMsg = 'Transform result data should be not be null or undefined';
  19688. }
  19689. throwError(errMsg);
  19690. }
  19691. var sourceFormat = detectSourceFormat(result.data);
  19692. if (!isSupportedSourceFormat(sourceFormat)) {
  19693. if ("development" !== 'production') {
  19694. errMsg = 'Transform result data should be array rows or object rows.';
  19695. }
  19696. throwError(errMsg);
  19697. }
  19698. var resultMetaRawOption;
  19699. var firstUpSource = upSourceList[0];
  19700. /**
  19701. * Intuitively, the end users known the content of the original `dataset.source`,
  19702. * calucating the transform result in mind.
  19703. * Suppose the original `dataset.source` is:
  19704. * ```js
  19705. * [
  19706. * ['product', '2012', '2013', '2014', '2015'],
  19707. * ['AAA', 41.1, 30.4, 65.1, 53.3],
  19708. * ['BBB', 86.5, 92.1, 85.7, 83.1],
  19709. * ['CCC', 24.1, 67.2, 79.5, 86.4]
  19710. * ]
  19711. * ```
  19712. * The dimension info have to be detected from the source data.
  19713. * Some of the transformers (like filter, sort) will follow the dimension info
  19714. * of upstream, while others use new dimensions (like aggregate).
  19715. * Transformer can output a field `dimensions` to define the its own output dimensions.
  19716. * We also allow transformers to ignore the output `dimensions` field, and
  19717. * inherit the upstream dimensions definition. It can reduce the burden of handling
  19718. * dimensions in transformers.
  19719. *
  19720. * See also [DIMENSION_INHERIT_RULE] in `sourceManager.ts`.
  19721. */
  19722. if (firstUpSource && resultIndex === 0 // If transformer returns `dimensions`, it means that the transformer has different
  19723. // dimensions definitions. We do not inherit anything from upstream.
  19724. && !result.dimensions) {
  19725. var startIndex = firstUpSource.startIndex; // We copy the header of upstream to the result becuase:
  19726. // (1) The returned data always does not contain header line and can not be used
  19727. // as dimension-detection. In this case we can not use "detected dimensions" of
  19728. // upstream directly, because it might be detected based on different `seriesLayoutBy`.
  19729. // (2) We should support that the series read the upstream source in `seriesLayoutBy: 'row'`.
  19730. // So the original detected header should be add to the result, otherwise they can not be read.
  19731. if (startIndex) {
  19732. result.data = firstUpSource.data.slice(0, startIndex).concat(result.data);
  19733. }
  19734. resultMetaRawOption = {
  19735. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19736. sourceHeader: startIndex,
  19737. dimensions: firstUpSource.metaRawOption.dimensions
  19738. };
  19739. } else {
  19740. resultMetaRawOption = {
  19741. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  19742. sourceHeader: 0,
  19743. dimensions: result.dimensions
  19744. };
  19745. }
  19746. return createSource(result.data, resultMetaRawOption, null, null);
  19747. });
  19748. }
  19749. function isSupportedSourceFormat(sourceFormat) {
  19750. return sourceFormat === SOURCE_FORMAT_ARRAY_ROWS || sourceFormat === SOURCE_FORMAT_OBJECT_ROWS;
  19751. }
  19752. /**
  19753. * [REQUIREMENT_MEMO]:
  19754. * (0) `metaRawOption` means `dimensions`/`sourceHeader`/`seriesLayoutBy` in raw option.
  19755. * (1) Keep support the feature: `metaRawOption` can be specified both on `series` and
  19756. * `root-dataset`. Them on `series` has higher priority.
  19757. * (2) Do not support to set `metaRawOption` on a `non-root-dataset`, because it might
  19758. * confuse users: whether those props indicate how to visit the upstream source or visit
  19759. * the transform result source, and some transforms has nothing to do with these props,
  19760. * and some transforms might have multiple upstream.
  19761. * (3) Transforms should specify `metaRawOption` in each output, just like they can be
  19762. * declared in `root-dataset`.
  19763. * (4) At present only support visit source in `SERIES_LAYOUT_BY_COLUMN` in transforms.
  19764. * That is for reducing complexity in transfroms.
  19765. * PENDING: Whether to provide transposition transform?
  19766. *
  19767. * [IMPLEMENTAION_MEMO]:
  19768. * "sourceVisitConfig" are calculated from `metaRawOption` and `data`.
  19769. * They will not be calculated until `source` is about to be visited (to prevent from
  19770. * duplicate calcuation). `source` is visited only in series and input to transforms.
  19771. *
  19772. * [DIMENSION_INHERIT_RULE]:
  19773. * By default the dimensions are inherited from ancestors, unless a transform return
  19774. * a new dimensions definition.
  19775. * Consider the case:
  19776. * ```js
  19777. * dataset: [{
  19778. * source: [ ['Product', 'Sales', 'Prise'], ['Cookies', 321, 44.21], ...]
  19779. * }, {
  19780. * transform: { type: 'filter', ... }
  19781. * }]
  19782. * dataset: [{
  19783. * dimension: ['Product', 'Sales', 'Prise'],
  19784. * source: [ ['Cookies', 321, 44.21], ...]
  19785. * }, {
  19786. * transform: { type: 'filter', ... }
  19787. * }]
  19788. * ```
  19789. * The two types of option should have the same behavior after transform.
  19790. *
  19791. *
  19792. * [SCENARIO]:
  19793. * (1) Provide source data directly:
  19794. * ```js
  19795. * series: {
  19796. * encode: {...},
  19797. * dimensions: [...]
  19798. * seriesLayoutBy: 'row',
  19799. * data: [[...]]
  19800. * }
  19801. * ```
  19802. * (2) Series refer to dataset.
  19803. * ```js
  19804. * series: [{
  19805. * encode: {...}
  19806. * // Ignore datasetIndex means `datasetIndex: 0`
  19807. * // and the dimensions defination in dataset is used
  19808. * }, {
  19809. * encode: {...},
  19810. * seriesLayoutBy: 'column',
  19811. * datasetIndex: 1
  19812. * }]
  19813. * ```
  19814. * (3) dataset transform
  19815. * ```js
  19816. * dataset: [{
  19817. * source: [...]
  19818. * }, {
  19819. * source: [...]
  19820. * }, {
  19821. * // By default from 0.
  19822. * transform: { type: 'filter', config: {...} }
  19823. * }, {
  19824. * // Piped.
  19825. * transform: [
  19826. * { type: 'filter', config: {...} },
  19827. * { type: 'sort', config: {...} }
  19828. * ]
  19829. * }, {
  19830. * id: 'regressionData',
  19831. * fromDatasetIndex: 1,
  19832. * // Third-party transform
  19833. * transform: { type: 'ecStat:regression', config: {...} }
  19834. * }, {
  19835. * // retrieve the extra result.
  19836. * id: 'regressionFormula',
  19837. * fromDatasetId: 'regressionData',
  19838. * fromTransformResult: 1
  19839. * }]
  19840. * ```
  19841. */
  19842. var SourceManager =
  19843. /** @class */
  19844. function () {
  19845. function SourceManager(sourceHost) {
  19846. // Cached source. Do not repeat calculating if not dirty.
  19847. this._sourceList = []; // version sign of each upstream source manager.
  19848. this._upstreamSignList = [];
  19849. this._versionSignBase = 0;
  19850. this._sourceHost = sourceHost;
  19851. }
  19852. /**
  19853. * Mark dirty.
  19854. */
  19855. SourceManager.prototype.dirty = function () {
  19856. this._setLocalSource([], []);
  19857. };
  19858. SourceManager.prototype._setLocalSource = function (sourceList, upstreamSignList) {
  19859. this._sourceList = sourceList;
  19860. this._upstreamSignList = upstreamSignList;
  19861. this._versionSignBase++;
  19862. if (this._versionSignBase > 9e10) {
  19863. this._versionSignBase = 0;
  19864. }
  19865. };
  19866. /**
  19867. * For detecting whether the upstream source is dirty, so that
  19868. * the local cached source (in `_sourceList`) should be discarded.
  19869. */
  19870. SourceManager.prototype._getVersionSign = function () {
  19871. return this._sourceHost.uid + '_' + this._versionSignBase;
  19872. };
  19873. /**
  19874. * Always return a source instance. Otherwise throw error.
  19875. */
  19876. SourceManager.prototype.prepareSource = function () {
  19877. // For the case that call `setOption` multiple time but no data changed,
  19878. // cache the result source to prevent from repeating transform.
  19879. if (this._isDirty()) {
  19880. this._createSource();
  19881. }
  19882. };
  19883. SourceManager.prototype._createSource = function () {
  19884. this._setLocalSource([], []);
  19885. var sourceHost = this._sourceHost;
  19886. var upSourceMgrList = this._getUpstreamSourceManagers();
  19887. var hasUpstream = !!upSourceMgrList.length;
  19888. var resultSourceList;
  19889. var upstreamSignList;
  19890. if (isSeries(sourceHost)) {
  19891. var seriesModel = sourceHost;
  19892. var data = void 0;
  19893. var sourceFormat = void 0;
  19894. var upSource = void 0; // Has upstream dataset
  19895. if (hasUpstream) {
  19896. var upSourceMgr = upSourceMgrList[0];
  19897. upSourceMgr.prepareSource();
  19898. upSource = upSourceMgr.getSource();
  19899. data = upSource.data;
  19900. sourceFormat = upSource.sourceFormat;
  19901. upstreamSignList = [upSourceMgr._getVersionSign()];
  19902. } // Series data is from own.
  19903. else {
  19904. data = seriesModel.get('data', true);
  19905. sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  19906. upstreamSignList = [];
  19907. } // See [REQUIREMENT_MEMO], merge settings on series and parent dataset if it is root.
  19908. var newMetaRawOption = this._getSourceMetaRawOption();
  19909. var upMetaRawOption = upSource ? upSource.metaRawOption : null;
  19910. var seriesLayoutBy = retrieve2(newMetaRawOption.seriesLayoutBy, upMetaRawOption ? upMetaRawOption.seriesLayoutBy : null);
  19911. var sourceHeader = retrieve2(newMetaRawOption.sourceHeader, upMetaRawOption ? upMetaRawOption.sourceHeader : null); // Note here we should not use `upSource.dimensionsDefine`. Consider the case:
  19912. // `upSource.dimensionsDefine` is detected by `seriesLayoutBy: 'column'`,
  19913. // but series need `seriesLayoutBy: 'row'`.
  19914. var dimensions = retrieve2(newMetaRawOption.dimensions, upMetaRawOption ? upMetaRawOption.dimensions : null);
  19915. resultSourceList = [createSource(data, {
  19916. seriesLayoutBy: seriesLayoutBy,
  19917. sourceHeader: sourceHeader,
  19918. dimensions: dimensions
  19919. }, sourceFormat, seriesModel.get('encode', true))];
  19920. } else {
  19921. var datasetModel = sourceHost; // Has upstream dataset.
  19922. if (hasUpstream) {
  19923. var result = this._applyTransform(upSourceMgrList);
  19924. resultSourceList = result.sourceList;
  19925. upstreamSignList = result.upstreamSignList;
  19926. } // Is root dataset.
  19927. else {
  19928. var sourceData = datasetModel.get('source', true);
  19929. resultSourceList = [createSource(sourceData, this._getSourceMetaRawOption(), null, // Note: dataset option does not have `encode`.
  19930. null)];
  19931. upstreamSignList = [];
  19932. }
  19933. }
  19934. if ("development" !== 'production') {
  19935. assert(resultSourceList && upstreamSignList);
  19936. }
  19937. this._setLocalSource(resultSourceList, upstreamSignList);
  19938. };
  19939. SourceManager.prototype._applyTransform = function (upMgrList) {
  19940. var datasetModel = this._sourceHost;
  19941. var transformOption = datasetModel.get('transform', true);
  19942. var fromTransformResult = datasetModel.get('fromTransformResult', true);
  19943. if ("development" !== 'production') {
  19944. assert(fromTransformResult != null || transformOption != null);
  19945. }
  19946. if (fromTransformResult != null) {
  19947. var errMsg = '';
  19948. if (upMgrList.length !== 1) {
  19949. if ("development" !== 'production') {
  19950. errMsg = 'When using `fromTransformResult`, there should be only one upstream dataset';
  19951. }
  19952. doThrow(errMsg);
  19953. }
  19954. }
  19955. var sourceList;
  19956. var upSourceList = [];
  19957. var upstreamSignList = [];
  19958. each(upMgrList, function (upMgr) {
  19959. upMgr.prepareSource();
  19960. var upSource = upMgr.getSource(fromTransformResult || 0);
  19961. var errMsg = '';
  19962. if (fromTransformResult != null && !upSource) {
  19963. if ("development" !== 'production') {
  19964. errMsg = 'Can not retrieve result by `fromTransformResult`: ' + fromTransformResult;
  19965. }
  19966. doThrow(errMsg);
  19967. }
  19968. upSourceList.push(upSource);
  19969. upstreamSignList.push(upMgr._getVersionSign());
  19970. });
  19971. if (transformOption) {
  19972. sourceList = applyDataTransform(transformOption, upSourceList, {
  19973. datasetIndex: datasetModel.componentIndex
  19974. });
  19975. } else if (fromTransformResult != null) {
  19976. sourceList = [cloneSourceShallow(upSourceList[0])];
  19977. }
  19978. return {
  19979. sourceList: sourceList,
  19980. upstreamSignList: upstreamSignList
  19981. };
  19982. };
  19983. SourceManager.prototype._isDirty = function () {
  19984. var sourceList = this._sourceList;
  19985. if (!sourceList.length) {
  19986. return true;
  19987. } // All sourceList is from the some upsteam.
  19988. var upSourceMgrList = this._getUpstreamSourceManagers();
  19989. for (var i = 0; i < upSourceMgrList.length; i++) {
  19990. var upSrcMgr = upSourceMgrList[i];
  19991. if ( // Consider the case that there is ancestor diry, call it recursively.
  19992. // The performance is probably not an issue because usually the chain is not long.
  19993. upSrcMgr._isDirty() || this._upstreamSignList[i] !== upSrcMgr._getVersionSign()) {
  19994. return true;
  19995. }
  19996. }
  19997. };
  19998. /**
  19999. * @param sourceIndex By defualt 0, means "main source".
  20000. * Most cases there is only one source.
  20001. */
  20002. SourceManager.prototype.getSource = function (sourceIndex) {
  20003. return this._sourceList[sourceIndex || 0];
  20004. };
  20005. /**
  20006. * PEDING: Is it fast enough?
  20007. * If no upstream, return empty array.
  20008. */
  20009. SourceManager.prototype._getUpstreamSourceManagers = function () {
  20010. // Always get the relationship from the raw option.
  20011. // Do not cache the link of the dependency graph, so that
  20012. // no need to update them when change happen.
  20013. var sourceHost = this._sourceHost;
  20014. if (isSeries(sourceHost)) {
  20015. var datasetModel = querySeriesUpstreamDatasetModel(sourceHost);
  20016. return !datasetModel ? [] : [datasetModel.getSourceManager()];
  20017. } else {
  20018. return map(queryDatasetUpstreamDatasetModels(sourceHost), function (datasetModel) {
  20019. return datasetModel.getSourceManager();
  20020. });
  20021. }
  20022. };
  20023. SourceManager.prototype._getSourceMetaRawOption = function () {
  20024. var sourceHost = this._sourceHost;
  20025. var seriesLayoutBy;
  20026. var sourceHeader;
  20027. var dimensions;
  20028. if (isSeries(sourceHost)) {
  20029. seriesLayoutBy = sourceHost.get('seriesLayoutBy', true);
  20030. sourceHeader = sourceHost.get('sourceHeader', true);
  20031. dimensions = sourceHost.get('dimensions', true);
  20032. } // See [REQUIREMENT_MEMO], `non-root-dataset` do not support them.
  20033. else if (!this._getUpstreamSourceManagers().length) {
  20034. var model = sourceHost;
  20035. seriesLayoutBy = model.get('seriesLayoutBy', true);
  20036. sourceHeader = model.get('sourceHeader', true);
  20037. dimensions = model.get('dimensions', true);
  20038. }
  20039. return {
  20040. seriesLayoutBy: seriesLayoutBy,
  20041. sourceHeader: sourceHeader,
  20042. dimensions: dimensions
  20043. };
  20044. };
  20045. return SourceManager;
  20046. }();
  20047. // disable the transform merge, but do not disable transfrom clone from rawOption.
  20048. function disableTransformOptionMerge(datasetModel) {
  20049. var transformOption = datasetModel.option.transform;
  20050. transformOption && setAsPrimitive(datasetModel.option.transform);
  20051. }
  20052. function isSeries(sourceHost) {
  20053. // Avoid circular dependency with Series.ts
  20054. return sourceHost.mainType === 'series';
  20055. }
  20056. function doThrow(errMsg) {
  20057. throw new Error(errMsg);
  20058. }
  20059. var TOOLTIP_LINE_HEIGHT_CSS = 'line-height:1'; // TODO: more textStyle option
  20060. function getTooltipTextStyle(textStyle, renderMode) {
  20061. var nameFontColor = textStyle.color || '#6e7079';
  20062. var nameFontSize = textStyle.fontSize || 12;
  20063. var nameFontWeight = textStyle.fontWeight || '400';
  20064. var valueFontColor = textStyle.color || '#464646';
  20065. var valueFontSize = textStyle.fontSize || 14;
  20066. var valueFontWeight = textStyle.fontWeight || '900';
  20067. if (renderMode === 'html') {
  20068. // `textStyle` is probably from user input, should be encoded to reduce security risk.
  20069. return {
  20070. // eslint-disable-next-line max-len
  20071. nameStyle: "font-size:" + encodeHTML(nameFontSize + '') + "px;color:" + encodeHTML(nameFontColor) + ";font-weight:" + encodeHTML(nameFontWeight + ''),
  20072. // eslint-disable-next-line max-len
  20073. valueStyle: "font-size:" + encodeHTML(valueFontSize + '') + "px;color:" + encodeHTML(valueFontColor) + ";font-weight:" + encodeHTML(valueFontWeight + '')
  20074. };
  20075. } else {
  20076. return {
  20077. nameStyle: {
  20078. fontSize: nameFontSize,
  20079. fill: nameFontColor,
  20080. fontWeight: nameFontWeight
  20081. },
  20082. valueStyle: {
  20083. fontSize: valueFontSize,
  20084. fill: valueFontColor,
  20085. fontWeight: valueFontWeight
  20086. }
  20087. };
  20088. }
  20089. } // See `TooltipMarkupLayoutIntent['innerGapLevel']`.
  20090. // (value from UI design)
  20091. var HTML_GAPS = [0, 10, 20, 30];
  20092. var RICH_TEXT_GAPS = ['', '\n', '\n\n', '\n\n\n']; // eslint-disable-next-line max-len
  20093. function createTooltipMarkup(type, option) {
  20094. option.type = type;
  20095. return option;
  20096. }
  20097. function getBuilder(fragment) {
  20098. return hasOwn(builderMap, fragment.type) && builderMap[fragment.type];
  20099. }
  20100. var builderMap = {
  20101. /**
  20102. * A `section` block is like:
  20103. * ```
  20104. * header
  20105. * subBlock
  20106. * subBlock
  20107. * ...
  20108. * ```
  20109. */
  20110. section: {
  20111. planLayout: function (fragment) {
  20112. var subBlockLen = fragment.blocks.length;
  20113. var thisBlockHasInnerGap = subBlockLen > 1 || subBlockLen > 0 && !fragment.noHeader;
  20114. var thisGapLevelBetweenSubBlocks = 0;
  20115. each(fragment.blocks, function (subBlock) {
  20116. getBuilder(subBlock).planLayout(subBlock);
  20117. var subGapLevel = subBlock.__gapLevelBetweenSubBlocks; // If the some of the sub-blocks have some gaps (like 10px) inside, this block
  20118. // should use a larger gap (like 20px) to distinguish those sub-blocks.
  20119. if (subGapLevel >= thisGapLevelBetweenSubBlocks) {
  20120. thisGapLevelBetweenSubBlocks = subGapLevel + (thisBlockHasInnerGap && ( // 0 always can not be readable gap level.
  20121. !subGapLevel // If no header, always keep the sub gap level. Otherwise
  20122. // look weird in case `multipleSeries`.
  20123. || subBlock.type === 'section' && !subBlock.noHeader) ? 1 : 0);
  20124. }
  20125. });
  20126. fragment.__gapLevelBetweenSubBlocks = thisGapLevelBetweenSubBlocks;
  20127. },
  20128. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  20129. var noHeader = fragment.noHeader;
  20130. var gaps = getGap(fragment);
  20131. var subMarkupText = buildSubBlocks(ctx, fragment, noHeader ? topMarginForOuterGap : gaps.html, toolTipTextStyle);
  20132. if (noHeader) {
  20133. return subMarkupText;
  20134. }
  20135. var displayableHeader = makeValueReadable(fragment.header, 'ordinal', ctx.useUTC);
  20136. var nameStyle = getTooltipTextStyle(toolTipTextStyle, ctx.renderMode).nameStyle;
  20137. if (ctx.renderMode === 'richText') {
  20138. return wrapInlineNameRichText(ctx, displayableHeader, nameStyle) + gaps.richText + subMarkupText;
  20139. } else {
  20140. return wrapBlockHTML("<div style=\"" + nameStyle + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodeHTML(displayableHeader) + '</div>' + subMarkupText, topMarginForOuterGap);
  20141. }
  20142. }
  20143. },
  20144. /**
  20145. * A `nameValue` block is like:
  20146. * ```
  20147. * marker name value
  20148. * ```
  20149. */
  20150. nameValue: {
  20151. planLayout: function (fragment) {
  20152. fragment.__gapLevelBetweenSubBlocks = 0;
  20153. },
  20154. build: function (ctx, fragment, topMarginForOuterGap, toolTipTextStyle) {
  20155. var renderMode = ctx.renderMode;
  20156. var noName = fragment.noName;
  20157. var noValue = fragment.noValue;
  20158. var noMarker = !fragment.markerType;
  20159. var name = fragment.name;
  20160. var value = fragment.value;
  20161. var useUTC = ctx.useUTC;
  20162. if (noName && noValue) {
  20163. return;
  20164. }
  20165. var markerStr = noMarker ? '' : ctx.markupStyleCreator.makeTooltipMarker(fragment.markerType, fragment.markerColor || '#333', renderMode);
  20166. var readableName = noName ? '' : makeValueReadable(name, 'ordinal', useUTC);
  20167. var valueTypeOption = fragment.valueType;
  20168. var readableValueList = noValue ? [] : isArray(value) ? map(value, function (val, idx) {
  20169. return makeValueReadable(val, isArray(valueTypeOption) ? valueTypeOption[idx] : valueTypeOption, useUTC);
  20170. }) : [makeValueReadable(value, isArray(valueTypeOption) ? valueTypeOption[0] : valueTypeOption, useUTC)];
  20171. var valueAlignRight = !noMarker || !noName; // It little weird if only value next to marker but far from marker.
  20172. var valueCloseToMarker = !noMarker && noName;
  20173. var _a = getTooltipTextStyle(toolTipTextStyle, renderMode),
  20174. nameStyle = _a.nameStyle,
  20175. valueStyle = _a.valueStyle;
  20176. return renderMode === 'richText' ? (noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameRichText(ctx, readableName, nameStyle)) // Value has commas inside, so use ' ' as delimiter for multiple values.
  20177. + (noValue ? '' : wrapInlineValueRichText(ctx, readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)) : wrapBlockHTML((noMarker ? '' : markerStr) + (noName ? '' : wrapInlineNameHTML(readableName, !noMarker, nameStyle)) + (noValue ? '' : wrapInlineValueHTML(readableValueList, valueAlignRight, valueCloseToMarker, valueStyle)), topMarginForOuterGap);
  20178. }
  20179. }
  20180. };
  20181. function buildSubBlocks(ctx, fragment, topMarginForOuterGap, tooltipTextStyle) {
  20182. var subMarkupTextList = [];
  20183. var subBlocks = fragment.blocks || [];
  20184. assert(!subBlocks || isArray(subBlocks));
  20185. subBlocks = subBlocks || [];
  20186. var orderMode = ctx.orderMode;
  20187. if (fragment.sortBlocks && orderMode) {
  20188. subBlocks = subBlocks.slice();
  20189. var orderMap = {
  20190. valueAsc: 'asc',
  20191. valueDesc: 'desc'
  20192. };
  20193. if (hasOwn(orderMap, orderMode)) {
  20194. var comparator_1 = new SortOrderComparator(orderMap[orderMode], null);
  20195. subBlocks.sort(function (a, b) {
  20196. return comparator_1.evaluate(a.sortParam, b.sortParam);
  20197. });
  20198. } // FIXME 'seriesDesc' necessary?
  20199. else if (orderMode === 'seriesDesc') {
  20200. subBlocks.reverse();
  20201. }
  20202. }
  20203. var gaps = getGap(fragment);
  20204. each(subBlocks, function (subBlock, idx) {
  20205. var subMarkupText = getBuilder(subBlock).build(ctx, subBlock, idx > 0 ? gaps.html : 0, tooltipTextStyle);
  20206. subMarkupText != null && subMarkupTextList.push(subMarkupText);
  20207. });
  20208. if (!subMarkupTextList.length) {
  20209. return;
  20210. }
  20211. return ctx.renderMode === 'richText' ? subMarkupTextList.join(gaps.richText) : wrapBlockHTML(subMarkupTextList.join(''), topMarginForOuterGap);
  20212. }
  20213. /**
  20214. * @return markupText. null/undefined means no content.
  20215. */
  20216. function buildTooltipMarkup(fragment, markupStyleCreator, renderMode, orderMode, useUTC, toolTipTextStyle) {
  20217. if (!fragment) {
  20218. return;
  20219. }
  20220. var builder = getBuilder(fragment);
  20221. builder.planLayout(fragment);
  20222. var ctx = {
  20223. useUTC: useUTC,
  20224. renderMode: renderMode,
  20225. orderMode: orderMode,
  20226. markupStyleCreator: markupStyleCreator
  20227. };
  20228. return builder.build(ctx, fragment, 0, toolTipTextStyle);
  20229. }
  20230. function getGap(fragment) {
  20231. var gapLevelBetweenSubBlocks = fragment.__gapLevelBetweenSubBlocks;
  20232. return {
  20233. html: HTML_GAPS[gapLevelBetweenSubBlocks],
  20234. richText: RICH_TEXT_GAPS[gapLevelBetweenSubBlocks]
  20235. };
  20236. }
  20237. function wrapBlockHTML(encodedContent, topGap) {
  20238. var clearfix = '<div style="clear:both"></div>';
  20239. var marginCSS = "margin: " + topGap + "px 0 0";
  20240. return "<div style=\"" + marginCSS + ";" + TOOLTIP_LINE_HEIGHT_CSS + ";\">" + encodedContent + clearfix + '</div>';
  20241. }
  20242. function wrapInlineNameHTML(name, leftHasMarker, style) {
  20243. var marginCss = leftHasMarker ? 'margin-left:2px' : '';
  20244. return "<span style=\"" + style + ";" + marginCss + "\">" + encodeHTML(name) + '</span>';
  20245. }
  20246. function wrapInlineValueHTML(valueList, alignRight, valueCloseToMarker, style) {
  20247. // Do not too close to marker, considering there are multiple values separated by spaces.
  20248. var paddingStr = valueCloseToMarker ? '10px' : '20px';
  20249. var alignCSS = alignRight ? "float:right;margin-left:" + paddingStr : '';
  20250. return "<span style=\"" + alignCSS + ";" + style + "\">" // Value has commas inside, so use ' ' as delimiter for multiple values.
  20251. + map(valueList, function (value) {
  20252. return encodeHTML(value);
  20253. }).join('&nbsp;&nbsp;') + '</span>';
  20254. }
  20255. function wrapInlineNameRichText(ctx, name, style) {
  20256. return ctx.markupStyleCreator.wrapRichTextStyle(name, style);
  20257. }
  20258. function wrapInlineValueRichText(ctx, valueList, alignRight, valueCloseToMarker, style) {
  20259. var styles = [style];
  20260. var paddingLeft = valueCloseToMarker ? 10 : 20;
  20261. alignRight && styles.push({
  20262. padding: [0, 0, 0, paddingLeft],
  20263. align: 'right'
  20264. }); // Value has commas inside, so use ' ' as delimiter for multiple values.
  20265. return ctx.markupStyleCreator.wrapRichTextStyle(valueList.join(' '), styles);
  20266. }
  20267. function retrieveVisualColorForTooltipMarker(series, dataIndex) {
  20268. var style = series.getData().getItemVisual(dataIndex, 'style');
  20269. var color = style[series.visualDrawType];
  20270. return convertToColorString(color);
  20271. }
  20272. function getPaddingFromTooltipModel(model, renderMode) {
  20273. var padding = model.get('padding');
  20274. return padding != null ? padding // We give slightly different to look pretty.
  20275. : renderMode === 'richText' ? [8, 10] : 10;
  20276. }
  20277. /**
  20278. * The major feature is generate styles for `renderMode: 'richText'`.
  20279. * But it also serves `renderMode: 'html'` to provide
  20280. * "renderMode-independent" API.
  20281. */
  20282. var TooltipMarkupStyleCreator =
  20283. /** @class */
  20284. function () {
  20285. function TooltipMarkupStyleCreator() {
  20286. this.richTextStyles = {}; // Notice that "generate a style name" usuall happens repeatly when mouse moving and
  20287. // displaying a tooltip. So we put the `_nextStyleNameId` as a member of each creator
  20288. // rather than static shared by all creators (which will cause it increase to fast).
  20289. this._nextStyleNameId = getRandomIdBase();
  20290. }
  20291. TooltipMarkupStyleCreator.prototype._generateStyleName = function () {
  20292. return '__EC_aUTo_' + this._nextStyleNameId++;
  20293. };
  20294. TooltipMarkupStyleCreator.prototype.makeTooltipMarker = function (markerType, colorStr, renderMode) {
  20295. var markerId = renderMode === 'richText' ? this._generateStyleName() : null;
  20296. var marker = getTooltipMarker({
  20297. color: colorStr,
  20298. type: markerType,
  20299. renderMode: renderMode,
  20300. markerId: markerId
  20301. });
  20302. if (isString(marker)) {
  20303. return marker;
  20304. } else {
  20305. if ("development" !== 'production') {
  20306. assert(markerId);
  20307. }
  20308. this.richTextStyles[markerId] = marker.style;
  20309. return marker.content;
  20310. }
  20311. };
  20312. /**
  20313. * @usage
  20314. * ```ts
  20315. * const styledText = markupStyleCreator.wrapRichTextStyle([
  20316. * // The styles will be auto merged.
  20317. * {
  20318. * fontSize: 12,
  20319. * color: 'blue'
  20320. * },
  20321. * {
  20322. * padding: 20
  20323. * }
  20324. * ]);
  20325. * ```
  20326. */
  20327. TooltipMarkupStyleCreator.prototype.wrapRichTextStyle = function (text, styles) {
  20328. var finalStl = {};
  20329. if (isArray(styles)) {
  20330. each(styles, function (stl) {
  20331. return extend(finalStl, stl);
  20332. });
  20333. } else {
  20334. extend(finalStl, styles);
  20335. }
  20336. var styleName = this._generateStyleName();
  20337. this.richTextStyles[styleName] = finalStl;
  20338. return "{" + styleName + "|" + text + "}";
  20339. };
  20340. return TooltipMarkupStyleCreator;
  20341. }();
  20342. function defaultSeriesFormatTooltip(opt) {
  20343. var series = opt.series;
  20344. var dataIndex = opt.dataIndex;
  20345. var multipleSeries = opt.multipleSeries;
  20346. var data = series.getData();
  20347. var tooltipDims = data.mapDimensionsAll('defaultedTooltip');
  20348. var tooltipDimLen = tooltipDims.length;
  20349. var value = series.getRawValue(dataIndex);
  20350. var isValueArr = isArray(value);
  20351. var markerColor = retrieveVisualColorForTooltipMarker(series, dataIndex); // Complicated rule for pretty tooltip.
  20352. var inlineValue;
  20353. var inlineValueType;
  20354. var subBlocks;
  20355. var sortParam;
  20356. if (tooltipDimLen > 1 || isValueArr && !tooltipDimLen) {
  20357. var formatArrResult = formatTooltipArrayValue(value, series, dataIndex, tooltipDims, markerColor);
  20358. inlineValue = formatArrResult.inlineValues;
  20359. inlineValueType = formatArrResult.inlineValueTypes;
  20360. subBlocks = formatArrResult.blocks; // Only support tooltip sort by the first inline value. It's enough in most cases.
  20361. sortParam = formatArrResult.inlineValues[0];
  20362. } else if (tooltipDimLen) {
  20363. var dimInfo = data.getDimensionInfo(tooltipDims[0]);
  20364. sortParam = inlineValue = retrieveRawValue(data, dataIndex, tooltipDims[0]);
  20365. inlineValueType = dimInfo.type;
  20366. } else {
  20367. sortParam = inlineValue = isValueArr ? value[0] : value;
  20368. } // Do not show generated series name. It might not be readable.
  20369. var seriesNameSpecified = isNameSpecified(series);
  20370. var seriesName = seriesNameSpecified && series.name || '';
  20371. var itemName = data.getName(dataIndex);
  20372. var inlineName = multipleSeries ? seriesName : itemName;
  20373. return createTooltipMarkup('section', {
  20374. header: seriesName,
  20375. // When series name not specified, do not show a header line with only '-'.
  20376. // This case alway happen in tooltip.trigger: 'item'.
  20377. noHeader: multipleSeries || !seriesNameSpecified,
  20378. sortParam: sortParam,
  20379. blocks: [createTooltipMarkup('nameValue', {
  20380. markerType: 'item',
  20381. markerColor: markerColor,
  20382. // Do not mix display seriesName and itemName in one tooltip,
  20383. // which might confuses users.
  20384. name: inlineName,
  20385. // name dimension might be auto assigned, where the name might
  20386. // be not readable. So we check trim here.
  20387. noName: !trim(inlineName),
  20388. value: inlineValue,
  20389. valueType: inlineValueType
  20390. })].concat(subBlocks || [])
  20391. });
  20392. }
  20393. function formatTooltipArrayValue(value, series, dataIndex, tooltipDims, colorStr) {
  20394. // check: category-no-encode-has-axis-data in dataset.html
  20395. var data = series.getData();
  20396. var isValueMultipleLine = reduce(value, function (isValueMultipleLine, val, idx) {
  20397. var dimItem = data.getDimensionInfo(idx);
  20398. return isValueMultipleLine = isValueMultipleLine || dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20399. }, false);
  20400. var inlineValues = [];
  20401. var inlineValueTypes = [];
  20402. var blocks = [];
  20403. tooltipDims.length ? each(tooltipDims, function (dim) {
  20404. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20405. }) // By default, all dims is used on tooltip.
  20406. : each(value, setEachItem);
  20407. function setEachItem(val, dim) {
  20408. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  20409. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20410. return;
  20411. }
  20412. if (isValueMultipleLine) {
  20413. blocks.push(createTooltipMarkup('nameValue', {
  20414. markerType: 'subItem',
  20415. markerColor: colorStr,
  20416. name: dimInfo.displayName,
  20417. value: val,
  20418. valueType: dimInfo.type
  20419. }));
  20420. } else {
  20421. inlineValues.push(val);
  20422. inlineValueTypes.push(dimInfo.type);
  20423. }
  20424. }
  20425. return {
  20426. inlineValues: inlineValues,
  20427. inlineValueTypes: inlineValueTypes,
  20428. blocks: blocks
  20429. };
  20430. }
  20431. var inner$1 = makeInner();
  20432. function getSelectionKey(data, dataIndex) {
  20433. return data.getName(dataIndex) || data.getId(dataIndex);
  20434. }
  20435. var SeriesModel =
  20436. /** @class */
  20437. function (_super) {
  20438. __extends(SeriesModel, _super);
  20439. function SeriesModel() {
  20440. // [Caution]: Becuase this class or desecendants can be used as `XXX.extend(subProto)`,
  20441. // the class members must not be initialized in constructor or declaration place.
  20442. // Otherwise there is bad case:
  20443. // class A {xxx = 1;}
  20444. // enableClassExtend(A);
  20445. // class B extends A {}
  20446. // var C = B.extend({xxx: 5});
  20447. // var c = new C();
  20448. // console.log(c.xxx); // expect 5 but always 1.
  20449. var _this = _super !== null && _super.apply(this, arguments) || this; // ---------------------------------------
  20450. // Props about data selection
  20451. // ---------------------------------------
  20452. _this._selectedDataIndicesMap = {};
  20453. return _this;
  20454. }
  20455. SeriesModel.prototype.init = function (option, parentModel, ecModel) {
  20456. this.seriesIndex = this.componentIndex;
  20457. this.dataTask = createTask({
  20458. count: dataTaskCount,
  20459. reset: dataTaskReset
  20460. });
  20461. this.dataTask.context = {
  20462. model: this
  20463. };
  20464. this.mergeDefaultAndTheme(option, ecModel);
  20465. var sourceManager = inner$1(this).sourceManager = new SourceManager(this);
  20466. sourceManager.prepareSource();
  20467. var data = this.getInitialData(option, ecModel);
  20468. wrapData(data, this);
  20469. this.dataTask.context.data = data;
  20470. if ("development" !== 'production') {
  20471. assert(data, 'getInitialData returned invalid data.');
  20472. }
  20473. inner$1(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  20474. // dataBeforeProcessed by cloneShallow), cloneShallow will
  20475. // cause data.graph.data !== data when using
  20476. // module:echarts/data/Graph or module:echarts/data/Tree.
  20477. // See module:echarts/data/helper/linkList
  20478. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  20479. // init or merge stage, because the data can be restored. So we do not `restoreData`
  20480. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  20481. // Call `seriesModel.getRawData()` instead.
  20482. // this.restoreData();
  20483. autoSeriesName(this);
  20484. this._initSelectedMapFromData(data);
  20485. };
  20486. /**
  20487. * Util for merge default and theme to option
  20488. */
  20489. SeriesModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  20490. var layoutMode = fetchLayoutMode(this);
  20491. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  20492. // But if name duplicate between series subType
  20493. // (for example: parallel) add component mainType,
  20494. // add suffix 'Series'.
  20495. var themeSubType = this.subType;
  20496. if (ComponentModel.hasClass(themeSubType)) {
  20497. themeSubType += 'Series';
  20498. }
  20499. merge(option, ecModel.getTheme().get(this.subType));
  20500. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  20501. defaultEmphasis(option, 'label', ['show']);
  20502. this.fillDataTextStyle(option.data);
  20503. if (layoutMode) {
  20504. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20505. }
  20506. };
  20507. SeriesModel.prototype.mergeOption = function (newSeriesOption, ecModel) {
  20508. // this.settingTask.dirty();
  20509. newSeriesOption = merge(this.option, newSeriesOption, true);
  20510. this.fillDataTextStyle(newSeriesOption.data);
  20511. var layoutMode = fetchLayoutMode(this);
  20512. if (layoutMode) {
  20513. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20514. }
  20515. var sourceManager = inner$1(this).sourceManager;
  20516. sourceManager.dirty();
  20517. sourceManager.prepareSource();
  20518. var data = this.getInitialData(newSeriesOption, ecModel);
  20519. wrapData(data, this);
  20520. this.dataTask.dirty();
  20521. this.dataTask.context.data = data;
  20522. inner$1(this).dataBeforeProcessed = data;
  20523. autoSeriesName(this);
  20524. this._initSelectedMapFromData(data);
  20525. };
  20526. SeriesModel.prototype.fillDataTextStyle = function (data) {
  20527. // Default data label emphasis `show`
  20528. // FIXME Tree structure data ?
  20529. // FIXME Performance ?
  20530. if (data && !isTypedArray(data)) {
  20531. var props = ['show'];
  20532. for (var i = 0; i < data.length; i++) {
  20533. if (data[i] && data[i].label) {
  20534. defaultEmphasis(data[i], 'label', props);
  20535. }
  20536. }
  20537. }
  20538. };
  20539. /**
  20540. * Init a data structure from data related option in series
  20541. * Must be overriden.
  20542. */
  20543. SeriesModel.prototype.getInitialData = function (option, ecModel) {
  20544. return;
  20545. };
  20546. /**
  20547. * Append data to list
  20548. */
  20549. SeriesModel.prototype.appendData = function (params) {
  20550. // FIXME ???
  20551. // (1) If data from dataset, forbidden append.
  20552. // (2) support append data of dataset.
  20553. var data = this.getRawData();
  20554. data.appendData(params.data);
  20555. };
  20556. /**
  20557. * Consider some method like `filter`, `map` need make new data,
  20558. * We should make sure that `seriesModel.getData()` get correct
  20559. * data in the stream procedure. So we fetch data from upstream
  20560. * each time `task.perform` called.
  20561. */
  20562. SeriesModel.prototype.getData = function (dataType) {
  20563. var task = getCurrentTask(this);
  20564. if (task) {
  20565. var data = task.context.data;
  20566. return dataType == null ? data : data.getLinkedData(dataType);
  20567. } else {
  20568. // When series is not alive (that may happen when click toolbox
  20569. // restore or setOption with not merge mode), series data may
  20570. // be still need to judge animation or something when graphic
  20571. // elements want to know whether fade out.
  20572. return inner$1(this).data;
  20573. }
  20574. };
  20575. SeriesModel.prototype.getAllData = function () {
  20576. var mainData = this.getData();
  20577. return mainData && mainData.getLinkedDataAll ? mainData.getLinkedDataAll() : [{
  20578. data: mainData
  20579. }];
  20580. };
  20581. SeriesModel.prototype.setData = function (data) {
  20582. var task = getCurrentTask(this);
  20583. if (task) {
  20584. var context = task.context; // Consider case: filter, data sample.
  20585. // FIXME:TS never used, so comment it
  20586. // if (context.data !== data && task.modifyOutputEnd) {
  20587. // task.setOutputEnd(data.count());
  20588. // }
  20589. context.outputData = data; // Caution: setData should update context.data,
  20590. // Because getData may be called multiply in a
  20591. // single stage and expect to get the data just
  20592. // set. (For example, AxisProxy, x y both call
  20593. // getData and setDate sequentially).
  20594. // So the context.data should be fetched from
  20595. // upstream each time when a stage starts to be
  20596. // performed.
  20597. if (task !== this.dataTask) {
  20598. context.data = data;
  20599. }
  20600. }
  20601. inner$1(this).data = data;
  20602. };
  20603. SeriesModel.prototype.getSource = function () {
  20604. return inner$1(this).sourceManager.getSource();
  20605. };
  20606. /**
  20607. * Get data before processed
  20608. */
  20609. SeriesModel.prototype.getRawData = function () {
  20610. return inner$1(this).dataBeforeProcessed;
  20611. };
  20612. /**
  20613. * Get base axis if has coordinate system and has axis.
  20614. * By default use coordSys.getBaseAxis();
  20615. * Can be overrided for some chart.
  20616. * @return {type} description
  20617. */
  20618. SeriesModel.prototype.getBaseAxis = function () {
  20619. var coordSys = this.coordinateSystem; // @ts-ignore
  20620. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20621. };
  20622. /**
  20623. * Default tooltip formatter
  20624. *
  20625. * @param dataIndex
  20626. * @param multipleSeries
  20627. * @param dataType
  20628. * @param renderMode valid values: 'html'(by default) and 'richText'.
  20629. * 'html' is used for rendering tooltip in extra DOM form, and the result
  20630. * string is used as DOM HTML content.
  20631. * 'richText' is used for rendering tooltip in rich text form, for those where
  20632. * DOM operation is not supported.
  20633. * @return formatted tooltip with `html` and `markers`
  20634. * Notice: The override method can also return string
  20635. */
  20636. SeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  20637. return defaultSeriesFormatTooltip({
  20638. series: this,
  20639. dataIndex: dataIndex,
  20640. multipleSeries: multipleSeries
  20641. });
  20642. };
  20643. SeriesModel.prototype.isAnimationEnabled = function () {
  20644. if (env.node) {
  20645. return false;
  20646. }
  20647. var animationEnabled = this.getShallow('animation');
  20648. if (animationEnabled) {
  20649. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20650. animationEnabled = false;
  20651. }
  20652. }
  20653. return !!animationEnabled;
  20654. };
  20655. SeriesModel.prototype.restoreData = function () {
  20656. this.dataTask.dirty();
  20657. };
  20658. SeriesModel.prototype.getColorFromPalette = function (name, scope, requestColorNum) {
  20659. var ecModel = this.ecModel; // PENDING
  20660. var color = PaletteMixin.prototype.getColorFromPalette.call(this, name, scope, requestColorNum);
  20661. if (!color) {
  20662. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20663. }
  20664. return color;
  20665. };
  20666. /**
  20667. * Use `data.mapDimensionsAll(coordDim)` instead.
  20668. * @deprecated
  20669. */
  20670. SeriesModel.prototype.coordDimToDataDim = function (coordDim) {
  20671. return this.getRawData().mapDimensionsAll(coordDim);
  20672. };
  20673. /**
  20674. * Get progressive rendering count each step
  20675. */
  20676. SeriesModel.prototype.getProgressive = function () {
  20677. return this.get('progressive');
  20678. };
  20679. /**
  20680. * Get progressive rendering count each step
  20681. */
  20682. SeriesModel.prototype.getProgressiveThreshold = function () {
  20683. return this.get('progressiveThreshold');
  20684. }; // PENGING If selectedMode is null ?
  20685. SeriesModel.prototype.select = function (innerDataIndices, dataType) {
  20686. this._innerSelect(this.getData(dataType), innerDataIndices);
  20687. };
  20688. SeriesModel.prototype.unselect = function (innerDataIndices, dataType) {
  20689. var selectedMap = this.option.selectedMap;
  20690. if (!selectedMap) {
  20691. return;
  20692. }
  20693. var data = this.getData(dataType);
  20694. for (var i = 0; i < innerDataIndices.length; i++) {
  20695. var dataIndex = innerDataIndices[i];
  20696. var nameOrId = getSelectionKey(data, dataIndex);
  20697. selectedMap[nameOrId] = false;
  20698. this._selectedDataIndicesMap[nameOrId] = -1;
  20699. }
  20700. };
  20701. SeriesModel.prototype.toggleSelect = function (innerDataIndices, dataType) {
  20702. var tmpArr = [];
  20703. for (var i = 0; i < innerDataIndices.length; i++) {
  20704. tmpArr[0] = innerDataIndices[i];
  20705. this.isSelected(innerDataIndices[i], dataType) ? this.unselect(tmpArr, dataType) : this.select(tmpArr, dataType);
  20706. }
  20707. };
  20708. SeriesModel.prototype.getSelectedDataIndices = function () {
  20709. var selectedDataIndicesMap = this._selectedDataIndicesMap;
  20710. var nameOrIds = keys(selectedDataIndicesMap);
  20711. var dataIndices = [];
  20712. for (var i = 0; i < nameOrIds.length; i++) {
  20713. var dataIndex = selectedDataIndicesMap[nameOrIds[i]];
  20714. if (dataIndex >= 0) {
  20715. dataIndices.push(dataIndex);
  20716. }
  20717. }
  20718. return dataIndices;
  20719. };
  20720. SeriesModel.prototype.isSelected = function (dataIndex, dataType) {
  20721. var selectedMap = this.option.selectedMap;
  20722. if (!selectedMap) {
  20723. return false;
  20724. }
  20725. var data = this.getData(dataType);
  20726. var nameOrId = getSelectionKey(data, dataIndex);
  20727. return selectedMap[nameOrId] || false;
  20728. };
  20729. SeriesModel.prototype._innerSelect = function (data, innerDataIndices) {
  20730. var _a, _b;
  20731. var selectedMode = this.option.selectedMode;
  20732. var len = innerDataIndices.length;
  20733. if (!selectedMode || !len) {
  20734. return;
  20735. }
  20736. if (selectedMode === 'multiple') {
  20737. var selectedMap = this.option.selectedMap || (this.option.selectedMap = {});
  20738. for (var i = 0; i < len; i++) {
  20739. var dataIndex = innerDataIndices[i]; // TODO diffrent types of data share same object.
  20740. var nameOrId = getSelectionKey(data, dataIndex);
  20741. selectedMap[nameOrId] = true;
  20742. this._selectedDataIndicesMap[nameOrId] = data.getRawIndex(dataIndex);
  20743. }
  20744. } else if (selectedMode === 'single' || selectedMode === true) {
  20745. var lastDataIndex = innerDataIndices[len - 1];
  20746. var nameOrId = getSelectionKey(data, lastDataIndex);
  20747. this.option.selectedMap = (_a = {}, _a[nameOrId] = true, _a);
  20748. this._selectedDataIndicesMap = (_b = {}, _b[nameOrId] = data.getRawIndex(lastDataIndex), _b);
  20749. }
  20750. };
  20751. SeriesModel.prototype._initSelectedMapFromData = function (data) {
  20752. // Ignore select info in data if selectedMap exists.
  20753. // NOTE It's only for legacy usage. edge data is not supported.
  20754. if (this.option.selectedMap) {
  20755. return;
  20756. }
  20757. var dataIndices = [];
  20758. if (data.hasItemOption) {
  20759. data.each(function (idx) {
  20760. var rawItem = data.getRawDataItem(idx);
  20761. if (typeof rawItem === 'object' && rawItem.selected) {
  20762. dataIndices.push(idx);
  20763. }
  20764. });
  20765. }
  20766. if (dataIndices.length > 0) {
  20767. this._innerSelect(data, dataIndices);
  20768. }
  20769. }; // /**
  20770. // * @see {module:echarts/stream/Scheduler}
  20771. // */
  20772. // abstract pipeTask: null
  20773. SeriesModel.registerClass = function (clz) {
  20774. return ComponentModel.registerClass(clz);
  20775. };
  20776. SeriesModel.protoInitialize = function () {
  20777. var proto = SeriesModel.prototype;
  20778. proto.type = 'series.__base__';
  20779. proto.seriesIndex = 0;
  20780. proto.useColorPaletteOnData = false;
  20781. proto.ignoreStyleOnData = false;
  20782. proto.hasSymbolVisual = false;
  20783. proto.defaultSymbol = 'circle'; // Make sure the values can be accessed!
  20784. proto.visualStyleAccessPath = 'itemStyle';
  20785. proto.visualDrawType = 'fill';
  20786. }();
  20787. return SeriesModel;
  20788. }(ComponentModel);
  20789. mixin(SeriesModel, DataFormatMixin);
  20790. mixin(SeriesModel, PaletteMixin);
  20791. mountExtend(SeriesModel, ComponentModel);
  20792. /**
  20793. * MUST be called after `prepareSource` called
  20794. * Here we need to make auto series, especially for auto legend. But we
  20795. * do not modify series.name in option to avoid side effects.
  20796. */
  20797. function autoSeriesName(seriesModel) {
  20798. // User specified name has higher priority, otherwise it may cause
  20799. // series can not be queried unexpectedly.
  20800. var name = seriesModel.name;
  20801. if (!isNameSpecified(seriesModel)) {
  20802. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20803. }
  20804. }
  20805. function getSeriesAutoName(seriesModel) {
  20806. var data = seriesModel.getRawData();
  20807. var dataDims = data.mapDimensionsAll('seriesName');
  20808. var nameArr = [];
  20809. each(dataDims, function (dataDim) {
  20810. var dimInfo = data.getDimensionInfo(dataDim);
  20811. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20812. });
  20813. return nameArr.join(' ');
  20814. }
  20815. function dataTaskCount(context) {
  20816. return context.model.getRawData().count();
  20817. }
  20818. function dataTaskReset(context) {
  20819. var seriesModel = context.model;
  20820. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20821. return dataTaskProgress;
  20822. }
  20823. function dataTaskProgress(param, context) {
  20824. // Avoid repead cloneShallow when data just created in reset.
  20825. if (context.outputData && param.end > context.outputData.count()) {
  20826. context.model.getRawData().cloneShallow(context.outputData);
  20827. }
  20828. } // TODO refactor
  20829. function wrapData(data, seriesModel) {
  20830. each(__spreadArrays(data.CHANGABLE_METHODS, data.DOWNSAMPLE_METHODS), function (methodName) {
  20831. data.wrapMethod(methodName, curry(onDataChange, seriesModel));
  20832. });
  20833. }
  20834. function onDataChange(seriesModel, newList) {
  20835. var task = getCurrentTask(seriesModel);
  20836. if (task) {
  20837. // Consider case: filter, selectRange
  20838. task.setOutputEnd((newList || this).count());
  20839. }
  20840. return newList;
  20841. }
  20842. function getCurrentTask(seriesModel) {
  20843. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20844. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20845. if (pipeline) {
  20846. // When pipline finished, the currrentTask keep the last
  20847. // task (renderTask).
  20848. var task = pipeline.currentTask;
  20849. if (task) {
  20850. var agentStubMap = task.agentStubMap;
  20851. if (agentStubMap) {
  20852. task = agentStubMap.get(seriesModel.uid);
  20853. }
  20854. }
  20855. return task;
  20856. }
  20857. }
  20858. var ComponentView =
  20859. /** @class */
  20860. function () {
  20861. function ComponentView() {
  20862. this.group = new Group();
  20863. this.uid = getUID('viewComponent');
  20864. }
  20865. ComponentView.prototype.init = function (ecModel, api) {};
  20866. ComponentView.prototype.render = function (model, ecModel, api, payload) {};
  20867. ComponentView.prototype.dispose = function (ecModel, api) {};
  20868. ComponentView.prototype.updateView = function (model, ecModel, api, payload) {// Do nothing;
  20869. };
  20870. ComponentView.prototype.updateLayout = function (model, ecModel, api, payload) {// Do nothing;
  20871. };
  20872. ComponentView.prototype.updateVisual = function (model, ecModel, api, payload) {// Do nothing;
  20873. };
  20874. /**
  20875. * Hook for blur target series.
  20876. * Can be used in marker for blur the markers
  20877. */
  20878. ComponentView.prototype.blurSeries = function (seriesModels, ecModel) {// Do nothing;
  20879. };
  20880. return ComponentView;
  20881. }();
  20882. enableClassExtend(ComponentView);
  20883. enableClassManagement(ComponentView);
  20884. /**
  20885. * @return {string} If large mode changed, return string 'reset';
  20886. */
  20887. function createRenderPlanner() {
  20888. var inner = makeInner();
  20889. return function (seriesModel) {
  20890. var fields = inner(seriesModel);
  20891. var pipelineContext = seriesModel.pipelineContext;
  20892. var originalLarge = !!fields.large;
  20893. var originalProgressive = !!fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  20894. // exists. See #11611 . Probably we need to modify this structure, see the comment
  20895. // on `performRawSeries` in `Schedular.js`.
  20896. var large = fields.large = !!(pipelineContext && pipelineContext.large);
  20897. var progressive = fields.progressiveRender = !!(pipelineContext && pipelineContext.progressiveRender);
  20898. return !!(originalLarge !== large || originalProgressive !== progressive) && 'reset';
  20899. };
  20900. }
  20901. var inner$2 = makeInner();
  20902. var renderPlanner = createRenderPlanner();
  20903. var ChartView =
  20904. /** @class */
  20905. function () {
  20906. function ChartView() {
  20907. this.group = new Group();
  20908. this.uid = getUID('viewChart');
  20909. this.renderTask = createTask({
  20910. plan: renderTaskPlan,
  20911. reset: renderTaskReset
  20912. });
  20913. this.renderTask.context = {
  20914. view: this
  20915. };
  20916. }
  20917. ChartView.prototype.init = function (ecModel, api) {};
  20918. ChartView.prototype.render = function (seriesModel, ecModel, api, payload) {};
  20919. /**
  20920. * Highlight series or specified data item.
  20921. */
  20922. ChartView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  20923. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20924. };
  20925. /**
  20926. * Downplay series or specified data item.
  20927. */
  20928. ChartView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  20929. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20930. };
  20931. /**
  20932. * Remove self.
  20933. */
  20934. ChartView.prototype.remove = function (ecModel, api) {
  20935. this.group.removeAll();
  20936. };
  20937. /**
  20938. * Dispose self.
  20939. */
  20940. ChartView.prototype.dispose = function (ecModel, api) {};
  20941. ChartView.prototype.updateView = function (seriesModel, ecModel, api, payload) {
  20942. this.render(seriesModel, ecModel, api, payload);
  20943. }; // FIXME never used?
  20944. ChartView.prototype.updateLayout = function (seriesModel, ecModel, api, payload) {
  20945. this.render(seriesModel, ecModel, api, payload);
  20946. }; // FIXME never used?
  20947. ChartView.prototype.updateVisual = function (seriesModel, ecModel, api, payload) {
  20948. this.render(seriesModel, ecModel, api, payload);
  20949. };
  20950. ChartView.markUpdateMethod = function (payload, methodName) {
  20951. inner$2(payload).updateMethod = methodName;
  20952. };
  20953. ChartView.protoInitialize = function () {
  20954. var proto = ChartView.prototype;
  20955. proto.type = 'chart';
  20956. }();
  20957. return ChartView;
  20958. }();
  20959. /**
  20960. * Set state of single element
  20961. */
  20962. function elSetState(el, state, highlightDigit) {
  20963. if (el) {
  20964. (state === 'emphasis' ? enterEmphasis : leaveEmphasis)(el, highlightDigit);
  20965. }
  20966. }
  20967. function toggleHighlight(data, payload, state) {
  20968. var dataIndex = queryDataIndex(data, payload);
  20969. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  20970. if (dataIndex != null) {
  20971. each(normalizeToArray(dataIndex), function (dataIdx) {
  20972. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  20973. });
  20974. } else {
  20975. data.eachItemGraphicEl(function (el) {
  20976. elSetState(el, state, highlightDigit);
  20977. });
  20978. }
  20979. }
  20980. enableClassExtend(ChartView, ['dispose']);
  20981. enableClassManagement(ChartView);
  20982. function renderTaskPlan(context) {
  20983. return renderPlanner(context.model);
  20984. }
  20985. function renderTaskReset(context) {
  20986. var seriesModel = context.model;
  20987. var ecModel = context.ecModel;
  20988. var api = context.api;
  20989. var payload = context.payload; // FIXME: remove updateView updateVisual
  20990. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20991. var view = context.view;
  20992. var updateMethod = payload && inner$2(payload).updateMethod;
  20993. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  20994. // is less than progressive threshold.
  20995. : 'render';
  20996. if (methodName !== 'render') {
  20997. view[methodName](seriesModel, ecModel, api, payload);
  20998. }
  20999. return progressMethodMap[methodName];
  21000. }
  21001. var progressMethodMap = {
  21002. incrementalPrepareRender: {
  21003. progress: function (params, context) {
  21004. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  21005. }
  21006. },
  21007. render: {
  21008. // Put view.render in `progress` to support appendData. But in this case
  21009. // view.render should not be called in reset, otherwise it will be called
  21010. // twise. Use `forceFirstProgress` to make sure that view.render is called
  21011. // in any cases.
  21012. forceFirstProgress: true,
  21013. progress: function (params, context) {
  21014. context.view.render(context.model, context.ecModel, context.api, context.payload);
  21015. }
  21016. }
  21017. };
  21018. /*
  21019. * Licensed to the Apache Software Foundation (ASF) under one
  21020. * or more contributor license agreements. See the NOTICE file
  21021. * distributed with this work for additional information
  21022. * regarding copyright ownership. The ASF licenses this file
  21023. * to you under the Apache License, Version 2.0 (the
  21024. * "License"); you may not use this file except in compliance
  21025. * with the License. You may obtain a copy of the License at
  21026. *
  21027. * http://www.apache.org/licenses/LICENSE-2.0
  21028. *
  21029. * Unless required by applicable law or agreed to in writing,
  21030. * software distributed under the License is distributed on an
  21031. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21032. * KIND, either express or implied. See the License for the
  21033. * specific language governing permissions and limitations
  21034. * under the License.
  21035. */
  21036. /**
  21037. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21038. */
  21039. /*
  21040. * Licensed to the Apache Software Foundation (ASF) under one
  21041. * or more contributor license agreements. See the NOTICE file
  21042. * distributed with this work for additional information
  21043. * regarding copyright ownership. The ASF licenses this file
  21044. * to you under the Apache License, Version 2.0 (the
  21045. * "License"); you may not use this file except in compliance
  21046. * with the License. You may obtain a copy of the License at
  21047. *
  21048. * http://www.apache.org/licenses/LICENSE-2.0
  21049. *
  21050. * Unless required by applicable law or agreed to in writing,
  21051. * software distributed under the License is distributed on an
  21052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21053. * KIND, either express or implied. See the License for the
  21054. * specific language governing permissions and limitations
  21055. * under the License.
  21056. */
  21057. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  21058. var RATE = '\0__throttleRate';
  21059. var THROTTLE_TYPE = '\0__throttleType';
  21060. /**
  21061. * @public
  21062. * @param {(Function)} fn
  21063. * @param {number} [delay=0] Unit: ms.
  21064. * @param {boolean} [debounce=false]
  21065. * true: If call interval less than `delay`, only the last call works.
  21066. * false: If call interval less than `delay, call works on fixed rate.
  21067. * @return {(Function)} throttled fn.
  21068. */
  21069. function throttle(fn, delay, debounce) {
  21070. var currCall;
  21071. var lastCall = 0;
  21072. var lastExec = 0;
  21073. var timer = null;
  21074. var diff;
  21075. var scope;
  21076. var args;
  21077. var debounceNextCall;
  21078. delay = delay || 0;
  21079. function exec() {
  21080. lastExec = new Date().getTime();
  21081. timer = null;
  21082. fn.apply(scope, args || []);
  21083. }
  21084. var cb = function () {
  21085. var cbArgs = [];
  21086. for (var _i = 0; _i < arguments.length; _i++) {
  21087. cbArgs[_i] = arguments[_i];
  21088. }
  21089. currCall = new Date().getTime();
  21090. scope = this;
  21091. args = cbArgs;
  21092. var thisDelay = debounceNextCall || delay;
  21093. var thisDebounce = debounceNextCall || debounce;
  21094. debounceNextCall = null;
  21095. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  21096. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  21097. // than a new call of `cb`, that is, preserving the command order. Consider
  21098. // calculating "scale rate" when roaming as an example. When a call of `cb`
  21099. // happens, either the `exec` is called dierectly, or the call is delayed.
  21100. // But the delayed call should never be later than next call of `cb`. Under
  21101. // this assurance, we can simply update view state each time `dispatchAction`
  21102. // triggered by user roaming, but not need to add extra code to avoid the
  21103. // state being "rolled-back".
  21104. if (thisDebounce) {
  21105. timer = setTimeout(exec, thisDelay);
  21106. } else {
  21107. if (diff >= 0) {
  21108. exec();
  21109. } else {
  21110. timer = setTimeout(exec, -diff);
  21111. }
  21112. }
  21113. lastCall = currCall;
  21114. };
  21115. /**
  21116. * Clear throttle.
  21117. * @public
  21118. */
  21119. cb.clear = function () {
  21120. if (timer) {
  21121. clearTimeout(timer);
  21122. timer = null;
  21123. }
  21124. };
  21125. /**
  21126. * Enable debounce once.
  21127. */
  21128. cb.debounceNextCall = function (debounceDelay) {
  21129. debounceNextCall = debounceDelay;
  21130. };
  21131. return cb;
  21132. }
  21133. /**
  21134. * Create throttle method or update throttle rate.
  21135. *
  21136. * @example
  21137. * ComponentView.prototype.render = function () {
  21138. * ...
  21139. * throttle.createOrUpdate(
  21140. * this,
  21141. * '_dispatchAction',
  21142. * this.model.get('throttle'),
  21143. * 'fixRate'
  21144. * );
  21145. * };
  21146. * ComponentView.prototype.remove = function () {
  21147. * throttle.clear(this, '_dispatchAction');
  21148. * };
  21149. * ComponentView.prototype.dispose = function () {
  21150. * throttle.clear(this, '_dispatchAction');
  21151. * };
  21152. *
  21153. */
  21154. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  21155. var fn = obj[fnAttr];
  21156. if (!fn) {
  21157. return;
  21158. }
  21159. var originFn = fn[ORIGIN_METHOD] || fn;
  21160. var lastThrottleType = fn[THROTTLE_TYPE];
  21161. var lastRate = fn[RATE];
  21162. if (lastRate !== rate || lastThrottleType !== throttleType) {
  21163. if (rate == null || !throttleType) {
  21164. return obj[fnAttr] = originFn;
  21165. }
  21166. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  21167. fn[ORIGIN_METHOD] = originFn;
  21168. fn[THROTTLE_TYPE] = throttleType;
  21169. fn[RATE] = rate;
  21170. }
  21171. return fn;
  21172. }
  21173. /**
  21174. * Clear throttle. Example see throttle.createOrUpdate.
  21175. */
  21176. function clear(obj, fnAttr) {
  21177. var fn = obj[fnAttr];
  21178. if (fn && fn[ORIGIN_METHOD]) {
  21179. obj[fnAttr] = fn[ORIGIN_METHOD];
  21180. }
  21181. }
  21182. var inner$3 = makeInner();
  21183. var defaultStyleMappers = {
  21184. itemStyle: makeStyleMapper(ITEM_STYLE_KEY_MAP, true),
  21185. lineStyle: makeStyleMapper(LINE_STYLE_KEY_MAP, true)
  21186. };
  21187. var defaultColorKey = {
  21188. lineStyle: 'stroke',
  21189. itemStyle: 'fill'
  21190. };
  21191. function getStyleMapper(seriesModel, stylePath) {
  21192. var styleMapper = seriesModel.visualStyleMapper || defaultStyleMappers[stylePath];
  21193. if (!styleMapper) {
  21194. console.warn("Unkown style type '" + stylePath + "'.");
  21195. return defaultStyleMappers.itemStyle;
  21196. }
  21197. return styleMapper;
  21198. }
  21199. function getDefaultColorKey(seriesModel, stylePath) {
  21200. // return defaultColorKey[stylePath] ||
  21201. var colorKey = seriesModel.visualDrawType || defaultColorKey[stylePath];
  21202. if (!colorKey) {
  21203. console.warn("Unkown style type '" + stylePath + "'.");
  21204. return 'fill';
  21205. }
  21206. return colorKey;
  21207. }
  21208. var seriesStyleTask = {
  21209. createOnAllSeries: true,
  21210. performRawSeries: true,
  21211. reset: function (seriesModel, ecModel) {
  21212. var data = seriesModel.getData();
  21213. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21214. var styleModel = seriesModel.getModel(stylePath);
  21215. var getStyle = getStyleMapper(seriesModel, stylePath);
  21216. var globalStyle = getStyle(styleModel);
  21217. var decalOption = styleModel.getShallow('decal');
  21218. if (decalOption) {
  21219. data.setVisual('decal', decalOption);
  21220. decalOption.dirty = true;
  21221. } // TODO
  21222. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21223. var color = globalStyle[colorKey]; // TODO style callback
  21224. var colorCallback = isFunction(color) ? color : null; // Get from color palette by default.
  21225. if (!globalStyle[colorKey] || colorCallback) {
  21226. // Note: if some series has color specified (e.g., by itemStyle.color), we DO NOT
  21227. // make it effect palette. Bacause some scenarios users need to make some series
  21228. // transparent or as background, which should better not effect the palette.
  21229. globalStyle[colorKey] = seriesModel.getColorFromPalette( // TODO series count changed.
  21230. seriesModel.name, null, ecModel.getSeriesCount());
  21231. data.setVisual('colorFromPalette', true);
  21232. }
  21233. data.setVisual('style', globalStyle);
  21234. data.setVisual('drawType', colorKey); // Only visible series has each data be visual encoded
  21235. if (!ecModel.isSeriesFiltered(seriesModel) && colorCallback) {
  21236. data.setVisual('colorFromPalette', false);
  21237. return {
  21238. dataEach: function (data, idx) {
  21239. var dataParams = seriesModel.getDataParams(idx);
  21240. var itemStyle = extend({}, globalStyle);
  21241. itemStyle[colorKey] = colorCallback(dataParams);
  21242. data.setItemVisual(idx, 'style', itemStyle);
  21243. }
  21244. };
  21245. }
  21246. }
  21247. };
  21248. var sharedModel = new Model();
  21249. var dataStyleTask = {
  21250. createOnAllSeries: true,
  21251. performRawSeries: true,
  21252. reset: function (seriesModel, ecModel) {
  21253. if (seriesModel.ignoreStyleOnData || ecModel.isSeriesFiltered(seriesModel)) {
  21254. return;
  21255. }
  21256. var data = seriesModel.getData();
  21257. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle'; // Set in itemStyle
  21258. var getStyle = getStyleMapper(seriesModel, stylePath);
  21259. var colorKey = data.getVisual('drawType');
  21260. return {
  21261. dataEach: data.hasItemOption ? function (data, idx) {
  21262. // Not use getItemModel for performance considuration
  21263. var rawItem = data.getRawDataItem(idx);
  21264. if (rawItem && rawItem[stylePath]) {
  21265. sharedModel.option = rawItem[stylePath];
  21266. var style = getStyle(sharedModel);
  21267. var existsStyle = data.ensureUniqueItemVisual(idx, 'style');
  21268. extend(existsStyle, style);
  21269. if (sharedModel.option.decal) {
  21270. data.setItemVisual(idx, 'decal', sharedModel.option.decal);
  21271. sharedModel.option.decal.dirty = true;
  21272. }
  21273. if (colorKey in style) {
  21274. data.setItemVisual(idx, 'colorFromPalette', false);
  21275. }
  21276. }
  21277. } : null
  21278. };
  21279. }
  21280. }; // Pick color from palette for the data which has not been set with color yet.
  21281. // Note: do not support stream rendering. No such cases yet.
  21282. var dataColorPaletteTask = {
  21283. performRawSeries: true,
  21284. overallReset: function (ecModel) {
  21285. // Each type of series use one scope.
  21286. // Pie and funnel are using diferrent scopes
  21287. var paletteScopeGroupByType = createHashMap();
  21288. ecModel.eachSeries(function (seriesModel) {
  21289. if (!seriesModel.useColorPaletteOnData) {
  21290. return;
  21291. }
  21292. var colorScope = paletteScopeGroupByType.get(seriesModel.type);
  21293. if (!colorScope) {
  21294. colorScope = {};
  21295. paletteScopeGroupByType.set(seriesModel.type, colorScope);
  21296. }
  21297. inner$3(seriesModel).scope = colorScope;
  21298. });
  21299. ecModel.eachSeries(function (seriesModel) {
  21300. if (!seriesModel.useColorPaletteOnData || ecModel.isSeriesFiltered(seriesModel)) {
  21301. return;
  21302. }
  21303. var dataAll = seriesModel.getRawData();
  21304. var idxMap = {};
  21305. var data = seriesModel.getData();
  21306. var colorScope = inner$3(seriesModel).scope;
  21307. var stylePath = seriesModel.visualStyleAccessPath || 'itemStyle';
  21308. var colorKey = getDefaultColorKey(seriesModel, stylePath);
  21309. data.each(function (idx) {
  21310. var rawIdx = data.getRawIndex(idx);
  21311. idxMap[rawIdx] = idx;
  21312. }); // Iterate on data before filtered. To make sure color from palette can be
  21313. // Consistent when toggling legend.
  21314. dataAll.each(function (rawIdx) {
  21315. var idx = idxMap[rawIdx];
  21316. var fromPalette = data.getItemVisual(idx, 'colorFromPalette'); // Get color from palette for each data only when the color is inherited from series color, which is
  21317. // also picked from color palette. So following situation is not in the case:
  21318. // 1. series.itemStyle.color is set
  21319. // 2. color is encoded by visualMap
  21320. if (fromPalette) {
  21321. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  21322. var name_1 = dataAll.getName(rawIdx) || rawIdx + '';
  21323. var dataCount = dataAll.count();
  21324. itemStyle[colorKey] = seriesModel.getColorFromPalette(name_1, colorScope, dataCount);
  21325. }
  21326. });
  21327. });
  21328. }
  21329. };
  21330. var PI$3 = Math.PI;
  21331. /**
  21332. * @param {module:echarts/ExtensionAPI} api
  21333. * @param {Object} [opts]
  21334. * @param {string} [opts.text]
  21335. * @param {string} [opts.color]
  21336. * @param {string} [opts.textColor]
  21337. * @return {module:zrender/Element}
  21338. */
  21339. function defaultLoading(api, opts) {
  21340. opts = opts || {};
  21341. defaults(opts, {
  21342. text: 'loading',
  21343. textColor: '#000',
  21344. fontSize: 12,
  21345. fontWeight: 'normal',
  21346. fontStyle: 'normal',
  21347. fontFamily: 'sans-serif',
  21348. maskColor: 'rgba(255, 255, 255, 0.8)',
  21349. showSpinner: true,
  21350. color: '#5470c6',
  21351. spinnerRadius: 10,
  21352. lineWidth: 5,
  21353. zlevel: 0
  21354. });
  21355. var group = new Group();
  21356. var mask = new Rect({
  21357. style: {
  21358. fill: opts.maskColor
  21359. },
  21360. zlevel: opts.zlevel,
  21361. z: 10000
  21362. });
  21363. group.add(mask);
  21364. var textContent = new ZRText({
  21365. style: {
  21366. text: opts.text,
  21367. fill: opts.textColor,
  21368. fontSize: opts.fontSize,
  21369. fontWeight: opts.fontWeight,
  21370. fontStyle: opts.fontStyle,
  21371. fontFamily: opts.fontFamily
  21372. }
  21373. });
  21374. var labelRect = new Rect({
  21375. style: {
  21376. fill: 'none'
  21377. },
  21378. textContent: textContent,
  21379. textConfig: {
  21380. position: 'right',
  21381. distance: 10
  21382. },
  21383. zlevel: opts.zlevel,
  21384. z: 10001
  21385. });
  21386. group.add(labelRect);
  21387. var arc;
  21388. if (opts.showSpinner) {
  21389. arc = new Arc({
  21390. shape: {
  21391. startAngle: -PI$3 / 2,
  21392. endAngle: -PI$3 / 2 + 0.1,
  21393. r: opts.spinnerRadius
  21394. },
  21395. style: {
  21396. stroke: opts.color,
  21397. lineCap: 'round',
  21398. lineWidth: opts.lineWidth
  21399. },
  21400. zlevel: opts.zlevel,
  21401. z: 10001
  21402. });
  21403. arc.animateShape(true).when(1000, {
  21404. endAngle: PI$3 * 3 / 2
  21405. }).start('circularInOut');
  21406. arc.animateShape(true).when(1000, {
  21407. startAngle: PI$3 * 3 / 2
  21408. }).delay(300).start('circularInOut');
  21409. group.add(arc);
  21410. } // Inject resize
  21411. group.resize = function () {
  21412. var textWidth = textContent.getBoundingRect().width;
  21413. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  21414. // textDistance needs to be calculated when both animation and text exist
  21415. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 - (opts.showSpinner && textWidth ? 0 : 5 + textWidth / 2) // only show the text
  21416. + (opts.showSpinner ? 0 : textWidth / 2) // only show the spinner
  21417. + (textWidth ? 0 : r);
  21418. var cy = api.getHeight() / 2;
  21419. opts.showSpinner && arc.setShape({
  21420. cx: cx,
  21421. cy: cy
  21422. });
  21423. labelRect.setShape({
  21424. x: cx - r,
  21425. y: cy - r,
  21426. width: r * 2,
  21427. height: r * 2
  21428. });
  21429. mask.setShape({
  21430. x: 0,
  21431. y: 0,
  21432. width: api.getWidth(),
  21433. height: api.getHeight()
  21434. });
  21435. };
  21436. group.resize();
  21437. return group;
  21438. }
  21439. var Scheduler =
  21440. /** @class */
  21441. function () {
  21442. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21443. // key: handlerUID
  21444. this._stageTaskMap = createHashMap();
  21445. this.ecInstance = ecInstance;
  21446. this.api = api; // Fix current processors in case that in some rear cases that
  21447. // processors might be registered after echarts instance created.
  21448. // Register processors incrementally for a echarts instance is
  21449. // not supported by this stream architecture.
  21450. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21451. visualHandlers = this._visualHandlers = visualHandlers.slice();
  21452. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21453. }
  21454. Scheduler.prototype.restoreData = function (ecModel, payload) {
  21455. // TODO: Only restore needed series and components, but not all components.
  21456. // Currently `restoreData` of all of the series and component will be called.
  21457. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21458. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21459. // and some components like coordinate system, axes, dataZoom, visualMap only
  21460. // need their target series refresh.
  21461. // (1) If we are implementing this feature some day, we should consider these cases:
  21462. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21463. // on the settings of `dataZoom`), it should be re-performed if the component
  21464. // is modified by `setOption`.
  21465. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21466. // it should be re-performed when the result array of `getTargetSeries` changed.
  21467. // We use `dependencies` to cover these issues.
  21468. // (3) How to update target series when coordinate system related components modified.
  21469. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21470. // and this case all of the tasks will be set as dirty.
  21471. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  21472. // depends on all of the series.
  21473. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21474. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21475. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21476. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21477. // probably cause state chaos (consider `dataZoomProcessor`).
  21478. this._stageTaskMap.each(function (taskRecord) {
  21479. var overallTask = taskRecord.overallTask;
  21480. overallTask && overallTask.dirty();
  21481. });
  21482. }; // If seriesModel provided, incremental threshold is check by series data.
  21483. Scheduler.prototype.getPerformArgs = function (task, isBlock) {
  21484. // For overall task
  21485. if (!task.__pipeline) {
  21486. return;
  21487. }
  21488. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21489. var pCtx = pipeline.context;
  21490. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  21491. var step = incremental ? pipeline.step : null;
  21492. var modDataCount = pCtx && pCtx.modDataCount;
  21493. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21494. return {
  21495. step: step,
  21496. modBy: modBy,
  21497. modDataCount: modDataCount
  21498. };
  21499. };
  21500. Scheduler.prototype.getPipeline = function (pipelineId) {
  21501. return this._pipelineMap.get(pipelineId);
  21502. };
  21503. /**
  21504. * Current, progressive rendering starts from visual and layout.
  21505. * Always detect render mode in the same stage, avoiding that incorrect
  21506. * detection caused by data filtering.
  21507. * Caution:
  21508. * `updateStreamModes` use `seriesModel.getData()`.
  21509. */
  21510. Scheduler.prototype.updateStreamModes = function (seriesModel, view) {
  21511. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21512. var data = seriesModel.getData();
  21513. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  21514. // animation frame. Note that some types of series do not provide
  21515. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21516. // use the term `incremental` but not `progressive` to describe the
  21517. // case that `chart.appendData`.
  21518. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  21519. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21520. // see `test/candlestick-large3.html`
  21521. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21522. seriesModel.pipelineContext = pipeline.context = {
  21523. progressiveRender: progressiveRender,
  21524. modDataCount: modDataCount,
  21525. large: large
  21526. };
  21527. };
  21528. Scheduler.prototype.restorePipelines = function (ecModel) {
  21529. var scheduler = this;
  21530. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21531. ecModel.eachSeries(function (seriesModel) {
  21532. var progressive = seriesModel.getProgressive();
  21533. var pipelineId = seriesModel.uid;
  21534. pipelineMap.set(pipelineId, {
  21535. id: pipelineId,
  21536. head: null,
  21537. tail: null,
  21538. threshold: seriesModel.getProgressiveThreshold(),
  21539. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21540. blockIndex: -1,
  21541. step: Math.round(progressive || 700),
  21542. count: 0
  21543. });
  21544. scheduler._pipe(seriesModel, seriesModel.dataTask);
  21545. });
  21546. };
  21547. Scheduler.prototype.prepareStageTasks = function () {
  21548. var stageTaskMap = this._stageTaskMap;
  21549. var ecModel = this.api.getModel();
  21550. var api = this.api;
  21551. each(this._allHandlers, function (handler) {
  21552. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {});
  21553. var errMsg = '';
  21554. if ("development" !== 'production') {
  21555. // Currently do not need to support to sepecify them both.
  21556. errMsg = '"reset" and "overallReset" must not be both specified.';
  21557. }
  21558. assert(!(handler.reset && handler.overallReset), errMsg);
  21559. handler.reset && this._createSeriesStageTask(handler, record, ecModel, api);
  21560. handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api);
  21561. }, this);
  21562. };
  21563. Scheduler.prototype.prepareView = function (view, model, ecModel, api) {
  21564. var renderTask = view.renderTask;
  21565. var context = renderTask.context;
  21566. context.model = model;
  21567. context.ecModel = ecModel;
  21568. context.api = api;
  21569. renderTask.__block = !view.incrementalPrepareRender;
  21570. this._pipe(model, renderTask);
  21571. };
  21572. Scheduler.prototype.performDataProcessorTasks = function (ecModel, payload) {
  21573. // If we do not use `block` here, it should be considered when to update modes.
  21574. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {
  21575. block: true
  21576. });
  21577. };
  21578. Scheduler.prototype.performVisualTasks = function (ecModel, payload, opt) {
  21579. this._performStageTasks(this._visualHandlers, ecModel, payload, opt);
  21580. };
  21581. Scheduler.prototype._performStageTasks = function (stageHandlers, ecModel, payload, opt) {
  21582. opt = opt || {};
  21583. var unfinished = false;
  21584. var scheduler = this;
  21585. each(stageHandlers, function (stageHandler, idx) {
  21586. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21587. return;
  21588. }
  21589. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21590. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21591. var overallTask = stageHandlerRecord.overallTask;
  21592. if (overallTask) {
  21593. var overallNeedDirty_1;
  21594. var agentStubMap = overallTask.agentStubMap;
  21595. agentStubMap.each(function (stub) {
  21596. if (needSetDirty(opt, stub)) {
  21597. stub.dirty();
  21598. overallNeedDirty_1 = true;
  21599. }
  21600. });
  21601. overallNeedDirty_1 && overallTask.dirty();
  21602. scheduler.updatePayload(overallTask, payload);
  21603. var performArgs_1 = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  21604. // then execute the overall task. And stub will call seriesModel.setData,
  21605. // which ensures that in the overallTask seriesModel.getData() will not
  21606. // return incorrect data.
  21607. agentStubMap.each(function (stub) {
  21608. stub.perform(performArgs_1);
  21609. });
  21610. if (overallTask.perform(performArgs_1)) {
  21611. unfinished = true;
  21612. }
  21613. } else if (seriesTaskMap) {
  21614. seriesTaskMap.each(function (task, pipelineId) {
  21615. if (needSetDirty(opt, task)) {
  21616. task.dirty();
  21617. }
  21618. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  21619. // if intending to decalare `performRawSeries` in handlers, only
  21620. // stream-independent (specifically, data item independent) operations can be
  21621. // performed. Because is a series is filtered, most of the tasks will not
  21622. // be performed. A stream-dependent operation probably cause wrong biz logic.
  21623. // Perhaps we should not provide a separate callback for this case instead
  21624. // of providing the config `performRawSeries`. The stream-dependent operaions
  21625. // and stream-independent operations should better not be mixed.
  21626. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  21627. scheduler.updatePayload(task, payload);
  21628. if (task.perform(performArgs)) {
  21629. unfinished = true;
  21630. }
  21631. });
  21632. }
  21633. });
  21634. function needSetDirty(opt, task) {
  21635. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21636. }
  21637. this.unfinished = unfinished || this.unfinished;
  21638. };
  21639. Scheduler.prototype.performSeriesTasks = function (ecModel) {
  21640. var unfinished;
  21641. ecModel.eachSeries(function (seriesModel) {
  21642. // Progress to the end for dataInit and dataRestore.
  21643. unfinished = seriesModel.dataTask.perform() || unfinished;
  21644. });
  21645. this.unfinished = unfinished || this.unfinished;
  21646. };
  21647. Scheduler.prototype.plan = function () {
  21648. // Travel pipelines, check block.
  21649. this._pipelineMap.each(function (pipeline) {
  21650. var task = pipeline.tail;
  21651. do {
  21652. if (task.__block) {
  21653. pipeline.blockIndex = task.__idxInPipeline;
  21654. break;
  21655. }
  21656. task = task.getUpstream();
  21657. } while (task);
  21658. });
  21659. };
  21660. Scheduler.prototype.updatePayload = function (task, payload) {
  21661. payload !== 'remain' && (task.context.payload = payload);
  21662. };
  21663. Scheduler.prototype._createSeriesStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  21664. var scheduler = this;
  21665. var oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so
  21666. // do not need to reuse the map.
  21667. var newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap();
  21668. var seriesType = stageHandler.seriesType;
  21669. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21670. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21671. // it works but it may cause other irrelevant charts blocked.
  21672. if (stageHandler.createOnAllSeries) {
  21673. ecModel.eachRawSeries(create);
  21674. } else if (seriesType) {
  21675. ecModel.eachRawSeriesByType(seriesType, create);
  21676. } else if (getTargetSeries) {
  21677. getTargetSeries(ecModel, api).each(create);
  21678. }
  21679. function create(seriesModel) {
  21680. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  21681. // Reuse original task instance.
  21682. var task = newSeriesTaskMap.set(pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask({
  21683. plan: seriesTaskPlan,
  21684. reset: seriesTaskReset,
  21685. count: seriesTaskCount
  21686. }));
  21687. task.context = {
  21688. model: seriesModel,
  21689. ecModel: ecModel,
  21690. api: api,
  21691. // PENDING: `useClearVisual` not used?
  21692. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21693. plan: stageHandler.plan,
  21694. reset: stageHandler.reset,
  21695. scheduler: scheduler
  21696. };
  21697. scheduler._pipe(seriesModel, task);
  21698. }
  21699. };
  21700. Scheduler.prototype._createOverallStageTask = function (stageHandler, stageHandlerRecord, ecModel, api) {
  21701. var scheduler = this;
  21702. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  21703. || createTask({
  21704. reset: overallTaskReset
  21705. });
  21706. overallTask.context = {
  21707. ecModel: ecModel,
  21708. api: api,
  21709. overallReset: stageHandler.overallReset,
  21710. scheduler: scheduler
  21711. };
  21712. var oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so
  21713. // do not need to reuse the map.
  21714. var newAgentStubMap = overallTask.agentStubMap = createHashMap();
  21715. var seriesType = stageHandler.seriesType;
  21716. var getTargetSeries = stageHandler.getTargetSeries;
  21717. var overallProgress = true;
  21718. var shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it
  21719. // let modifyOutputEnd = stageHandler.modifyOutputEnd;
  21720. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21721. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21722. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21723. // we set the pipeline block.
  21724. var errMsg = '';
  21725. if ("development" !== 'production') {
  21726. errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.';
  21727. }
  21728. assert(!stageHandler.createOnAllSeries, errMsg);
  21729. if (seriesType) {
  21730. ecModel.eachRawSeriesByType(seriesType, createStub);
  21731. } else if (getTargetSeries) {
  21732. getTargetSeries(ecModel, api).each(createStub);
  21733. } // Otherwise, (usually it is legancy case), the overall task will only be
  21734. // executed when upstream dirty. Otherwise the progressive rendering of all
  21735. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21736. // dirty info from upsteam.
  21737. else {
  21738. overallProgress = false;
  21739. each(ecModel.getSeries(), createStub);
  21740. }
  21741. function createStub(seriesModel) {
  21742. var pipelineId = seriesModel.uid;
  21743. var stub = newAgentStubMap.set(pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask
  21744. // should be set as dirty and re-performed.
  21745. shouldOverallTaskDirty = true, createTask({
  21746. reset: stubReset,
  21747. onDirty: stubOnDirty
  21748. })));
  21749. stub.context = {
  21750. model: seriesModel,
  21751. overallProgress: overallProgress // FIXME:TS never used, so comment it
  21752. // modifyOutputEnd: modifyOutputEnd
  21753. };
  21754. stub.agent = overallTask;
  21755. stub.__block = overallProgress;
  21756. scheduler._pipe(seriesModel, stub);
  21757. }
  21758. if (shouldOverallTaskDirty) {
  21759. overallTask.dirty();
  21760. }
  21761. };
  21762. Scheduler.prototype._pipe = function (seriesModel, task) {
  21763. var pipelineId = seriesModel.uid;
  21764. var pipeline = this._pipelineMap.get(pipelineId);
  21765. !pipeline.head && (pipeline.head = task);
  21766. pipeline.tail && pipeline.tail.pipe(task);
  21767. pipeline.tail = task;
  21768. task.__idxInPipeline = pipeline.count++;
  21769. task.__pipeline = pipeline;
  21770. };
  21771. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21772. if (isFunction(stageHandler)) {
  21773. stageHandler = {
  21774. overallReset: stageHandler,
  21775. seriesType: detectSeriseType(stageHandler)
  21776. };
  21777. }
  21778. stageHandler.uid = getUID('stageHandler');
  21779. visualType && (stageHandler.visualType = visualType);
  21780. return stageHandler;
  21781. };
  21782. return Scheduler;
  21783. }();
  21784. function overallTaskReset(context) {
  21785. context.overallReset(context.ecModel, context.api, context.payload);
  21786. }
  21787. function stubReset(context) {
  21788. return context.overallProgress && stubProgress;
  21789. }
  21790. function stubProgress() {
  21791. this.agent.dirty();
  21792. this.getDownstream().dirty();
  21793. }
  21794. function stubOnDirty() {
  21795. this.agent && this.agent.dirty();
  21796. }
  21797. function seriesTaskPlan(context) {
  21798. return context.plan ? context.plan(context.model, context.ecModel, context.api, context.payload) : null;
  21799. }
  21800. function seriesTaskReset(context) {
  21801. if (context.useClearVisual) {
  21802. context.data.clearAllVisual();
  21803. }
  21804. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  21805. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  21806. return makeSeriesTaskProgress(idx);
  21807. }) : singleSeriesTaskProgress;
  21808. }
  21809. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21810. function makeSeriesTaskProgress(resetDefineIdx) {
  21811. return function (params, context) {
  21812. var data = context.data;
  21813. var resetDefine = context.resetDefines[resetDefineIdx];
  21814. if (resetDefine && resetDefine.dataEach) {
  21815. for (var i = params.start; i < params.end; i++) {
  21816. resetDefine.dataEach(data, i);
  21817. }
  21818. } else if (resetDefine && resetDefine.progress) {
  21819. resetDefine.progress(params, data);
  21820. }
  21821. };
  21822. }
  21823. function seriesTaskCount(context) {
  21824. return context.data.count();
  21825. }
  21826. /**
  21827. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21828. * To ensure that they can work normally, they should work in block mode, that is,
  21829. * they should not be started util the previous tasks finished. So they cause the
  21830. * progressive rendering disabled. We try to detect the series type, to narrow down
  21831. * the block range to only the series type they concern, but not all series.
  21832. */
  21833. function detectSeriseType(legacyFunc) {
  21834. seriesType = null;
  21835. try {
  21836. // Assume there is no async when calling `eachSeriesByType`.
  21837. legacyFunc(ecModelMock, apiMock);
  21838. } catch (e) {}
  21839. return seriesType;
  21840. }
  21841. var ecModelMock = {};
  21842. var apiMock = {};
  21843. var seriesType;
  21844. mockMethods(ecModelMock, GlobalModel);
  21845. mockMethods(apiMock, ExtensionAPI);
  21846. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21847. seriesType = type;
  21848. };
  21849. ecModelMock.eachComponent = function (cond) {
  21850. if (cond.mainType === 'series' && cond.subType) {
  21851. seriesType = cond.subType;
  21852. }
  21853. };
  21854. function mockMethods(target, Clz) {
  21855. /* eslint-disable */
  21856. for (var name_1 in Clz.prototype) {
  21857. // Do not use hasOwnProperty
  21858. target[name_1] = noop;
  21859. }
  21860. /* eslint-enable */
  21861. }
  21862. /*
  21863. * Licensed to the Apache Software Foundation (ASF) under one
  21864. * or more contributor license agreements. See the NOTICE file
  21865. * distributed with this work for additional information
  21866. * regarding copyright ownership. The ASF licenses this file
  21867. * to you under the Apache License, Version 2.0 (the
  21868. * "License"); you may not use this file except in compliance
  21869. * with the License. You may obtain a copy of the License at
  21870. *
  21871. * http://www.apache.org/licenses/LICENSE-2.0
  21872. *
  21873. * Unless required by applicable law or agreed to in writing,
  21874. * software distributed under the License is distributed on an
  21875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21876. * KIND, either express or implied. See the License for the
  21877. * specific language governing permissions and limitations
  21878. * under the License.
  21879. */
  21880. /**
  21881. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21882. */
  21883. /*
  21884. * Licensed to the Apache Software Foundation (ASF) under one
  21885. * or more contributor license agreements. See the NOTICE file
  21886. * distributed with this work for additional information
  21887. * regarding copyright ownership. The ASF licenses this file
  21888. * to you under the Apache License, Version 2.0 (the
  21889. * "License"); you may not use this file except in compliance
  21890. * with the License. You may obtain a copy of the License at
  21891. *
  21892. * http://www.apache.org/licenses/LICENSE-2.0
  21893. *
  21894. * Unless required by applicable law or agreed to in writing,
  21895. * software distributed under the License is distributed on an
  21896. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21897. * KIND, either express or implied. See the License for the
  21898. * specific language governing permissions and limitations
  21899. * under the License.
  21900. */
  21901. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21902. var lightTheme = {
  21903. color: colorAll,
  21904. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  21905. };
  21906. /*
  21907. * Licensed to the Apache Software Foundation (ASF) under one
  21908. * or more contributor license agreements. See the NOTICE file
  21909. * distributed with this work for additional information
  21910. * regarding copyright ownership. The ASF licenses this file
  21911. * to you under the Apache License, Version 2.0 (the
  21912. * "License"); you may not use this file except in compliance
  21913. * with the License. You may obtain a copy of the License at
  21914. *
  21915. * http://www.apache.org/licenses/LICENSE-2.0
  21916. *
  21917. * Unless required by applicable law or agreed to in writing,
  21918. * software distributed under the License is distributed on an
  21919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21920. * KIND, either express or implied. See the License for the
  21921. * specific language governing permissions and limitations
  21922. * under the License.
  21923. */
  21924. /**
  21925. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21926. */
  21927. /*
  21928. * Licensed to the Apache Software Foundation (ASF) under one
  21929. * or more contributor license agreements. See the NOTICE file
  21930. * distributed with this work for additional information
  21931. * regarding copyright ownership. The ASF licenses this file
  21932. * to you under the Apache License, Version 2.0 (the
  21933. * "License"); you may not use this file except in compliance
  21934. * with the License. You may obtain a copy of the License at
  21935. *
  21936. * http://www.apache.org/licenses/LICENSE-2.0
  21937. *
  21938. * Unless required by applicable law or agreed to in writing,
  21939. * software distributed under the License is distributed on an
  21940. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21941. * KIND, either express or implied. See the License for the
  21942. * specific language governing permissions and limitations
  21943. * under the License.
  21944. */
  21945. var contrastColor = '#B9B8CE';
  21946. var backgroundColor = '#100C2A';
  21947. var axisCommon = function () {
  21948. return {
  21949. axisLine: {
  21950. lineStyle: {
  21951. color: contrastColor
  21952. }
  21953. },
  21954. splitLine: {
  21955. lineStyle: {
  21956. color: '#484753'
  21957. }
  21958. },
  21959. splitArea: {
  21960. areaStyle: {
  21961. color: ['rgba(255,255,255,0.02)', 'rgba(255,255,255,0.05)']
  21962. }
  21963. },
  21964. minorSplitLine: {
  21965. lineStyle: {
  21966. color: '#20203B'
  21967. }
  21968. }
  21969. };
  21970. };
  21971. var colorPalette = ['#4992ff', '#7cffb2', '#fddd60', '#ff6e76', '#58d9f9', '#05c091', '#ff8a45', '#8d48e3', '#dd79ff'];
  21972. var theme = {
  21973. darkMode: true,
  21974. color: colorPalette,
  21975. backgroundColor: backgroundColor,
  21976. axisPointer: {
  21977. lineStyle: {
  21978. color: '#817f91'
  21979. },
  21980. crossStyle: {
  21981. color: '#817f91'
  21982. },
  21983. label: {
  21984. // TODO Contrast of label backgorundColor
  21985. color: '#fff'
  21986. }
  21987. },
  21988. legend: {
  21989. textStyle: {
  21990. color: contrastColor
  21991. }
  21992. },
  21993. textStyle: {
  21994. color: contrastColor
  21995. },
  21996. title: {
  21997. textStyle: {
  21998. color: '#EEF1FA'
  21999. },
  22000. subtextStyle: {
  22001. color: '#B9B8CE'
  22002. }
  22003. },
  22004. toolbox: {
  22005. iconStyle: {
  22006. borderColor: contrastColor
  22007. }
  22008. },
  22009. dataZoom: {
  22010. borderColor: '#71708A',
  22011. textStyle: {
  22012. color: contrastColor
  22013. },
  22014. brushStyle: {
  22015. color: 'rgba(135,163,206,0.3)'
  22016. },
  22017. handleStyle: {
  22018. color: '#353450',
  22019. borderColor: '#C5CBE3'
  22020. },
  22021. moveHandleStyle: {
  22022. color: '#B0B6C3',
  22023. opacity: 0.3
  22024. },
  22025. fillerColor: 'rgba(135,163,206,0.2)',
  22026. emphasis: {
  22027. handleStyle: {
  22028. borderColor: '#91B7F2',
  22029. color: '#4D587D'
  22030. },
  22031. moveHandleStyle: {
  22032. color: '#636D9A',
  22033. opacity: 0.7
  22034. }
  22035. },
  22036. dataBackground: {
  22037. lineStyle: {
  22038. color: '#71708A',
  22039. width: 1
  22040. },
  22041. areaStyle: {
  22042. color: '#71708A'
  22043. }
  22044. },
  22045. selectedDataBackground: {
  22046. lineStyle: {
  22047. color: '#87A3CE'
  22048. },
  22049. areaStyle: {
  22050. color: '#87A3CE'
  22051. }
  22052. }
  22053. },
  22054. visualMap: {
  22055. textStyle: {
  22056. color: contrastColor
  22057. }
  22058. },
  22059. timeline: {
  22060. lineStyle: {
  22061. color: contrastColor
  22062. },
  22063. label: {
  22064. color: contrastColor
  22065. },
  22066. controlStyle: {
  22067. color: contrastColor,
  22068. borderColor: contrastColor
  22069. }
  22070. },
  22071. calendar: {
  22072. itemStyle: {
  22073. color: backgroundColor
  22074. },
  22075. dayLabel: {
  22076. color: contrastColor
  22077. },
  22078. monthLabel: {
  22079. color: contrastColor
  22080. },
  22081. yearLabel: {
  22082. color: contrastColor
  22083. }
  22084. },
  22085. timeAxis: axisCommon(),
  22086. logAxis: axisCommon(),
  22087. valueAxis: axisCommon(),
  22088. categoryAxis: axisCommon(),
  22089. line: {
  22090. symbol: 'circle'
  22091. },
  22092. graph: {
  22093. color: colorPalette
  22094. },
  22095. gauge: {
  22096. title: {
  22097. color: contrastColor
  22098. },
  22099. axisLine: {
  22100. lineStyle: {
  22101. color: [[1, 'rgba(207,212,219,0.2)']]
  22102. }
  22103. },
  22104. axisLabel: {
  22105. color: contrastColor
  22106. },
  22107. detail: {
  22108. color: '#EEF1FA'
  22109. }
  22110. },
  22111. candlestick: {
  22112. itemStyle: {
  22113. color: '#f64e56',
  22114. color0: '#54ea92',
  22115. borderColor: '#f64e56',
  22116. borderColor0: '#54ea92' // borderColor: '#ca2824',
  22117. // borderColor0: '#09a443'
  22118. }
  22119. }
  22120. };
  22121. theme.categoryAxis.splitLine.show = false;
  22122. function parseXML(svg) {
  22123. if (isString(svg)) {
  22124. var parser = new DOMParser();
  22125. svg = parser.parseFromString(svg, 'text/xml');
  22126. }
  22127. var svgNode = svg;
  22128. if (svgNode.nodeType === 9) {
  22129. svgNode = svgNode.firstChild;
  22130. }
  22131. while (svgNode.nodeName.toLowerCase() !== 'svg' || svgNode.nodeType !== 1) {
  22132. svgNode = svgNode.nextSibling;
  22133. }
  22134. return svgNode;
  22135. }
  22136. var storage = createHashMap();
  22137. var mapDataStorage = {
  22138. /**
  22139. * Compatible with previous `echarts.registerMap`.
  22140. * @usage
  22141. * ```js
  22142. * $.get('USA.json', function (geoJson) {
  22143. * echarts.registerMap('USA', geoJson);
  22144. * // Or
  22145. * echarts.registerMap('USA', {
  22146. * geoJson: geoJson,
  22147. * specialAreas: {}
  22148. * })
  22149. * });
  22150. *
  22151. * $.get('airport.svg', function (svg) {
  22152. * echarts.registerMap('airport', {
  22153. * svg: svg
  22154. * }
  22155. * });
  22156. *
  22157. * echarts.registerMap('eu', [
  22158. * {svg: eu-topographic.svg},
  22159. * {geoJSON: eu.json}
  22160. * ])
  22161. * ```
  22162. */
  22163. registerMap: function (mapName, rawDef, rawSpecialAreas) {
  22164. var records;
  22165. if (isArray(rawDef)) {
  22166. records = rawDef;
  22167. } else if (rawDef.svg) {
  22168. records = [{
  22169. type: 'svg',
  22170. source: rawDef.svg,
  22171. specialAreas: rawDef.specialAreas
  22172. }];
  22173. } else {
  22174. // Backward compatibility.
  22175. var geoSource = rawDef.geoJson || rawDef.geoJSON;
  22176. if (geoSource && !rawDef.features) {
  22177. rawSpecialAreas = rawDef.specialAreas;
  22178. rawDef = geoSource;
  22179. }
  22180. records = [{
  22181. type: 'geoJSON',
  22182. source: rawDef,
  22183. specialAreas: rawSpecialAreas
  22184. }];
  22185. }
  22186. each(records, function (record) {
  22187. var type = record.type;
  22188. type === 'geoJson' && (type = record.type = 'geoJSON');
  22189. var parse = parsers[type];
  22190. if ("development" !== 'production') {
  22191. assert(parse, 'Illegal map type: ' + type);
  22192. }
  22193. parse(record);
  22194. });
  22195. return storage.set(mapName, records);
  22196. },
  22197. retrieveMap: function (mapName) {
  22198. return storage.get(mapName);
  22199. }
  22200. };
  22201. var parsers = {
  22202. geoJSON: function (record) {
  22203. var source = record.source;
  22204. record.geoJSON = !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  22205. },
  22206. // Only perform parse to XML object here, which might be time
  22207. // consiming for large SVG.
  22208. // Although convert XML to zrender element is also time consiming,
  22209. // if we do it here, the clone of zrender elements has to be
  22210. // required. So we do it once for each geo instance, util real
  22211. // performance issues call for optimizing it.
  22212. svg: function (record) {
  22213. record.svgXML = parseXML(record.source);
  22214. }
  22215. };
  22216. /**
  22217. * Usage of query:
  22218. * `chart.on('click', query, handler);`
  22219. * The `query` can be:
  22220. * + The component type query string, only `mainType` or `mainType.subType`,
  22221. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  22222. * + The component query object, like:
  22223. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  22224. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  22225. * + The data query object, like:
  22226. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  22227. * + The other query object (cmponent customized query), like:
  22228. * `{element: 'some'}` (only available in custom series).
  22229. *
  22230. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  22231. * same as there is no such prop in the `query` object.
  22232. */
  22233. var ECEventProcessor =
  22234. /** @class */
  22235. function () {
  22236. function ECEventProcessor() {}
  22237. ECEventProcessor.prototype.normalizeQuery = function (query) {
  22238. var cptQuery = {};
  22239. var dataQuery = {};
  22240. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  22241. if (isString(query)) {
  22242. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  22243. cptQuery.mainType = condCptType.main || null;
  22244. cptQuery.subType = condCptType.sub || null;
  22245. } // `query` is an object, convert to {mainType, index, name, id}.
  22246. else {
  22247. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  22248. // can not be used in `compomentModel.filterForExposedEvent`.
  22249. var suffixes_1 = ['Index', 'Name', 'Id'];
  22250. var dataKeys_1 = {
  22251. name: 1,
  22252. dataIndex: 1,
  22253. dataType: 1
  22254. };
  22255. each(query, function (val, key) {
  22256. var reserved = false;
  22257. for (var i = 0; i < suffixes_1.length; i++) {
  22258. var propSuffix = suffixes_1[i];
  22259. var suffixPos = key.lastIndexOf(propSuffix);
  22260. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  22261. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  22262. if (mainType !== 'data') {
  22263. cptQuery.mainType = mainType;
  22264. cptQuery[propSuffix.toLowerCase()] = val;
  22265. reserved = true;
  22266. }
  22267. }
  22268. }
  22269. if (dataKeys_1.hasOwnProperty(key)) {
  22270. dataQuery[key] = val;
  22271. reserved = true;
  22272. }
  22273. if (!reserved) {
  22274. otherQuery[key] = val;
  22275. }
  22276. });
  22277. }
  22278. return {
  22279. cptQuery: cptQuery,
  22280. dataQuery: dataQuery,
  22281. otherQuery: otherQuery
  22282. };
  22283. };
  22284. ECEventProcessor.prototype.filter = function (eventType, query) {
  22285. // They should be assigned before each trigger call.
  22286. var eventInfo = this.eventInfo;
  22287. if (!eventInfo) {
  22288. return true;
  22289. }
  22290. var targetEl = eventInfo.targetEl;
  22291. var packedEvent = eventInfo.packedEvent;
  22292. var model = eventInfo.model;
  22293. var view = eventInfo.view; // For event like 'globalout'.
  22294. if (!model || !view) {
  22295. return true;
  22296. }
  22297. var cptQuery = query.cptQuery;
  22298. var dataQuery = query.dataQuery;
  22299. 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));
  22300. function check(query, host, prop, propOnHost) {
  22301. return query[prop] == null || host[propOnHost || prop] === query[prop];
  22302. }
  22303. };
  22304. ECEventProcessor.prototype.afterTrigger = function () {
  22305. // Make sure the eventInfo wont be used in next trigger.
  22306. this.eventInfo = null;
  22307. };
  22308. return ECEventProcessor;
  22309. }();
  22310. var seriesSymbolTask = {
  22311. createOnAllSeries: true,
  22312. // For legend.
  22313. performRawSeries: true,
  22314. reset: function (seriesModel, ecModel) {
  22315. var data = seriesModel.getData();
  22316. if (seriesModel.legendSymbol) {
  22317. data.setVisual('legendSymbol', seriesModel.legendSymbol);
  22318. }
  22319. if (!seriesModel.hasSymbolVisual) {
  22320. return;
  22321. }
  22322. var symbolType = seriesModel.get('symbol');
  22323. var symbolSize = seriesModel.get('symbolSize');
  22324. var keepAspect = seriesModel.get('symbolKeepAspect');
  22325. var symbolRotate = seriesModel.get('symbolRotate');
  22326. var hasSymbolTypeCallback = isFunction(symbolType);
  22327. var hasSymbolSizeCallback = isFunction(symbolSize);
  22328. var hasSymbolRotateCallback = isFunction(symbolRotate);
  22329. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  22330. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : seriesModel.defaultSymbol;
  22331. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  22332. var seriesSymbolRotate = !hasSymbolRotateCallback ? symbolRotate : null;
  22333. data.setVisual({
  22334. legendSymbol: seriesModel.legendSymbol || seriesSymbol,
  22335. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  22336. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  22337. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  22338. // some cases but generally it is not recommanded.
  22339. symbol: seriesSymbol,
  22340. symbolSize: seriesSymbolSize,
  22341. symbolKeepAspect: keepAspect,
  22342. symbolRotate: seriesSymbolRotate
  22343. }); // Only visible series has each data be visual encoded
  22344. if (ecModel.isSeriesFiltered(seriesModel)) {
  22345. return;
  22346. }
  22347. function dataEach(data, idx) {
  22348. var rawValue = seriesModel.getRawValue(idx);
  22349. var params = seriesModel.getDataParams(idx);
  22350. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  22351. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  22352. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  22353. }
  22354. return {
  22355. dataEach: hasCallback ? dataEach : null
  22356. };
  22357. }
  22358. };
  22359. var dataSymbolTask = {
  22360. createOnAllSeries: true,
  22361. // For legend.
  22362. performRawSeries: true,
  22363. reset: function (seriesModel, ecModel) {
  22364. if (!seriesModel.hasSymbolVisual) {
  22365. return;
  22366. } // Only visible series has each data be visual encoded
  22367. if (ecModel.isSeriesFiltered(seriesModel)) {
  22368. return;
  22369. }
  22370. var data = seriesModel.getData();
  22371. function dataEach(data, idx) {
  22372. var itemModel = data.getItemModel(idx);
  22373. var itemSymbolType = itemModel.getShallow('symbol', true);
  22374. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  22375. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  22376. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  22377. if (itemSymbolType != null) {
  22378. data.setItemVisual(idx, 'symbol', itemSymbolType);
  22379. }
  22380. if (itemSymbolSize != null) {
  22381. // PENDING Transform symbolSize ?
  22382. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  22383. }
  22384. if (itemSymbolRotate != null) {
  22385. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  22386. }
  22387. if (itemSymbolKeepAspect != null) {
  22388. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  22389. }
  22390. }
  22391. return {
  22392. dataEach: data.hasItemOption ? dataEach : null
  22393. };
  22394. }
  22395. };
  22396. /*
  22397. * Licensed to the Apache Software Foundation (ASF) under one
  22398. * or more contributor license agreements. See the NOTICE file
  22399. * distributed with this work for additional information
  22400. * regarding copyright ownership. The ASF licenses this file
  22401. * to you under the Apache License, Version 2.0 (the
  22402. * "License"); you may not use this file except in compliance
  22403. * with the License. You may obtain a copy of the License at
  22404. *
  22405. * http://www.apache.org/licenses/LICENSE-2.0
  22406. *
  22407. * Unless required by applicable law or agreed to in writing,
  22408. * software distributed under the License is distributed on an
  22409. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22410. * KIND, either express or implied. See the License for the
  22411. * specific language governing permissions and limitations
  22412. * under the License.
  22413. */
  22414. /**
  22415. * AUTO-GENERATED FILE. DO NOT MODIFY.
  22416. */
  22417. /*
  22418. * Licensed to the Apache Software Foundation (ASF) under one
  22419. * or more contributor license agreements. See the NOTICE file
  22420. * distributed with this work for additional information
  22421. * regarding copyright ownership. The ASF licenses this file
  22422. * to you under the Apache License, Version 2.0 (the
  22423. * "License"); you may not use this file except in compliance
  22424. * with the License. You may obtain a copy of the License at
  22425. *
  22426. * http://www.apache.org/licenses/LICENSE-2.0
  22427. *
  22428. * Unless required by applicable law or agreed to in writing,
  22429. * software distributed under the License is distributed on an
  22430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22431. * KIND, either express or implied. See the License for the
  22432. * specific language governing permissions and limitations
  22433. * under the License.
  22434. */
  22435. function getItemVisualFromData(data, dataIndex, key) {
  22436. switch (key) {
  22437. case 'color':
  22438. var style = data.getItemVisual(dataIndex, 'style');
  22439. return style[data.getVisual('drawType')];
  22440. case 'opacity':
  22441. return data.getItemVisual(dataIndex, 'style').opacity;
  22442. case 'symbol':
  22443. case 'symbolSize':
  22444. case 'liftZ':
  22445. return data.getItemVisual(dataIndex, key);
  22446. default:
  22447. if ("development" !== 'production') {
  22448. console.warn("Unknown visual type " + key);
  22449. }
  22450. }
  22451. }
  22452. function getVisualFromData(data, key) {
  22453. switch (key) {
  22454. case 'color':
  22455. var style = data.getVisual('style');
  22456. return style[data.getVisual('drawType')];
  22457. case 'opacity':
  22458. return data.getVisual('style').opacity;
  22459. case 'symbol':
  22460. case 'symbolSize':
  22461. case 'liftZ':
  22462. return data.getVisual(key);
  22463. default:
  22464. if ("development" !== 'production') {
  22465. console.warn("Unknown visual type " + key);
  22466. }
  22467. }
  22468. }
  22469. function setItemVisualFromData(data, dataIndex, key, value) {
  22470. switch (key) {
  22471. case 'color':
  22472. // Make sure not sharing style object.
  22473. var style = data.ensureUniqueItemVisual(dataIndex, 'style');
  22474. style[data.getVisual('drawType')] = value; // Mark the color has been changed, not from palette anymore
  22475. data.setItemVisual(dataIndex, 'colorFromPalette', false);
  22476. break;
  22477. case 'opacity':
  22478. data.ensureUniqueItemVisual(dataIndex, 'style').opacity = value;
  22479. break;
  22480. case 'symbol':
  22481. case 'symbolSize':
  22482. case 'liftZ':
  22483. data.setItemVisual(dataIndex, key, value);
  22484. break;
  22485. default:
  22486. if ("development" !== 'production') {
  22487. console.warn("Unknown visual type " + key);
  22488. }
  22489. }
  22490. }
  22491. var PI2$6 = Math.PI * 2;
  22492. var CMD$3 = PathProxy.CMD;
  22493. var DEFAULT_SEARCH_SPACE = ['top', 'right', 'bottom', 'left'];
  22494. function getCandidateAnchor(pos, distance, rect, outPt, outDir) {
  22495. var width = rect.width;
  22496. var height = rect.height;
  22497. switch (pos) {
  22498. case 'top':
  22499. outPt.set(rect.x + width / 2, rect.y - distance);
  22500. outDir.set(0, -1);
  22501. break;
  22502. case 'bottom':
  22503. outPt.set(rect.x + width / 2, rect.y + height + distance);
  22504. outDir.set(0, 1);
  22505. break;
  22506. case 'left':
  22507. outPt.set(rect.x - distance, rect.y + height / 2);
  22508. outDir.set(-1, 0);
  22509. break;
  22510. case 'right':
  22511. outPt.set(rect.x + width + distance, rect.y + height / 2);
  22512. outDir.set(1, 0);
  22513. break;
  22514. }
  22515. }
  22516. function projectPointToArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y, out) {
  22517. x -= cx;
  22518. y -= cy;
  22519. var d = Math.sqrt(x * x + y * y);
  22520. x /= d;
  22521. y /= d; // Intersect point.
  22522. var ox = x * r + cx;
  22523. var oy = y * r + cy;
  22524. if (Math.abs(startAngle - endAngle) % PI2$6 < 1e-4) {
  22525. // Is a circle
  22526. out[0] = ox;
  22527. out[1] = oy;
  22528. return d - r;
  22529. }
  22530. if (anticlockwise) {
  22531. var tmp = startAngle;
  22532. startAngle = normalizeRadian(endAngle);
  22533. endAngle = normalizeRadian(tmp);
  22534. } else {
  22535. startAngle = normalizeRadian(startAngle);
  22536. endAngle = normalizeRadian(endAngle);
  22537. }
  22538. if (startAngle > endAngle) {
  22539. endAngle += PI2$6;
  22540. }
  22541. var angle = Math.atan2(y, x);
  22542. if (angle < 0) {
  22543. angle += PI2$6;
  22544. }
  22545. if (angle >= startAngle && angle <= endAngle || angle + PI2$6 >= startAngle && angle + PI2$6 <= endAngle) {
  22546. // Project point is on the arc.
  22547. out[0] = ox;
  22548. out[1] = oy;
  22549. return d - r;
  22550. }
  22551. var x1 = r * Math.cos(startAngle) + cx;
  22552. var y1 = r * Math.sin(startAngle) + cy;
  22553. var x2 = r * Math.cos(endAngle) + cx;
  22554. var y2 = r * Math.sin(endAngle) + cy;
  22555. var d1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y);
  22556. var d2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y);
  22557. if (d1 < d2) {
  22558. out[0] = x1;
  22559. out[1] = y1;
  22560. return Math.sqrt(d1);
  22561. } else {
  22562. out[0] = x2;
  22563. out[1] = y2;
  22564. return Math.sqrt(d2);
  22565. }
  22566. }
  22567. function projectPointToLine(x1, y1, x2, y2, x, y, out, limitToEnds) {
  22568. var dx = x - x1;
  22569. var dy = y - y1;
  22570. var dx1 = x2 - x1;
  22571. var dy1 = y2 - y1;
  22572. var lineLen = Math.sqrt(dx1 * dx1 + dy1 * dy1);
  22573. dx1 /= lineLen;
  22574. dy1 /= lineLen; // dot product
  22575. var projectedLen = dx * dx1 + dy * dy1;
  22576. var t = projectedLen / lineLen;
  22577. if (limitToEnds) {
  22578. t = Math.min(Math.max(t, 0), 1);
  22579. }
  22580. t *= lineLen;
  22581. var ox = out[0] = x1 + t * dx1;
  22582. var oy = out[1] = y1 + t * dy1;
  22583. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  22584. }
  22585. function projectPointToRect(x1, y1, width, height, x, y, out) {
  22586. if (width < 0) {
  22587. x1 = x1 + width;
  22588. width = -width;
  22589. }
  22590. if (height < 0) {
  22591. y1 = y1 + height;
  22592. height = -height;
  22593. }
  22594. var x2 = x1 + width;
  22595. var y2 = y1 + height;
  22596. var ox = out[0] = Math.min(Math.max(x, x1), x2);
  22597. var oy = out[1] = Math.min(Math.max(y, y1), y2);
  22598. return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
  22599. }
  22600. var tmpPt = [];
  22601. function nearestPointOnRect(pt, rect, out) {
  22602. var dist = projectPointToRect(rect.x, rect.y, rect.width, rect.height, pt.x, pt.y, tmpPt);
  22603. out.set(tmpPt[0], tmpPt[1]);
  22604. return dist;
  22605. }
  22606. /**
  22607. * Calculate min distance corresponding point.
  22608. * This method won't evaluate if point is in the path.
  22609. */
  22610. function nearestPointOnPath(pt, path, out) {
  22611. var xi = 0;
  22612. var yi = 0;
  22613. var x0 = 0;
  22614. var y0 = 0;
  22615. var x1;
  22616. var y1;
  22617. var minDist = Infinity;
  22618. var data = path.data;
  22619. var x = pt.x;
  22620. var y = pt.y;
  22621. for (var i = 0; i < data.length;) {
  22622. var cmd = data[i++];
  22623. if (i === 1) {
  22624. xi = data[i];
  22625. yi = data[i + 1];
  22626. x0 = xi;
  22627. y0 = yi;
  22628. }
  22629. var d = minDist;
  22630. switch (cmd) {
  22631. case CMD$3.M:
  22632. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  22633. // 在 closePath 的时候使用
  22634. x0 = data[i++];
  22635. y0 = data[i++];
  22636. xi = x0;
  22637. yi = y0;
  22638. break;
  22639. case CMD$3.L:
  22640. d = projectPointToLine(xi, yi, data[i], data[i + 1], x, y, tmpPt, true);
  22641. xi = data[i++];
  22642. yi = data[i++];
  22643. break;
  22644. case CMD$3.C:
  22645. d = cubicProjectPoint(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  22646. xi = data[i++];
  22647. yi = data[i++];
  22648. break;
  22649. case CMD$3.Q:
  22650. d = quadraticProjectPoint(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y, tmpPt);
  22651. xi = data[i++];
  22652. yi = data[i++];
  22653. break;
  22654. case CMD$3.A:
  22655. // TODO Arc 判断的开销比较大
  22656. var cx = data[i++];
  22657. var cy = data[i++];
  22658. var rx = data[i++];
  22659. var ry = data[i++];
  22660. var theta = data[i++];
  22661. var dTheta = data[i++]; // TODO Arc 旋转
  22662. i += 1;
  22663. var anticlockwise = !!(1 - data[i++]);
  22664. x1 = Math.cos(theta) * rx + cx;
  22665. y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  22666. if (i <= 1) {
  22667. // 第一个命令起点还未定义
  22668. x0 = x1;
  22669. y0 = y1;
  22670. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  22671. var _x = (x - cx) * ry / rx + cx;
  22672. d = projectPointToArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y, tmpPt);
  22673. xi = Math.cos(theta + dTheta) * rx + cx;
  22674. yi = Math.sin(theta + dTheta) * ry + cy;
  22675. break;
  22676. case CMD$3.R:
  22677. x0 = xi = data[i++];
  22678. y0 = yi = data[i++];
  22679. var width = data[i++];
  22680. var height = data[i++];
  22681. d = projectPointToRect(x0, y0, width, height, x, y, tmpPt);
  22682. break;
  22683. case CMD$3.Z:
  22684. d = projectPointToLine(xi, yi, x0, y0, x, y, tmpPt, true);
  22685. xi = x0;
  22686. yi = y0;
  22687. break;
  22688. }
  22689. if (d < minDist) {
  22690. minDist = d;
  22691. out.set(tmpPt[0], tmpPt[1]);
  22692. }
  22693. }
  22694. return minDist;
  22695. } // Temporal varible for intermediate usage.
  22696. var pt0 = new Point();
  22697. var pt1 = new Point();
  22698. var pt2 = new Point();
  22699. var dir = new Point();
  22700. var dir2 = new Point();
  22701. /**
  22702. * Calculate a proper guide line based on the label position and graphic element definition
  22703. * @param label
  22704. * @param labelRect
  22705. * @param target
  22706. * @param targetRect
  22707. */
  22708. function updateLabelLinePoints(target, labelLineModel) {
  22709. if (!target) {
  22710. return;
  22711. }
  22712. var labelLine = target.getTextGuideLine();
  22713. var label = target.getTextContent(); // Needs to create text guide in each charts.
  22714. if (!(label && labelLine)) {
  22715. return;
  22716. }
  22717. var labelGuideConfig = target.textGuideLineConfig || {};
  22718. var points = [[0, 0], [0, 0], [0, 0]];
  22719. var searchSpace = labelGuideConfig.candidates || DEFAULT_SEARCH_SPACE;
  22720. var labelRect = label.getBoundingRect().clone();
  22721. labelRect.applyTransform(label.getComputedTransform());
  22722. var minDist = Infinity;
  22723. var anchorPoint = labelGuideConfig.anchor;
  22724. var targetTransform = target.getComputedTransform();
  22725. var targetInversedTransform = targetTransform && invert([], targetTransform);
  22726. var len = labelLineModel.get('length2') || 0;
  22727. if (anchorPoint) {
  22728. pt2.copy(anchorPoint);
  22729. }
  22730. for (var i = 0; i < searchSpace.length; i++) {
  22731. var candidate = searchSpace[i];
  22732. getCandidateAnchor(candidate, 0, labelRect, pt0, dir);
  22733. Point.scaleAndAdd(pt1, pt0, dir, len); // Transform to target coord space.
  22734. pt1.transform(targetInversedTransform); // Note: getBoundingRect will ensure the `path` being created.
  22735. var boundingRect = target.getBoundingRect();
  22736. var dist = anchorPoint ? anchorPoint.distance(pt1) : target instanceof Path ? nearestPointOnPath(pt1, target.path, pt2) : nearestPointOnRect(pt1, boundingRect, pt2); // TODO pt2 is in the path
  22737. if (dist < minDist) {
  22738. minDist = dist; // Transform back to global space.
  22739. pt1.transform(targetTransform);
  22740. pt2.transform(targetTransform);
  22741. pt2.toArray(points[0]);
  22742. pt1.toArray(points[1]);
  22743. pt0.toArray(points[2]);
  22744. }
  22745. }
  22746. limitTurnAngle(points, labelLineModel.get('minTurnAngle'));
  22747. labelLine.setShape({
  22748. points: points
  22749. });
  22750. } // Temporal variable for the limitTurnAngle function
  22751. var tmpArr = [];
  22752. var tmpProjPoint = new Point();
  22753. /**
  22754. * Reduce the line segment attached to the label to limit the turn angle between two segments.
  22755. * @param linePoints
  22756. * @param minTurnAngle Radian of minimum turn angle. 0 - 180
  22757. */
  22758. function limitTurnAngle(linePoints, minTurnAngle) {
  22759. if (!(minTurnAngle <= 180 && minTurnAngle > 0)) {
  22760. return;
  22761. }
  22762. minTurnAngle = minTurnAngle / 180 * Math.PI; // The line points can be
  22763. // /pt1----pt2 (label)
  22764. // /
  22765. // pt0/
  22766. pt0.fromArray(linePoints[0]);
  22767. pt1.fromArray(linePoints[1]);
  22768. pt2.fromArray(linePoints[2]);
  22769. Point.sub(dir, pt0, pt1);
  22770. Point.sub(dir2, pt2, pt1);
  22771. var len1 = dir.len();
  22772. var len2 = dir2.len();
  22773. if (len1 < 1e-3 || len2 < 1e-3) {
  22774. return;
  22775. }
  22776. dir.scale(1 / len1);
  22777. dir2.scale(1 / len2);
  22778. var angleCos = dir.dot(dir2);
  22779. var minTurnAngleCos = Math.cos(minTurnAngle);
  22780. if (minTurnAngleCos < angleCos) {
  22781. // Smaller than minTurnAngle
  22782. // Calculate project point of pt0 on pt1-pt2
  22783. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  22784. tmpProjPoint.fromArray(tmpArr); // Calculate new projected length with limited minTurnAngle and get the new connect point
  22785. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI - minTurnAngle)); // Limit the new calculated connect point between pt1 and pt2.
  22786. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  22787. if (isNaN(t)) {
  22788. return;
  22789. }
  22790. if (t < 0) {
  22791. Point.copy(tmpProjPoint, pt1);
  22792. } else if (t > 1) {
  22793. Point.copy(tmpProjPoint, pt2);
  22794. }
  22795. tmpProjPoint.toArray(linePoints[1]);
  22796. }
  22797. }
  22798. /**
  22799. * Limit the angle of line and the surface
  22800. * @param maxSurfaceAngle Radian of minimum turn angle. 0 - 180. 0 is same direction to normal. 180 is opposite
  22801. */
  22802. function limitSurfaceAngle(linePoints, surfaceNormal, maxSurfaceAngle) {
  22803. if (!(maxSurfaceAngle <= 180 && maxSurfaceAngle > 0)) {
  22804. return;
  22805. }
  22806. maxSurfaceAngle = maxSurfaceAngle / 180 * Math.PI;
  22807. pt0.fromArray(linePoints[0]);
  22808. pt1.fromArray(linePoints[1]);
  22809. pt2.fromArray(linePoints[2]);
  22810. Point.sub(dir, pt1, pt0);
  22811. Point.sub(dir2, pt2, pt1);
  22812. var len1 = dir.len();
  22813. var len2 = dir2.len();
  22814. if (len1 < 1e-3 || len2 < 1e-3) {
  22815. return;
  22816. }
  22817. dir.scale(1 / len1);
  22818. dir2.scale(1 / len2);
  22819. var angleCos = dir.dot(surfaceNormal);
  22820. var maxSurfaceAngleCos = Math.cos(maxSurfaceAngle);
  22821. if (angleCos < maxSurfaceAngleCos) {
  22822. // Calculate project point of pt0 on pt1-pt2
  22823. var d = projectPointToLine(pt1.x, pt1.y, pt2.x, pt2.y, pt0.x, pt0.y, tmpArr, false);
  22824. tmpProjPoint.fromArray(tmpArr);
  22825. var HALF_PI = Math.PI / 2;
  22826. var angle2 = Math.acos(dir2.dot(surfaceNormal));
  22827. var newAngle = HALF_PI + angle2 - maxSurfaceAngle;
  22828. if (newAngle >= HALF_PI) {
  22829. // parallel
  22830. Point.copy(tmpProjPoint, pt2);
  22831. } else {
  22832. // Calculate new projected length with limited minTurnAngle and get the new connect point
  22833. tmpProjPoint.scaleAndAdd(dir2, d / Math.tan(Math.PI / 2 - newAngle)); // Limit the new calculated connect point between pt1 and pt2.
  22834. var t = pt2.x !== pt1.x ? (tmpProjPoint.x - pt1.x) / (pt2.x - pt1.x) : (tmpProjPoint.y - pt1.y) / (pt2.y - pt1.y);
  22835. if (isNaN(t)) {
  22836. return;
  22837. }
  22838. if (t < 0) {
  22839. Point.copy(tmpProjPoint, pt1);
  22840. } else if (t > 1) {
  22841. Point.copy(tmpProjPoint, pt2);
  22842. }
  22843. }
  22844. tmpProjPoint.toArray(linePoints[1]);
  22845. }
  22846. }
  22847. function setLabelLineState(labelLine, ignore, stateName, stateModel) {
  22848. var isNormal = stateName === 'normal';
  22849. var stateObj = isNormal ? labelLine : labelLine.ensureState(stateName); // Make sure display.
  22850. stateObj.ignore = ignore; // Set smooth
  22851. var smooth = stateModel.get('smooth');
  22852. if (smooth && smooth === true) {
  22853. smooth = 0.3;
  22854. }
  22855. stateObj.shape = stateObj.shape || {};
  22856. if (smooth > 0) {
  22857. stateObj.shape.smooth = smooth;
  22858. }
  22859. var styleObj = stateModel.getModel('lineStyle').getLineStyle();
  22860. isNormal ? labelLine.useStyle(styleObj) : stateObj.style = styleObj;
  22861. }
  22862. function buildLabelLinePath(path, shape) {
  22863. var smooth = shape.smooth;
  22864. var points = shape.points;
  22865. if (!points) {
  22866. return;
  22867. }
  22868. path.moveTo(points[0][0], points[0][1]);
  22869. if (smooth > 0 && points.length >= 3) {
  22870. var len1 = dist(points[0], points[1]);
  22871. var len2 = dist(points[1], points[2]);
  22872. if (!len1 || !len2) {
  22873. path.lineTo(points[1][0], points[1][1]);
  22874. path.lineTo(points[2][0], points[2][1]);
  22875. return;
  22876. }
  22877. var moveLen = Math.min(len1, len2) * smooth;
  22878. var midPoint0 = lerp([], points[1], points[0], moveLen / len1);
  22879. var midPoint2 = lerp([], points[1], points[2], moveLen / len2);
  22880. var midPoint1 = lerp([], midPoint0, midPoint2, 0.5);
  22881. path.bezierCurveTo(midPoint0[0], midPoint0[1], midPoint0[0], midPoint0[1], midPoint1[0], midPoint1[1]);
  22882. path.bezierCurveTo(midPoint2[0], midPoint2[1], midPoint2[0], midPoint2[1], points[2][0], points[2][1]);
  22883. } else {
  22884. for (var i = 1; i < points.length; i++) {
  22885. path.lineTo(points[i][0], points[i][1]);
  22886. }
  22887. }
  22888. }
  22889. /**
  22890. * Create a label line if necessary and set it's style.
  22891. */
  22892. function setLabelLineStyle(targetEl, statesModels, defaultStyle) {
  22893. var labelLine = targetEl.getTextGuideLine();
  22894. var label = targetEl.getTextContent();
  22895. if (!label) {
  22896. // Not show label line if there is no label.
  22897. if (labelLine) {
  22898. targetEl.removeTextGuideLine();
  22899. }
  22900. return;
  22901. }
  22902. var normalModel = statesModels.normal;
  22903. var showNormal = normalModel.get('show');
  22904. var labelIgnoreNormal = label.ignore;
  22905. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  22906. var stateName = DISPLAY_STATES[i];
  22907. var stateModel = statesModels[stateName];
  22908. var isNormal = stateName === 'normal';
  22909. if (stateModel) {
  22910. var stateShow = stateModel.get('show');
  22911. var isLabelIgnored = isNormal ? labelIgnoreNormal : retrieve2(label.states[stateName] && label.states[stateName].ignore, labelIgnoreNormal);
  22912. if (isLabelIgnored // Not show when label is not shown in this state.
  22913. || !retrieve2(stateShow, showNormal) // Use normal state by default if not set.
  22914. ) {
  22915. var stateObj = isNormal ? labelLine : labelLine && labelLine.states.normal;
  22916. if (stateObj) {
  22917. stateObj.ignore = true;
  22918. }
  22919. continue;
  22920. } // Create labelLine if not exists
  22921. if (!labelLine) {
  22922. labelLine = new Polyline();
  22923. targetEl.setTextGuideLine(labelLine); // Reset state of normal because it's new created.
  22924. // NOTE: NORMAL should always been the first!
  22925. if (!isNormal && (labelIgnoreNormal || !showNormal)) {
  22926. setLabelLineState(labelLine, true, 'normal', statesModels.normal);
  22927. } // Use same state proxy.
  22928. if (targetEl.stateProxy) {
  22929. labelLine.stateProxy = targetEl.stateProxy;
  22930. }
  22931. }
  22932. setLabelLineState(labelLine, false, stateName, stateModel);
  22933. }
  22934. }
  22935. if (labelLine) {
  22936. defaults(labelLine.style, defaultStyle); // Not fill.
  22937. labelLine.style.fill = null;
  22938. var showAbove = normalModel.get('showAbove');
  22939. var labelLineConfig = targetEl.textGuideLineConfig = targetEl.textGuideLineConfig || {};
  22940. labelLineConfig.showAbove = showAbove || false; // Custom the buildPath.
  22941. labelLine.buildPath = buildLabelLinePath;
  22942. }
  22943. }
  22944. function getLabelLineStatesModels(itemModel, labelLineName) {
  22945. labelLineName = labelLineName || 'labelLine';
  22946. var statesModels = {
  22947. normal: itemModel.getModel(labelLineName)
  22948. };
  22949. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  22950. var stateName = SPECIAL_STATES[i];
  22951. statesModels[stateName] = itemModel.getModel([stateName, labelLineName]);
  22952. }
  22953. return statesModels;
  22954. }
  22955. function prepareLayoutList(input) {
  22956. var list = [];
  22957. for (var i = 0; i < input.length; i++) {
  22958. var rawItem = input[i];
  22959. if (rawItem.defaultAttr.ignore) {
  22960. continue;
  22961. }
  22962. var label = rawItem.label;
  22963. var transform = label.getComputedTransform(); // NOTE: Get bounding rect after getComputedTransform, or label may not been updated by the host el.
  22964. var localRect = label.getBoundingRect();
  22965. var isAxisAligned = !transform || transform[1] < 1e-5 && transform[2] < 1e-5;
  22966. var minMargin = label.style.margin || 0;
  22967. var globalRect = localRect.clone();
  22968. globalRect.applyTransform(transform);
  22969. globalRect.x -= minMargin / 2;
  22970. globalRect.y -= minMargin / 2;
  22971. globalRect.width += minMargin;
  22972. globalRect.height += minMargin;
  22973. var obb = isAxisAligned ? new OrientedBoundingRect(localRect, transform) : null;
  22974. list.push({
  22975. label: label,
  22976. labelLine: rawItem.labelLine,
  22977. rect: globalRect,
  22978. localRect: localRect,
  22979. obb: obb,
  22980. priority: rawItem.priority,
  22981. defaultAttr: rawItem.defaultAttr,
  22982. layoutOption: rawItem.computedLayoutOption,
  22983. axisAligned: isAxisAligned,
  22984. transform: transform
  22985. });
  22986. }
  22987. return list;
  22988. }
  22989. function shiftLayout(list, xyDim, sizeDim, minBound, maxBound, balanceShift) {
  22990. var len = list.length;
  22991. if (len < 2) {
  22992. return;
  22993. }
  22994. list.sort(function (a, b) {
  22995. return a.rect[xyDim] - b.rect[xyDim];
  22996. });
  22997. var lastPos = 0;
  22998. var delta;
  22999. var adjusted = false;
  23000. var totalShifts = 0;
  23001. for (var i = 0; i < len; i++) {
  23002. var item = list[i];
  23003. var rect = item.rect;
  23004. delta = rect[xyDim] - lastPos;
  23005. if (delta < 0) {
  23006. // shiftForward(i, len, -delta);
  23007. rect[xyDim] -= delta;
  23008. item.label[xyDim] -= delta;
  23009. adjusted = true;
  23010. }
  23011. var shift = Math.max(-delta, 0);
  23012. totalShifts += shift;
  23013. lastPos = rect[xyDim] + rect[sizeDim];
  23014. }
  23015. if (totalShifts > 0 && balanceShift) {
  23016. // Shift back to make the distribution more equally.
  23017. shiftList(-totalShifts / len, 0, len);
  23018. } // TODO bleedMargin?
  23019. var first = list[0];
  23020. var last = list[len - 1];
  23021. var minGap;
  23022. var maxGap;
  23023. updateMinMaxGap(); // If ends exceed two bounds, squeeze at most 80%, then take the gap of two bounds.
  23024. minGap < 0 && squeezeGaps(-minGap, 0.8);
  23025. maxGap < 0 && squeezeGaps(maxGap, 0.8);
  23026. updateMinMaxGap();
  23027. takeBoundsGap(minGap, maxGap, 1);
  23028. takeBoundsGap(maxGap, minGap, -1); // Handle bailout when there is not enough space.
  23029. updateMinMaxGap();
  23030. if (minGap < 0) {
  23031. squeezeWhenBailout(-minGap);
  23032. }
  23033. if (maxGap < 0) {
  23034. squeezeWhenBailout(maxGap);
  23035. }
  23036. function updateMinMaxGap() {
  23037. minGap = first.rect[xyDim] - minBound;
  23038. maxGap = maxBound - last.rect[xyDim] - last.rect[sizeDim];
  23039. }
  23040. function takeBoundsGap(gapThisBound, gapOtherBound, moveDir) {
  23041. if (gapThisBound < 0) {
  23042. // Move from other gap if can.
  23043. var moveFromMaxGap = Math.min(gapOtherBound, -gapThisBound);
  23044. if (moveFromMaxGap > 0) {
  23045. shiftList(moveFromMaxGap * moveDir, 0, len);
  23046. var remained = moveFromMaxGap + gapThisBound;
  23047. if (remained < 0) {
  23048. squeezeGaps(-remained * moveDir, 1);
  23049. }
  23050. } else {
  23051. squeezeGaps(-gapThisBound * moveDir, 1);
  23052. }
  23053. }
  23054. }
  23055. function shiftList(delta, start, end) {
  23056. if (delta !== 0) {
  23057. adjusted = true;
  23058. }
  23059. for (var i = start; i < end; i++) {
  23060. var item = list[i];
  23061. var rect = item.rect;
  23062. rect[xyDim] += delta;
  23063. item.label[xyDim] += delta;
  23064. }
  23065. } // Squeeze gaps if the labels exceed margin.
  23066. function squeezeGaps(delta, maxSqeezePercent) {
  23067. var gaps = [];
  23068. var totalGaps = 0;
  23069. for (var i = 1; i < len; i++) {
  23070. var prevItemRect = list[i - 1].rect;
  23071. var gap = Math.max(list[i].rect[xyDim] - prevItemRect[xyDim] - prevItemRect[sizeDim], 0);
  23072. gaps.push(gap);
  23073. totalGaps += gap;
  23074. }
  23075. if (!totalGaps) {
  23076. return;
  23077. }
  23078. var squeezePercent = Math.min(Math.abs(delta) / totalGaps, maxSqeezePercent);
  23079. if (delta > 0) {
  23080. for (var i = 0; i < len - 1; i++) {
  23081. // Distribute the shift delta to all gaps.
  23082. var movement = gaps[i] * squeezePercent; // Forward
  23083. shiftList(movement, 0, i + 1);
  23084. }
  23085. } else {
  23086. // Backward
  23087. for (var i = len - 1; i > 0; i--) {
  23088. // Distribute the shift delta to all gaps.
  23089. var movement = gaps[i - 1] * squeezePercent;
  23090. shiftList(-movement, i, len);
  23091. }
  23092. }
  23093. }
  23094. /**
  23095. * Squeeze to allow overlap if there is no more space available.
  23096. * Let other overlapping strategy like hideOverlap do the job instead of keep exceeding the bounds.
  23097. */
  23098. function squeezeWhenBailout(delta) {
  23099. var dir = delta < 0 ? -1 : 1;
  23100. delta = Math.abs(delta);
  23101. var moveForEachLabel = Math.ceil(delta / (len - 1));
  23102. for (var i = 0; i < len - 1; i++) {
  23103. if (dir > 0) {
  23104. // Forward
  23105. shiftList(moveForEachLabel, 0, i + 1);
  23106. } else {
  23107. // Backward
  23108. shiftList(-moveForEachLabel, len - i - 1, len);
  23109. }
  23110. delta -= moveForEachLabel;
  23111. if (delta <= 0) {
  23112. return;
  23113. }
  23114. }
  23115. }
  23116. return adjusted;
  23117. }
  23118. /**
  23119. * Adjust labels on x direction to avoid overlap.
  23120. */
  23121. function shiftLayoutOnX(list, leftBound, rightBound, // If average the shifts on all labels and add them to 0
  23122. // TODO: Not sure if should enable it.
  23123. // Pros: The angle of lines will distribute more equally
  23124. // Cons: In some layout. It may not what user wanted. like in pie. the label of last sector is usually changed unexpectedly.
  23125. balanceShift) {
  23126. return shiftLayout(list, 'x', 'width', leftBound, rightBound, balanceShift);
  23127. }
  23128. /**
  23129. * Adjust labels on y direction to avoid overlap.
  23130. */
  23131. function shiftLayoutOnY(list, topBound, bottomBound, // If average the shifts on all labels and add them to 0
  23132. balanceShift) {
  23133. return shiftLayout(list, 'y', 'height', topBound, bottomBound, balanceShift);
  23134. }
  23135. function hideOverlap(labelList) {
  23136. var displayedLabels = []; // TODO, render overflow visible first, put in the displayedLabels.
  23137. labelList.sort(function (a, b) {
  23138. return b.priority - a.priority;
  23139. });
  23140. var globalRect = new BoundingRect(0, 0, 0, 0);
  23141. function hideEl(el) {
  23142. if (!el.ignore) {
  23143. // Show on emphasis.
  23144. var emphasisState = el.ensureState('emphasis');
  23145. if (emphasisState.ignore == null) {
  23146. emphasisState.ignore = false;
  23147. }
  23148. }
  23149. el.ignore = true;
  23150. }
  23151. for (var i = 0; i < labelList.length; i++) {
  23152. var labelItem = labelList[i];
  23153. var isAxisAligned = labelItem.axisAligned;
  23154. var localRect = labelItem.localRect;
  23155. var transform = labelItem.transform;
  23156. var label = labelItem.label;
  23157. var labelLine = labelItem.labelLine;
  23158. globalRect.copy(labelItem.rect); // Add a threshold because layout may be aligned precisely.
  23159. globalRect.width -= 0.1;
  23160. globalRect.height -= 0.1;
  23161. globalRect.x += 0.05;
  23162. globalRect.y += 0.05;
  23163. var obb = labelItem.obb;
  23164. var overlapped = false;
  23165. for (var j = 0; j < displayedLabels.length; j++) {
  23166. var existsTextCfg = displayedLabels[j]; // Fast rejection.
  23167. if (!globalRect.intersect(existsTextCfg.rect)) {
  23168. continue;
  23169. }
  23170. if (isAxisAligned && existsTextCfg.axisAligned) {
  23171. // Is overlapped
  23172. overlapped = true;
  23173. break;
  23174. }
  23175. if (!existsTextCfg.obb) {
  23176. // If self is not axis aligned. But other is.
  23177. existsTextCfg.obb = new OrientedBoundingRect(existsTextCfg.localRect, existsTextCfg.transform);
  23178. }
  23179. if (!obb) {
  23180. // If self is axis aligned. But other is not.
  23181. obb = new OrientedBoundingRect(localRect, transform);
  23182. }
  23183. if (obb.intersect(existsTextCfg.obb)) {
  23184. overlapped = true;
  23185. break;
  23186. }
  23187. } // TODO Callback to determine if this overlap should be handled?
  23188. if (overlapped) {
  23189. hideEl(label);
  23190. labelLine && hideEl(labelLine);
  23191. } else {
  23192. label.attr('ignore', labelItem.defaultAttr.ignore);
  23193. labelLine && labelLine.attr('ignore', labelItem.defaultAttr.labelGuideIgnore);
  23194. displayedLabels.push(labelItem);
  23195. }
  23196. }
  23197. }
  23198. function cloneArr(points) {
  23199. if (points) {
  23200. var newPoints = [];
  23201. for (var i = 0; i < points.length; i++) {
  23202. newPoints.push(points[i].slice());
  23203. }
  23204. return newPoints;
  23205. }
  23206. }
  23207. function prepareLayoutCallbackParams(labelItem, hostEl) {
  23208. var label = labelItem.label;
  23209. var labelLine = hostEl && hostEl.getTextGuideLine();
  23210. return {
  23211. dataIndex: labelItem.dataIndex,
  23212. dataType: labelItem.dataType,
  23213. seriesIndex: labelItem.seriesModel.seriesIndex,
  23214. text: labelItem.label.style.text,
  23215. rect: labelItem.hostRect,
  23216. labelRect: labelItem.rect,
  23217. // x: labelAttr.x,
  23218. // y: labelAttr.y,
  23219. align: label.style.align,
  23220. verticalAlign: label.style.verticalAlign,
  23221. labelLinePoints: cloneArr(labelLine && labelLine.shape.points)
  23222. };
  23223. }
  23224. var LABEL_OPTION_TO_STYLE_KEYS = ['align', 'verticalAlign', 'width', 'height', 'fontSize'];
  23225. var dummyTransformable = new Transformable();
  23226. var labelLayoutInnerStore = makeInner();
  23227. var labelLineAnimationStore = makeInner();
  23228. function extendWithKeys(target, source, keys) {
  23229. for (var i = 0; i < keys.length; i++) {
  23230. var key = keys[i];
  23231. if (source[key] != null) {
  23232. target[key] = source[key];
  23233. }
  23234. }
  23235. }
  23236. var LABEL_LAYOUT_PROPS = ['x', 'y', 'rotation'];
  23237. var LabelManager =
  23238. /** @class */
  23239. function () {
  23240. function LabelManager() {
  23241. this._labelList = [];
  23242. this._chartViewList = [];
  23243. }
  23244. LabelManager.prototype.clearLabels = function () {
  23245. this._labelList = [];
  23246. this._chartViewList = [];
  23247. };
  23248. /**
  23249. * Add label to manager
  23250. */
  23251. LabelManager.prototype._addLabel = function (dataIndex, dataType, seriesModel, label, layoutOption) {
  23252. var labelStyle = label.style;
  23253. var hostEl = label.__hostTarget;
  23254. var textConfig = hostEl.textConfig || {}; // TODO: If label is in other state.
  23255. var labelTransform = label.getComputedTransform();
  23256. var labelRect = label.getBoundingRect().plain();
  23257. BoundingRect.applyTransform(labelRect, labelRect, labelTransform);
  23258. if (labelTransform) {
  23259. dummyTransformable.setLocalTransform(labelTransform);
  23260. } else {
  23261. // Identity transform.
  23262. dummyTransformable.x = dummyTransformable.y = dummyTransformable.rotation = dummyTransformable.originX = dummyTransformable.originY = 0;
  23263. dummyTransformable.scaleX = dummyTransformable.scaleY = 1;
  23264. }
  23265. var host = label.__hostTarget;
  23266. var hostRect;
  23267. if (host) {
  23268. hostRect = host.getBoundingRect().plain();
  23269. var transform = host.getComputedTransform();
  23270. BoundingRect.applyTransform(hostRect, hostRect, transform);
  23271. }
  23272. var labelGuide = hostRect && host.getTextGuideLine();
  23273. this._labelList.push({
  23274. label: label,
  23275. labelLine: labelGuide,
  23276. seriesModel: seriesModel,
  23277. dataIndex: dataIndex,
  23278. dataType: dataType,
  23279. layoutOption: layoutOption,
  23280. computedLayoutOption: null,
  23281. rect: labelRect,
  23282. hostRect: hostRect,
  23283. // Label with lower priority will be hidden when overlapped
  23284. // Use rect size as default priority
  23285. priority: hostRect ? hostRect.width * hostRect.height : 0,
  23286. // Save default label attributes.
  23287. // For restore if developers want get back to default value in callback.
  23288. defaultAttr: {
  23289. ignore: label.ignore,
  23290. labelGuideIgnore: labelGuide && labelGuide.ignore,
  23291. x: dummyTransformable.x,
  23292. y: dummyTransformable.y,
  23293. rotation: dummyTransformable.rotation,
  23294. style: {
  23295. x: labelStyle.x,
  23296. y: labelStyle.y,
  23297. align: labelStyle.align,
  23298. verticalAlign: labelStyle.verticalAlign,
  23299. width: labelStyle.width,
  23300. height: labelStyle.height,
  23301. fontSize: labelStyle.fontSize
  23302. },
  23303. cursor: label.cursor,
  23304. attachedPos: textConfig.position,
  23305. attachedRot: textConfig.rotation
  23306. }
  23307. });
  23308. };
  23309. LabelManager.prototype.addLabelsOfSeries = function (chartView) {
  23310. var _this = this;
  23311. this._chartViewList.push(chartView);
  23312. var seriesModel = chartView.__model;
  23313. var layoutOption = seriesModel.get('labelLayout');
  23314. /**
  23315. * Ignore layouting if it's not specified anything.
  23316. */
  23317. if (!(isFunction(layoutOption) || keys(layoutOption).length)) {
  23318. return;
  23319. }
  23320. chartView.group.traverse(function (child) {
  23321. if (child.ignore) {
  23322. return true; // Stop traverse descendants.
  23323. } // Only support label being hosted on graphic elements.
  23324. var textEl = child.getTextContent();
  23325. var ecData = getECData(child); // Can only attach the text on the element with dataIndex
  23326. if (textEl && !textEl.disableLabelLayout) {
  23327. _this._addLabel(ecData.dataIndex, ecData.dataType, seriesModel, textEl, layoutOption);
  23328. }
  23329. });
  23330. };
  23331. LabelManager.prototype.updateLayoutConfig = function (api) {
  23332. var width = api.getWidth();
  23333. var height = api.getHeight();
  23334. function createDragHandler(el, labelLineModel) {
  23335. return function () {
  23336. updateLabelLinePoints(el, labelLineModel);
  23337. };
  23338. }
  23339. for (var i = 0; i < this._labelList.length; i++) {
  23340. var labelItem = this._labelList[i];
  23341. var label = labelItem.label;
  23342. var hostEl = label.__hostTarget;
  23343. var defaultLabelAttr = labelItem.defaultAttr;
  23344. var layoutOption = void 0; // TODO A global layout option?
  23345. if (typeof labelItem.layoutOption === 'function') {
  23346. layoutOption = labelItem.layoutOption(prepareLayoutCallbackParams(labelItem, hostEl));
  23347. } else {
  23348. layoutOption = labelItem.layoutOption;
  23349. }
  23350. layoutOption = layoutOption || {};
  23351. labelItem.computedLayoutOption = layoutOption;
  23352. var degreeToRadian = Math.PI / 180;
  23353. if (hostEl) {
  23354. hostEl.setTextConfig({
  23355. // Force to set local false.
  23356. local: false,
  23357. // Ignore position and rotation config on the host el if x or y is changed.
  23358. position: layoutOption.x != null || layoutOption.y != null ? null : defaultLabelAttr.attachedPos,
  23359. // Ignore rotation config on the host el if rotation is changed.
  23360. rotation: layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.attachedRot,
  23361. offset: [layoutOption.dx || 0, layoutOption.dy || 0]
  23362. });
  23363. }
  23364. var needsUpdateLabelLine = false;
  23365. if (layoutOption.x != null) {
  23366. // TODO width of chart view.
  23367. label.x = parsePercent$1(layoutOption.x, width);
  23368. label.setStyle('x', 0); // Ignore movement in style. TODO: origin.
  23369. needsUpdateLabelLine = true;
  23370. } else {
  23371. label.x = defaultLabelAttr.x;
  23372. label.setStyle('x', defaultLabelAttr.style.x);
  23373. }
  23374. if (layoutOption.y != null) {
  23375. // TODO height of chart view.
  23376. label.y = parsePercent$1(layoutOption.y, height);
  23377. label.setStyle('y', 0); // Ignore movement in style.
  23378. needsUpdateLabelLine = true;
  23379. } else {
  23380. label.y = defaultLabelAttr.y;
  23381. label.setStyle('y', defaultLabelAttr.style.y);
  23382. }
  23383. if (layoutOption.labelLinePoints) {
  23384. var guideLine = hostEl.getTextGuideLine();
  23385. if (guideLine) {
  23386. guideLine.setShape({
  23387. points: layoutOption.labelLinePoints
  23388. }); // Not update
  23389. needsUpdateLabelLine = false;
  23390. }
  23391. }
  23392. var labelLayoutStore = labelLayoutInnerStore(label);
  23393. labelLayoutStore.needsUpdateLabelLine = needsUpdateLabelLine;
  23394. label.rotation = layoutOption.rotate != null ? layoutOption.rotate * degreeToRadian : defaultLabelAttr.rotation;
  23395. for (var k = 0; k < LABEL_OPTION_TO_STYLE_KEYS.length; k++) {
  23396. var key = LABEL_OPTION_TO_STYLE_KEYS[k];
  23397. label.setStyle(key, layoutOption[key] != null ? layoutOption[key] : defaultLabelAttr.style[key]);
  23398. }
  23399. if (layoutOption.draggable) {
  23400. label.draggable = true;
  23401. label.cursor = 'move';
  23402. if (hostEl) {
  23403. var hostModel = labelItem.seriesModel;
  23404. if (labelItem.dataIndex != null) {
  23405. var data = labelItem.seriesModel.getData(labelItem.dataType);
  23406. hostModel = data.getItemModel(labelItem.dataIndex);
  23407. }
  23408. label.on('drag', createDragHandler(hostEl, hostModel.getModel('labelLine')));
  23409. }
  23410. } else {
  23411. // TODO Other drag functions?
  23412. label.off('drag');
  23413. label.cursor = defaultLabelAttr.cursor;
  23414. }
  23415. }
  23416. };
  23417. LabelManager.prototype.layout = function (api) {
  23418. var width = api.getWidth();
  23419. var height = api.getHeight();
  23420. var labelList = prepareLayoutList(this._labelList);
  23421. var labelsNeedsAdjustOnX = filter(labelList, function (item) {
  23422. return item.layoutOption.moveOverlap === 'shiftX';
  23423. });
  23424. var labelsNeedsAdjustOnY = filter(labelList, function (item) {
  23425. return item.layoutOption.moveOverlap === 'shiftY';
  23426. });
  23427. shiftLayoutOnX(labelsNeedsAdjustOnX, 0, width);
  23428. shiftLayoutOnY(labelsNeedsAdjustOnY, 0, height);
  23429. var labelsNeedsHideOverlap = filter(labelList, function (item) {
  23430. return item.layoutOption.hideOverlap;
  23431. });
  23432. hideOverlap(labelsNeedsHideOverlap);
  23433. };
  23434. /**
  23435. * Process all labels. Not only labels with layoutOption.
  23436. */
  23437. LabelManager.prototype.processLabelsOverall = function () {
  23438. var _this = this;
  23439. each(this._chartViewList, function (chartView) {
  23440. var seriesModel = chartView.__model;
  23441. var ignoreLabelLineUpdate = chartView.ignoreLabelLineUpdate;
  23442. var animationEnabled = seriesModel.isAnimationEnabled();
  23443. chartView.group.traverse(function (child) {
  23444. if (child.ignore) {
  23445. return true; // Stop traverse descendants.
  23446. }
  23447. var needsUpdateLabelLine = !ignoreLabelLineUpdate;
  23448. var label = child.getTextContent();
  23449. if (!needsUpdateLabelLine && label) {
  23450. needsUpdateLabelLine = labelLayoutInnerStore(label).needsUpdateLabelLine;
  23451. }
  23452. if (needsUpdateLabelLine) {
  23453. _this._updateLabelLine(child, seriesModel);
  23454. }
  23455. if (animationEnabled) {
  23456. _this._animateLabels(child, seriesModel);
  23457. }
  23458. });
  23459. });
  23460. };
  23461. LabelManager.prototype._updateLabelLine = function (el, seriesModel) {
  23462. // Only support label being hosted on graphic elements.
  23463. var textEl = el.getTextContent(); // Update label line style.
  23464. var ecData = getECData(el);
  23465. var dataIndex = ecData.dataIndex; // Only support labelLine on the labels represent data.
  23466. if (textEl && dataIndex != null) {
  23467. var data = seriesModel.getData(ecData.dataType);
  23468. var itemModel = data.getItemModel(dataIndex);
  23469. var defaultStyle = {};
  23470. var visualStyle = data.getItemVisual(dataIndex, 'style');
  23471. var visualType = data.getVisual('drawType'); // Default to be same with main color
  23472. defaultStyle.stroke = visualStyle[visualType];
  23473. var labelLineModel = itemModel.getModel('labelLine');
  23474. setLabelLineStyle(el, getLabelLineStatesModels(itemModel), defaultStyle);
  23475. updateLabelLinePoints(el, labelLineModel);
  23476. }
  23477. };
  23478. LabelManager.prototype._animateLabels = function (el, seriesModel) {
  23479. var textEl = el.getTextContent();
  23480. var guideLine = el.getTextGuideLine(); // Animate
  23481. if (textEl && !textEl.ignore && !textEl.invisible && !el.disableLabelAnimation && !isElementRemoved(el)) {
  23482. var layoutStore = labelLayoutInnerStore(textEl);
  23483. var oldLayout = layoutStore.oldLayout;
  23484. var ecData = getECData(el);
  23485. var dataIndex = ecData.dataIndex;
  23486. var newProps = {
  23487. x: textEl.x,
  23488. y: textEl.y,
  23489. rotation: textEl.rotation
  23490. };
  23491. var data = seriesModel.getData(ecData.dataType);
  23492. if (!oldLayout) {
  23493. textEl.attr(newProps); // Disable fade in animation if value animation is enabled.
  23494. if (!labelInner(textEl).valueAnimation) {
  23495. var oldOpacity = retrieve2(textEl.style.opacity, 1); // Fade in animation
  23496. textEl.style.opacity = 0;
  23497. initProps(textEl, {
  23498. style: {
  23499. opacity: oldOpacity
  23500. }
  23501. }, seriesModel, dataIndex);
  23502. }
  23503. } else {
  23504. textEl.attr(oldLayout); // Make sure the animation from is in the right status.
  23505. var prevStates = el.prevStates;
  23506. if (prevStates) {
  23507. if (indexOf(prevStates, 'select') >= 0) {
  23508. textEl.attr(layoutStore.oldLayoutSelect);
  23509. }
  23510. if (indexOf(prevStates, 'emphasis') >= 0) {
  23511. textEl.attr(layoutStore.oldLayoutEmphasis);
  23512. }
  23513. }
  23514. updateProps(textEl, newProps, seriesModel, dataIndex);
  23515. }
  23516. layoutStore.oldLayout = newProps;
  23517. if (textEl.states.select) {
  23518. var layoutSelect = layoutStore.oldLayoutSelect = {};
  23519. extendWithKeys(layoutSelect, newProps, LABEL_LAYOUT_PROPS);
  23520. extendWithKeys(layoutSelect, textEl.states.select, LABEL_LAYOUT_PROPS);
  23521. }
  23522. if (textEl.states.emphasis) {
  23523. var layoutEmphasis = layoutStore.oldLayoutEmphasis = {};
  23524. extendWithKeys(layoutEmphasis, newProps, LABEL_LAYOUT_PROPS);
  23525. extendWithKeys(layoutEmphasis, textEl.states.emphasis, LABEL_LAYOUT_PROPS);
  23526. }
  23527. animateLabelValue(textEl, dataIndex, data, seriesModel, seriesModel);
  23528. }
  23529. if (guideLine && !guideLine.ignore && !guideLine.invisible) {
  23530. var layoutStore = labelLineAnimationStore(guideLine);
  23531. var oldLayout = layoutStore.oldLayout;
  23532. var newLayout = {
  23533. points: guideLine.shape.points
  23534. };
  23535. if (!oldLayout) {
  23536. guideLine.setShape(newLayout);
  23537. guideLine.style.strokePercent = 0;
  23538. initProps(guideLine, {
  23539. style: {
  23540. strokePercent: 1
  23541. }
  23542. }, seriesModel);
  23543. } else {
  23544. guideLine.attr({
  23545. shape: oldLayout
  23546. });
  23547. updateProps(guideLine, {
  23548. shape: newLayout
  23549. }, seriesModel);
  23550. }
  23551. layoutStore.oldLayout = newLayout;
  23552. }
  23553. };
  23554. return LabelManager;
  23555. }();
  23556. // Inlucdes: pieSelect, pieUnSelect, pieToggleSelect, mapSelect, mapUnSelect, mapToggleSelect
  23557. function createLegacyDataSelectAction(seriesType, ecRegisterAction) {
  23558. function getSeriesIndices(ecModel, payload) {
  23559. var seriesIndices = [];
  23560. ecModel.eachComponent({
  23561. mainType: 'series',
  23562. subType: seriesType,
  23563. query: payload
  23564. }, function (seriesModel) {
  23565. seriesIndices.push(seriesModel.seriesIndex);
  23566. });
  23567. return seriesIndices;
  23568. }
  23569. each([[seriesType + 'ToggleSelect', 'toggleSelect'], [seriesType + 'Select', 'select'], [seriesType + 'UnSelect', 'unselect']], function (eventsMap) {
  23570. ecRegisterAction(eventsMap[0], function (payload, ecModel, api) {
  23571. payload = extend({}, payload);
  23572. if ("development" !== 'production') {
  23573. deprecateReplaceLog(payload.type, eventsMap[1]);
  23574. }
  23575. api.dispatchAction(extend(payload, {
  23576. type: eventsMap[1],
  23577. seriesIndex: getSeriesIndices(ecModel, payload)
  23578. }));
  23579. });
  23580. });
  23581. }
  23582. function handleSeriesLegacySelectEvents(type, eventPostfix, ecIns, ecModel, payload) {
  23583. var legacyEventName = type + eventPostfix;
  23584. if (!ecIns.isSilent(legacyEventName)) {
  23585. if ("development" !== 'production') {
  23586. deprecateLog("event " + legacyEventName + " is deprecated.");
  23587. }
  23588. ecModel.eachComponent({
  23589. mainType: 'series',
  23590. subType: 'pie'
  23591. }, function (seriesModel) {
  23592. var seriesIndex = seriesModel.seriesIndex;
  23593. var selected = payload.selected;
  23594. for (var i = 0; i < selected.length; i++) {
  23595. if (selected[i].seriesIndex === seriesIndex) {
  23596. var data = seriesModel.getData();
  23597. var dataIndex = queryDataIndex(data, payload.fromActionPayload);
  23598. ecIns.trigger(legacyEventName, {
  23599. type: legacyEventName,
  23600. seriesId: seriesModel.id,
  23601. name: isArray(dataIndex) ? data.getName(dataIndex[0]) : data.getName(dataIndex),
  23602. selected: extend({}, seriesModel.option.selectedMap)
  23603. });
  23604. }
  23605. }
  23606. });
  23607. }
  23608. }
  23609. function handleLegacySelectEvents(messageCenter, ecIns, api) {
  23610. messageCenter.on('selectchanged', function (params) {
  23611. var ecModel = api.getModel();
  23612. if (params.isFromClick) {
  23613. handleSeriesLegacySelectEvents('map', 'selectchanged', ecIns, ecModel, params);
  23614. handleSeriesLegacySelectEvents('pie', 'selectchanged', ecIns, ecModel, params);
  23615. } else if (params.fromAction === 'select') {
  23616. handleSeriesLegacySelectEvents('map', 'selected', ecIns, ecModel, params);
  23617. handleSeriesLegacySelectEvents('pie', 'selected', ecIns, ecModel, params);
  23618. } else if (params.fromAction === 'unselect') {
  23619. handleSeriesLegacySelectEvents('map', 'unselected', ecIns, ecModel, params);
  23620. handleSeriesLegacySelectEvents('pie', 'unselected', ecIns, ecModel, params);
  23621. }
  23622. });
  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. /**
  23643. * AUTO-GENERATED FILE. DO NOT MODIFY.
  23644. */
  23645. /*
  23646. * Licensed to the Apache Software Foundation (ASF) under one
  23647. * or more contributor license agreements. See the NOTICE file
  23648. * distributed with this work for additional information
  23649. * regarding copyright ownership. The ASF licenses this file
  23650. * to you under the Apache License, Version 2.0 (the
  23651. * "License"); you may not use this file except in compliance
  23652. * with the License. You may obtain a copy of the License at
  23653. *
  23654. * http://www.apache.org/licenses/LICENSE-2.0
  23655. *
  23656. * Unless required by applicable law or agreed to in writing,
  23657. * software distributed under the License is distributed on an
  23658. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23659. * KIND, either express or implied. See the License for the
  23660. * specific language governing permissions and limitations
  23661. * under the License.
  23662. */
  23663. function findEventDispatcher(target, det, returnFirstMatch) {
  23664. var found;
  23665. while (target) {
  23666. if (det(target)) {
  23667. found = target;
  23668. if (returnFirstMatch) {
  23669. break;
  23670. }
  23671. }
  23672. target = target.__hostTarget || target.parent;
  23673. }
  23674. return found;
  23675. }
  23676. var wmUniqueIndex = Math.round(Math.random() * 9);
  23677. var WeakMap = (function () {
  23678. function WeakMap() {
  23679. this._id = '__ec_inner_' + wmUniqueIndex++;
  23680. }
  23681. WeakMap.prototype.get = function (key) {
  23682. return this._guard(key)[this._id];
  23683. };
  23684. WeakMap.prototype.set = function (key, value) {
  23685. var target = this._guard(key);
  23686. if (typeof Object.defineProperty === 'function') {
  23687. Object.defineProperty(target, this._id, {
  23688. value: value,
  23689. enumerable: false,
  23690. configurable: true
  23691. });
  23692. }
  23693. else {
  23694. target[this._id] = value;
  23695. }
  23696. return this;
  23697. };
  23698. WeakMap.prototype["delete"] = function (key) {
  23699. if (this.has(key)) {
  23700. delete this._guard(key)[this._id];
  23701. return true;
  23702. }
  23703. return false;
  23704. };
  23705. WeakMap.prototype.has = function (key) {
  23706. return !!this._guard(key)[this._id];
  23707. };
  23708. WeakMap.prototype._guard = function (key) {
  23709. if (key !== Object(key)) {
  23710. throw TypeError('Value of WeakMap is not a non-null object.');
  23711. }
  23712. return key;
  23713. };
  23714. return WeakMap;
  23715. }());
  23716. /**
  23717. * Triangle shape
  23718. * @inner
  23719. */
  23720. var Triangle = Path.extend({
  23721. type: 'triangle',
  23722. shape: {
  23723. cx: 0,
  23724. cy: 0,
  23725. width: 0,
  23726. height: 0
  23727. },
  23728. buildPath: function (path, shape) {
  23729. var cx = shape.cx;
  23730. var cy = shape.cy;
  23731. var width = shape.width / 2;
  23732. var height = shape.height / 2;
  23733. path.moveTo(cx, cy - height);
  23734. path.lineTo(cx + width, cy + height);
  23735. path.lineTo(cx - width, cy + height);
  23736. path.closePath();
  23737. }
  23738. });
  23739. /**
  23740. * Diamond shape
  23741. * @inner
  23742. */
  23743. var Diamond = Path.extend({
  23744. type: 'diamond',
  23745. shape: {
  23746. cx: 0,
  23747. cy: 0,
  23748. width: 0,
  23749. height: 0
  23750. },
  23751. buildPath: function (path, shape) {
  23752. var cx = shape.cx;
  23753. var cy = shape.cy;
  23754. var width = shape.width / 2;
  23755. var height = shape.height / 2;
  23756. path.moveTo(cx, cy - height);
  23757. path.lineTo(cx + width, cy);
  23758. path.lineTo(cx, cy + height);
  23759. path.lineTo(cx - width, cy);
  23760. path.closePath();
  23761. }
  23762. });
  23763. /**
  23764. * Pin shape
  23765. * @inner
  23766. */
  23767. var Pin = Path.extend({
  23768. type: 'pin',
  23769. shape: {
  23770. // x, y on the cusp
  23771. x: 0,
  23772. y: 0,
  23773. width: 0,
  23774. height: 0
  23775. },
  23776. buildPath: function (path, shape) {
  23777. var x = shape.x;
  23778. var y = shape.y;
  23779. var w = shape.width / 5 * 3; // Height must be larger than width
  23780. var h = Math.max(w, shape.height);
  23781. var r = w / 2; // Dist on y with tangent point and circle center
  23782. var dy = r * r / (h - r);
  23783. var cy = y - h + r + dy;
  23784. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  23785. var dx = Math.cos(angle) * r;
  23786. var tanX = Math.sin(angle);
  23787. var tanY = Math.cos(angle);
  23788. var cpLen = r * 0.6;
  23789. var cpLen2 = r * 0.7;
  23790. path.moveTo(x - dx, cy + dy);
  23791. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  23792. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  23793. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  23794. path.closePath();
  23795. }
  23796. });
  23797. /**
  23798. * Arrow shape
  23799. * @inner
  23800. */
  23801. var Arrow = Path.extend({
  23802. type: 'arrow',
  23803. shape: {
  23804. x: 0,
  23805. y: 0,
  23806. width: 0,
  23807. height: 0
  23808. },
  23809. buildPath: function (ctx, shape) {
  23810. var height = shape.height;
  23811. var width = shape.width;
  23812. var x = shape.x;
  23813. var y = shape.y;
  23814. var dx = width / 3 * 2;
  23815. ctx.moveTo(x, y);
  23816. ctx.lineTo(x + dx, y + height);
  23817. ctx.lineTo(x, y + height / 4 * 3);
  23818. ctx.lineTo(x - dx, y + height);
  23819. ctx.lineTo(x, y);
  23820. ctx.closePath();
  23821. }
  23822. });
  23823. /**
  23824. * Map of path contructors
  23825. */
  23826. // TODO Use function to build symbol path.
  23827. var symbolCtors = {
  23828. // Use small height rect to simulate line.
  23829. // Avoid using stroke.
  23830. line: Rect,
  23831. rect: Rect,
  23832. roundRect: Rect,
  23833. square: Rect,
  23834. circle: Circle,
  23835. diamond: Diamond,
  23836. pin: Pin,
  23837. arrow: Arrow,
  23838. triangle: Triangle
  23839. }; // NOTICE Only use fill. No line!
  23840. var symbolShapeMakers = {
  23841. line: function (x, y, w, h, shape) {
  23842. var thickness = 2; // A thin line
  23843. shape.x = x;
  23844. shape.y = y + h / 2 - thickness / 2;
  23845. shape.width = w;
  23846. shape.height = thickness;
  23847. },
  23848. rect: function (x, y, w, h, shape) {
  23849. shape.x = x;
  23850. shape.y = y;
  23851. shape.width = w;
  23852. shape.height = h;
  23853. },
  23854. roundRect: function (x, y, w, h, shape) {
  23855. shape.x = x;
  23856. shape.y = y;
  23857. shape.width = w;
  23858. shape.height = h;
  23859. shape.r = Math.min(w, h) / 4;
  23860. },
  23861. square: function (x, y, w, h, shape) {
  23862. var size = Math.min(w, h);
  23863. shape.x = x;
  23864. shape.y = y;
  23865. shape.width = size;
  23866. shape.height = size;
  23867. },
  23868. circle: function (x, y, w, h, shape) {
  23869. // Put circle in the center of square
  23870. shape.cx = x + w / 2;
  23871. shape.cy = y + h / 2;
  23872. shape.r = Math.min(w, h) / 2;
  23873. },
  23874. diamond: function (x, y, w, h, shape) {
  23875. shape.cx = x + w / 2;
  23876. shape.cy = y + h / 2;
  23877. shape.width = w;
  23878. shape.height = h;
  23879. },
  23880. pin: function (x, y, w, h, shape) {
  23881. shape.x = x + w / 2;
  23882. shape.y = y + h / 2;
  23883. shape.width = w;
  23884. shape.height = h;
  23885. },
  23886. arrow: function (x, y, w, h, shape) {
  23887. shape.x = x + w / 2;
  23888. shape.y = y + h / 2;
  23889. shape.width = w;
  23890. shape.height = h;
  23891. },
  23892. triangle: function (x, y, w, h, shape) {
  23893. shape.cx = x + w / 2;
  23894. shape.cy = y + h / 2;
  23895. shape.width = w;
  23896. shape.height = h;
  23897. }
  23898. };
  23899. var symbolBuildProxies = {};
  23900. each(symbolCtors, function (Ctor, name) {
  23901. symbolBuildProxies[name] = new Ctor();
  23902. });
  23903. var SymbolClz = Path.extend({
  23904. type: 'symbol',
  23905. shape: {
  23906. symbolType: '',
  23907. x: 0,
  23908. y: 0,
  23909. width: 0,
  23910. height: 0
  23911. },
  23912. calculateTextPosition: function (out, config, rect) {
  23913. var res = calculateTextPosition(out, config, rect);
  23914. var shape = this.shape;
  23915. if (shape && shape.symbolType === 'pin' && config.position === 'inside') {
  23916. res.y = rect.y + rect.height * 0.4;
  23917. }
  23918. return res;
  23919. },
  23920. buildPath: function (ctx, shape, inBundle) {
  23921. var symbolType = shape.symbolType;
  23922. if (symbolType !== 'none') {
  23923. var proxySymbol = symbolBuildProxies[symbolType];
  23924. if (!proxySymbol) {
  23925. // Default rect
  23926. symbolType = 'rect';
  23927. proxySymbol = symbolBuildProxies[symbolType];
  23928. }
  23929. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  23930. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  23931. }
  23932. }
  23933. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  23934. function symbolPathSetColor(color, innerColor) {
  23935. if (this.type !== 'image') {
  23936. var symbolStyle = this.style;
  23937. if (this.__isEmptyBrush) {
  23938. symbolStyle.stroke = color;
  23939. symbolStyle.fill = innerColor || '#fff'; // TODO Same width with lineStyle in LineView.
  23940. symbolStyle.lineWidth = 2;
  23941. } else {
  23942. symbolStyle.fill = color;
  23943. }
  23944. this.markRedraw();
  23945. }
  23946. }
  23947. /**
  23948. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  23949. */
  23950. function createSymbol(symbolType, x, y, w, h, color, // whether to keep the ratio of w/h,
  23951. keepAspect) {
  23952. // TODO Support image object, DynamicImage.
  23953. var isEmpty = symbolType.indexOf('empty') === 0;
  23954. if (isEmpty) {
  23955. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  23956. }
  23957. var symbolPath;
  23958. if (symbolType.indexOf('image://') === 0) {
  23959. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23960. } else if (symbolType.indexOf('path://') === 0) {
  23961. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  23962. } else {
  23963. symbolPath = new SymbolClz({
  23964. shape: {
  23965. symbolType: symbolType,
  23966. x: x,
  23967. y: y,
  23968. width: w,
  23969. height: h
  23970. }
  23971. });
  23972. }
  23973. symbolPath.__isEmptyBrush = isEmpty; // TODO Should deprecate setColor
  23974. symbolPath.setColor = symbolPathSetColor;
  23975. if (color) {
  23976. symbolPath.setColor(color);
  23977. }
  23978. return symbolPath;
  23979. }
  23980. function createLinearGradient(ctx, obj, rect) {
  23981. var x = obj.x == null ? 0 : obj.x;
  23982. var x2 = obj.x2 == null ? 1 : obj.x2;
  23983. var y = obj.y == null ? 0 : obj.y;
  23984. var y2 = obj.y2 == null ? 0 : obj.y2;
  23985. if (!obj.global) {
  23986. x = x * rect.width + rect.x;
  23987. x2 = x2 * rect.width + rect.x;
  23988. y = y * rect.height + rect.y;
  23989. y2 = y2 * rect.height + rect.y;
  23990. }
  23991. x = isNaN(x) ? 0 : x;
  23992. x2 = isNaN(x2) ? 1 : x2;
  23993. y = isNaN(y) ? 0 : y;
  23994. y2 = isNaN(y2) ? 0 : y2;
  23995. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  23996. return canvasGradient;
  23997. }
  23998. function createRadialGradient(ctx, obj, rect) {
  23999. var width = rect.width;
  24000. var height = rect.height;
  24001. var min = Math.min(width, height);
  24002. var x = obj.x == null ? 0.5 : obj.x;
  24003. var y = obj.y == null ? 0.5 : obj.y;
  24004. var r = obj.r == null ? 0.5 : obj.r;
  24005. if (!obj.global) {
  24006. x = x * width + rect.x;
  24007. y = y * height + rect.y;
  24008. r = r * min;
  24009. }
  24010. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  24011. return canvasGradient;
  24012. }
  24013. function getCanvasGradient(ctx, obj, rect) {
  24014. var canvasGradient = obj.type === 'radial'
  24015. ? createRadialGradient(ctx, obj, rect)
  24016. : createLinearGradient(ctx, obj, rect);
  24017. var colorStops = obj.colorStops;
  24018. for (var i = 0; i < colorStops.length; i++) {
  24019. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  24020. }
  24021. return canvasGradient;
  24022. }
  24023. function isClipPathChanged(clipPaths, prevClipPaths) {
  24024. if (clipPaths === prevClipPaths || (!clipPaths && !prevClipPaths)) {
  24025. return false;
  24026. }
  24027. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  24028. return true;
  24029. }
  24030. for (var i = 0; i < clipPaths.length; i++) {
  24031. if (clipPaths[i] !== prevClipPaths[i]) {
  24032. return true;
  24033. }
  24034. }
  24035. return false;
  24036. }
  24037. function normalizeLineDash(lineType, lineWidth) {
  24038. if (!lineType || lineType === 'solid' || !(lineWidth > 0)) {
  24039. return null;
  24040. }
  24041. lineWidth = lineWidth || 1;
  24042. return lineType === 'dashed'
  24043. ? [4 * lineWidth, 2 * lineWidth]
  24044. : lineType === 'dotted'
  24045. ? [lineWidth]
  24046. : isNumber(lineType)
  24047. ? [lineType] : isArray(lineType) ? lineType : null;
  24048. }
  24049. var pathProxyForDraw = new PathProxy(true);
  24050. function styleHasStroke(style) {
  24051. var stroke = style.stroke;
  24052. return !(stroke == null || stroke === 'none' || !(style.lineWidth > 0));
  24053. }
  24054. function styleHasFill(style) {
  24055. var fill = style.fill;
  24056. return fill != null && fill !== 'none';
  24057. }
  24058. function doFillPath(ctx, style) {
  24059. if (style.fillOpacity != null && style.fillOpacity !== 1) {
  24060. var originalGlobalAlpha = ctx.globalAlpha;
  24061. ctx.globalAlpha = style.fillOpacity * style.opacity;
  24062. ctx.fill();
  24063. ctx.globalAlpha = originalGlobalAlpha;
  24064. }
  24065. else {
  24066. ctx.fill();
  24067. }
  24068. }
  24069. function doStrokePath(ctx, style) {
  24070. if (style.strokeOpacity != null && style.strokeOpacity !== 1) {
  24071. var originalGlobalAlpha = ctx.globalAlpha;
  24072. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  24073. ctx.stroke();
  24074. ctx.globalAlpha = originalGlobalAlpha;
  24075. }
  24076. else {
  24077. ctx.stroke();
  24078. }
  24079. }
  24080. function createCanvasPattern(ctx, pattern, el) {
  24081. var image = createOrUpdateImage(pattern.image, pattern.__image, el);
  24082. if (isImageReady(image)) {
  24083. var canvasPattern = ctx.createPattern(image, pattern.repeat || 'repeat');
  24084. if (typeof DOMMatrix === 'function') {
  24085. var matrix = new DOMMatrix();
  24086. matrix.rotateSelf(0, 0, (pattern.rotation || 0) / Math.PI * 180);
  24087. matrix.scaleSelf((pattern.scaleX || 1), (pattern.scaleY || 1));
  24088. matrix.translateSelf((pattern.x || 0), (pattern.y || 0));
  24089. canvasPattern.setTransform(matrix);
  24090. }
  24091. return canvasPattern;
  24092. }
  24093. }
  24094. function brushPath(ctx, el, style, inBatch) {
  24095. var hasStroke = styleHasStroke(style);
  24096. var hasFill = styleHasFill(style);
  24097. var strokePercent = style.strokePercent;
  24098. var strokePart = strokePercent < 1;
  24099. var firstDraw = !el.path;
  24100. if ((!el.silent || strokePart) && firstDraw) {
  24101. el.createPathProxy();
  24102. }
  24103. var path = el.path || pathProxyForDraw;
  24104. if (!inBatch) {
  24105. var fill = style.fill;
  24106. var stroke = style.stroke;
  24107. var hasFillGradient = hasFill && !!fill.colorStops;
  24108. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  24109. var hasFillPattern = hasFill && !!fill.image;
  24110. var hasStrokePattern = hasStroke && !!stroke.image;
  24111. var fillGradient = void 0;
  24112. var strokeGradient = void 0;
  24113. var fillPattern = void 0;
  24114. var strokePattern = void 0;
  24115. var rect = void 0;
  24116. if (hasFillGradient || hasStrokeGradient) {
  24117. rect = el.getBoundingRect();
  24118. }
  24119. if (hasFillGradient) {
  24120. fillGradient = el.__dirty
  24121. ? getCanvasGradient(ctx, fill, rect)
  24122. : el.__canvasFillGradient;
  24123. el.__canvasFillGradient = fillGradient;
  24124. }
  24125. if (hasStrokeGradient) {
  24126. strokeGradient = el.__dirty
  24127. ? getCanvasGradient(ctx, stroke, rect)
  24128. : el.__canvasStrokeGradient;
  24129. el.__canvasStrokeGradient = strokeGradient;
  24130. }
  24131. if (hasFillPattern) {
  24132. fillPattern = (el.__dirty || !el.__canvasFillPattern)
  24133. ? createCanvasPattern(ctx, fill, el)
  24134. : el.__canvasFillPattern;
  24135. el.__canvasFillPattern = fillPattern;
  24136. }
  24137. if (hasStrokePattern) {
  24138. strokePattern = (el.__dirty || !el.__canvasStrokePattern)
  24139. ? createCanvasPattern(ctx, stroke, el)
  24140. : el.__canvasStrokePattern;
  24141. el.__canvasStrokePattern = fillPattern;
  24142. }
  24143. if (hasFillGradient) {
  24144. ctx.fillStyle = fillGradient;
  24145. }
  24146. else if (hasFillPattern) {
  24147. if (fillPattern) {
  24148. ctx.fillStyle = fillPattern;
  24149. }
  24150. else {
  24151. hasFill = false;
  24152. }
  24153. }
  24154. if (hasStrokeGradient) {
  24155. ctx.strokeStyle = strokeGradient;
  24156. }
  24157. else if (hasStrokePattern) {
  24158. if (strokePattern) {
  24159. ctx.strokeStyle = strokePattern;
  24160. }
  24161. else {
  24162. hasStroke = false;
  24163. }
  24164. }
  24165. }
  24166. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24167. var lineDashOffset = style.lineDashOffset;
  24168. var ctxLineDash = !!ctx.setLineDash;
  24169. var scale = el.getGlobalScale();
  24170. path.setScale(scale[0], scale[1], el.segmentIgnoreThreshold);
  24171. if (lineDash) {
  24172. var lineScale_1 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24173. if (lineScale_1 && lineScale_1 !== 1) {
  24174. lineDash = map(lineDash, function (rawVal) {
  24175. return rawVal / lineScale_1;
  24176. });
  24177. lineDashOffset /= lineScale_1;
  24178. }
  24179. }
  24180. var needsRebuild = true;
  24181. if (firstDraw || (el.__dirty & Path.SHAPE_CHANGED_BIT)
  24182. || (lineDash && !ctxLineDash && hasStroke)) {
  24183. path.setDPR(ctx.dpr);
  24184. if (strokePart) {
  24185. path.setContext(null);
  24186. }
  24187. else {
  24188. path.setContext(ctx);
  24189. needsRebuild = false;
  24190. }
  24191. path.reset();
  24192. if (lineDash && !ctxLineDash) {
  24193. path.setLineDash(lineDash);
  24194. path.setLineDashOffset(lineDashOffset);
  24195. }
  24196. el.buildPath(path, el.shape, inBatch);
  24197. path.toStatic();
  24198. el.pathUpdated();
  24199. }
  24200. if (needsRebuild) {
  24201. path.rebuildPath(ctx, strokePart ? strokePercent : 1);
  24202. }
  24203. if (lineDash && ctxLineDash) {
  24204. ctx.setLineDash(lineDash);
  24205. ctx.lineDashOffset = lineDashOffset;
  24206. }
  24207. if (!inBatch) {
  24208. if (style.strokeFirst) {
  24209. if (hasStroke) {
  24210. doStrokePath(ctx, style);
  24211. }
  24212. if (hasFill) {
  24213. doFillPath(ctx, style);
  24214. }
  24215. }
  24216. else {
  24217. if (hasFill) {
  24218. doFillPath(ctx, style);
  24219. }
  24220. if (hasStroke) {
  24221. doStrokePath(ctx, style);
  24222. }
  24223. }
  24224. }
  24225. if (lineDash && ctxLineDash) {
  24226. ctx.setLineDash([]);
  24227. }
  24228. }
  24229. function brushImage(ctx, el, style) {
  24230. var image = el.__image = createOrUpdateImage(style.image, el.__image, el, el.onload);
  24231. if (!image || !isImageReady(image)) {
  24232. return;
  24233. }
  24234. var x = style.x || 0;
  24235. var y = style.y || 0;
  24236. var width = el.getWidth();
  24237. var height = el.getHeight();
  24238. var aspect = image.width / image.height;
  24239. if (width == null && height != null) {
  24240. width = height * aspect;
  24241. }
  24242. else if (height == null && width != null) {
  24243. height = width / aspect;
  24244. }
  24245. else if (width == null && height == null) {
  24246. width = image.width;
  24247. height = image.height;
  24248. }
  24249. if (style.sWidth && style.sHeight) {
  24250. var sx = style.sx || 0;
  24251. var sy = style.sy || 0;
  24252. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  24253. }
  24254. else if (style.sx && style.sy) {
  24255. var sx = style.sx;
  24256. var sy = style.sy;
  24257. var sWidth = width - sx;
  24258. var sHeight = height - sy;
  24259. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  24260. }
  24261. else {
  24262. ctx.drawImage(image, x, y, width, height);
  24263. }
  24264. }
  24265. function brushText(ctx, el, style) {
  24266. var text = style.text;
  24267. text != null && (text += '');
  24268. if (text) {
  24269. ctx.font = style.font || DEFAULT_FONT;
  24270. ctx.textAlign = style.textAlign;
  24271. ctx.textBaseline = style.textBaseline;
  24272. var hasLineDash = void 0;
  24273. if (ctx.setLineDash) {
  24274. var lineDash = style.lineDash && style.lineWidth > 0 && normalizeLineDash(style.lineDash, style.lineWidth);
  24275. var lineDashOffset = style.lineDashOffset;
  24276. if (lineDash) {
  24277. var lineScale_2 = (style.strokeNoScale && el.getLineScale) ? el.getLineScale() : 1;
  24278. if (lineScale_2 && lineScale_2 !== 1) {
  24279. lineDash = map(lineDash, function (rawVal) {
  24280. return rawVal / lineScale_2;
  24281. });
  24282. lineDashOffset /= lineScale_2;
  24283. }
  24284. ctx.setLineDash(lineDash);
  24285. ctx.lineDashOffset = lineDashOffset;
  24286. hasLineDash = true;
  24287. }
  24288. }
  24289. if (style.strokeFirst) {
  24290. if (styleHasStroke(style)) {
  24291. ctx.strokeText(text, style.x, style.y);
  24292. }
  24293. if (styleHasFill(style)) {
  24294. ctx.fillText(text, style.x, style.y);
  24295. }
  24296. }
  24297. else {
  24298. if (styleHasFill(style)) {
  24299. ctx.fillText(text, style.x, style.y);
  24300. }
  24301. if (styleHasStroke(style)) {
  24302. ctx.strokeText(text, style.x, style.y);
  24303. }
  24304. }
  24305. if (hasLineDash) {
  24306. ctx.setLineDash([]);
  24307. }
  24308. }
  24309. }
  24310. var SHADOW_NUMBER_PROPS = ['shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  24311. var STROKE_PROPS = [
  24312. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  24313. ];
  24314. function bindCommonProps(ctx, style, prevStyle, forceSetAll, scope) {
  24315. var styleChanged = false;
  24316. if (!forceSetAll) {
  24317. prevStyle = prevStyle || {};
  24318. if (style === prevStyle) {
  24319. return false;
  24320. }
  24321. }
  24322. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24323. if (!styleChanged) {
  24324. flushPathDrawn(ctx, scope);
  24325. styleChanged = true;
  24326. }
  24327. ctx.globalAlpha = style.opacity == null ? DEFAULT_COMMON_STYLE.opacity : style.opacity;
  24328. }
  24329. if (forceSetAll || style.blend !== prevStyle.blend) {
  24330. if (!styleChanged) {
  24331. flushPathDrawn(ctx, scope);
  24332. styleChanged = true;
  24333. }
  24334. ctx.globalCompositeOperation = style.blend || DEFAULT_COMMON_STYLE.blend;
  24335. }
  24336. for (var i = 0; i < SHADOW_NUMBER_PROPS.length; i++) {
  24337. var propName = SHADOW_NUMBER_PROPS[i];
  24338. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24339. if (!styleChanged) {
  24340. flushPathDrawn(ctx, scope);
  24341. styleChanged = true;
  24342. }
  24343. ctx[propName] = ctx.dpr * (style[propName] || 0);
  24344. }
  24345. }
  24346. if (forceSetAll || style.shadowColor !== prevStyle.shadowColor) {
  24347. if (!styleChanged) {
  24348. flushPathDrawn(ctx, scope);
  24349. styleChanged = true;
  24350. }
  24351. ctx.shadowColor = style.shadowColor || DEFAULT_COMMON_STYLE.shadowColor;
  24352. }
  24353. return styleChanged;
  24354. }
  24355. function bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetAll, scope) {
  24356. var style = getStyle(el, scope.inHover);
  24357. var prevStyle = forceSetAll
  24358. ? null
  24359. : (prevEl && getStyle(prevEl, scope.inHover) || {});
  24360. if (style === prevStyle) {
  24361. return false;
  24362. }
  24363. var styleChanged = bindCommonProps(ctx, style, prevStyle, forceSetAll, scope);
  24364. if (forceSetAll || style.fill !== prevStyle.fill) {
  24365. if (!styleChanged) {
  24366. flushPathDrawn(ctx, scope);
  24367. styleChanged = true;
  24368. }
  24369. ctx.fillStyle = style.fill;
  24370. }
  24371. if (forceSetAll || style.stroke !== prevStyle.stroke) {
  24372. if (!styleChanged) {
  24373. flushPathDrawn(ctx, scope);
  24374. styleChanged = true;
  24375. }
  24376. ctx.strokeStyle = style.stroke;
  24377. }
  24378. if (forceSetAll || style.opacity !== prevStyle.opacity) {
  24379. if (!styleChanged) {
  24380. flushPathDrawn(ctx, scope);
  24381. styleChanged = true;
  24382. }
  24383. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  24384. }
  24385. if (el.hasStroke()) {
  24386. var lineWidth = style.lineWidth;
  24387. var newLineWidth = lineWidth / ((style.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1);
  24388. if (ctx.lineWidth !== newLineWidth) {
  24389. if (!styleChanged) {
  24390. flushPathDrawn(ctx, scope);
  24391. styleChanged = true;
  24392. }
  24393. ctx.lineWidth = newLineWidth;
  24394. }
  24395. }
  24396. for (var i = 0; i < STROKE_PROPS.length; i++) {
  24397. var prop = STROKE_PROPS[i];
  24398. var propName = prop[0];
  24399. if (forceSetAll || style[propName] !== prevStyle[propName]) {
  24400. if (!styleChanged) {
  24401. flushPathDrawn(ctx, scope);
  24402. styleChanged = true;
  24403. }
  24404. ctx[propName] = style[propName] || prop[1];
  24405. }
  24406. }
  24407. return styleChanged;
  24408. }
  24409. function bindImageStyle(ctx, el, prevEl, forceSetAll, scope) {
  24410. return bindCommonProps(ctx, getStyle(el, scope.inHover), prevEl && getStyle(prevEl, scope.inHover), forceSetAll, scope);
  24411. }
  24412. function setContextTransform(ctx, el) {
  24413. var m = el.transform;
  24414. var dpr = ctx.dpr || 1;
  24415. if (m) {
  24416. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  24417. }
  24418. else {
  24419. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  24420. }
  24421. }
  24422. function updateClipStatus(clipPaths, ctx, scope) {
  24423. var allClipped = false;
  24424. for (var i = 0; i < clipPaths.length; i++) {
  24425. var clipPath = clipPaths[i];
  24426. allClipped = allClipped || clipPath.isZeroArea();
  24427. setContextTransform(ctx, clipPath);
  24428. ctx.beginPath();
  24429. clipPath.buildPath(ctx, clipPath.shape);
  24430. ctx.clip();
  24431. }
  24432. scope.allClipped = allClipped;
  24433. }
  24434. function isTransformChanged(m0, m1) {
  24435. if (m0 && m1) {
  24436. return m0[0] !== m1[0]
  24437. || m0[1] !== m1[1]
  24438. || m0[2] !== m1[2]
  24439. || m0[3] !== m1[3]
  24440. || m0[4] !== m1[4]
  24441. || m0[5] !== m1[5];
  24442. }
  24443. else if (!m0 && !m1) {
  24444. return false;
  24445. }
  24446. return true;
  24447. }
  24448. var DRAW_TYPE_PATH = 1;
  24449. var DRAW_TYPE_IMAGE = 2;
  24450. var DRAW_TYPE_TEXT = 3;
  24451. var DRAW_TYPE_INCREMENTAL = 4;
  24452. function canPathBatch(style) {
  24453. var hasFill = styleHasFill(style);
  24454. var hasStroke = styleHasStroke(style);
  24455. return !(style.lineDash
  24456. || !(+hasFill ^ +hasStroke)
  24457. || (hasFill && typeof style.fill !== 'string')
  24458. || (hasStroke && typeof style.stroke !== 'string')
  24459. || style.strokePercent < 1
  24460. || style.strokeOpacity < 1
  24461. || style.fillOpacity < 1);
  24462. }
  24463. function flushPathDrawn(ctx, scope) {
  24464. scope.batchFill && ctx.fill();
  24465. scope.batchStroke && ctx.stroke();
  24466. scope.batchFill = '';
  24467. scope.batchStroke = '';
  24468. }
  24469. function getStyle(el, inHover) {
  24470. return inHover ? (el.__hoverStyle || el.style) : el.style;
  24471. }
  24472. function brushSingle(ctx, el) {
  24473. brush(ctx, el, { inHover: false, viewWidth: 0, viewHeight: 0 }, true);
  24474. }
  24475. function brush(ctx, el, scope, isLast) {
  24476. var m = el.transform;
  24477. if (!el.shouldBePainted(scope.viewWidth, scope.viewHeight, false, false)) {
  24478. el.__dirty &= ~Element.REDARAW_BIT;
  24479. el.__isRendered = false;
  24480. return;
  24481. }
  24482. var clipPaths = el.__clipPaths;
  24483. var prevElClipPaths = scope.prevElClipPaths;
  24484. var forceSetTransform = false;
  24485. var forceSetStyle = false;
  24486. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  24487. if (prevElClipPaths && prevElClipPaths.length) {
  24488. flushPathDrawn(ctx, scope);
  24489. ctx.restore();
  24490. forceSetStyle = forceSetTransform = true;
  24491. scope.prevElClipPaths = null;
  24492. scope.allClipped = false;
  24493. scope.prevEl = null;
  24494. }
  24495. if (clipPaths && clipPaths.length) {
  24496. flushPathDrawn(ctx, scope);
  24497. ctx.save();
  24498. updateClipStatus(clipPaths, ctx, scope);
  24499. forceSetTransform = true;
  24500. }
  24501. scope.prevElClipPaths = clipPaths;
  24502. }
  24503. if (scope.allClipped) {
  24504. el.__isRendered = false;
  24505. return;
  24506. }
  24507. el.beforeBrush && el.beforeBrush();
  24508. el.innerBeforeBrush();
  24509. var prevEl = scope.prevEl;
  24510. if (!prevEl) {
  24511. forceSetStyle = forceSetTransform = true;
  24512. }
  24513. var canBatchPath = el instanceof Path
  24514. && el.autoBatch
  24515. && canPathBatch(el.style);
  24516. if (forceSetTransform || isTransformChanged(m, prevEl.transform)) {
  24517. flushPathDrawn(ctx, scope);
  24518. setContextTransform(ctx, el);
  24519. }
  24520. else if (!canBatchPath) {
  24521. flushPathDrawn(ctx, scope);
  24522. }
  24523. var style = getStyle(el, scope.inHover);
  24524. if (el instanceof Path) {
  24525. if (scope.lastDrawType !== DRAW_TYPE_PATH) {
  24526. forceSetStyle = true;
  24527. scope.lastDrawType = DRAW_TYPE_PATH;
  24528. }
  24529. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24530. if (!canBatchPath || (!scope.batchFill && !scope.batchStroke)) {
  24531. ctx.beginPath();
  24532. }
  24533. brushPath(ctx, el, style, canBatchPath);
  24534. if (canBatchPath) {
  24535. scope.batchFill = style.fill || '';
  24536. scope.batchStroke = style.stroke || '';
  24537. }
  24538. }
  24539. else {
  24540. if (el instanceof TSpan) {
  24541. if (scope.lastDrawType !== DRAW_TYPE_TEXT) {
  24542. forceSetStyle = true;
  24543. scope.lastDrawType = DRAW_TYPE_TEXT;
  24544. }
  24545. bindPathAndTextCommonStyle(ctx, el, prevEl, forceSetStyle, scope);
  24546. brushText(ctx, el, style);
  24547. }
  24548. else if (el instanceof ZRImage) {
  24549. if (scope.lastDrawType !== DRAW_TYPE_IMAGE) {
  24550. forceSetStyle = true;
  24551. scope.lastDrawType = DRAW_TYPE_IMAGE;
  24552. }
  24553. bindImageStyle(ctx, el, prevEl, forceSetStyle, scope);
  24554. brushImage(ctx, el, style);
  24555. }
  24556. else if (el instanceof IncrementalDisplayable) {
  24557. if (scope.lastDrawType !== DRAW_TYPE_INCREMENTAL) {
  24558. forceSetStyle = true;
  24559. scope.lastDrawType = DRAW_TYPE_INCREMENTAL;
  24560. }
  24561. brushIncremental(ctx, el, scope);
  24562. }
  24563. }
  24564. if (canBatchPath && isLast) {
  24565. flushPathDrawn(ctx, scope);
  24566. }
  24567. el.innerAfterBrush();
  24568. el.afterBrush && el.afterBrush();
  24569. scope.prevEl = el;
  24570. el.__dirty = 0;
  24571. el.__isRendered = true;
  24572. }
  24573. function brushIncremental(ctx, el, scope) {
  24574. var displayables = el.getDisplayables();
  24575. var temporalDisplayables = el.getTemporalDisplayables();
  24576. ctx.save();
  24577. var innerScope = {
  24578. prevElClipPaths: null,
  24579. prevEl: null,
  24580. allClipped: false,
  24581. viewWidth: scope.viewWidth,
  24582. viewHeight: scope.viewHeight,
  24583. inHover: scope.inHover
  24584. };
  24585. var i;
  24586. var len;
  24587. for (i = el.getCursor(), len = displayables.length; i < len; i++) {
  24588. var displayable = displayables[i];
  24589. displayable.beforeBrush && displayable.beforeBrush();
  24590. displayable.innerBeforeBrush();
  24591. brush(ctx, displayable, innerScope, i === len - 1);
  24592. displayable.innerAfterBrush();
  24593. displayable.afterBrush && displayable.afterBrush();
  24594. innerScope.prevEl = displayable;
  24595. }
  24596. for (var i_1 = 0, len_1 = temporalDisplayables.length; i_1 < len_1; i_1++) {
  24597. var displayable = temporalDisplayables[i_1];
  24598. displayable.beforeBrush && displayable.beforeBrush();
  24599. displayable.innerBeforeBrush();
  24600. brush(ctx, displayable, innerScope, i_1 === len_1 - 1);
  24601. displayable.innerAfterBrush();
  24602. displayable.afterBrush && displayable.afterBrush();
  24603. innerScope.prevEl = displayable;
  24604. }
  24605. el.clearTemporalDisplayables();
  24606. el.notClear = true;
  24607. ctx.restore();
  24608. }
  24609. var decalMap = new WeakMap();
  24610. var decalCache = new LRU(100);
  24611. var decalKeys = ['symbol', 'symbolSize', 'symbolKeepAspect', 'color', 'backgroundColor', 'dashArrayX', 'dashArrayY', 'maxTileWidth', 'maxTileHeight'];
  24612. /**
  24613. * Create or update pattern image from decal options
  24614. *
  24615. * @param {InnerDecalObject | 'none'} decalObject decal options, 'none' if no decal
  24616. * @return {Pattern} pattern with generated image, null if no decal
  24617. */
  24618. function createOrUpdatePatternFromDecal(decalObject, api) {
  24619. if (decalObject === 'none') {
  24620. return null;
  24621. }
  24622. var dpr = api.getDevicePixelRatio();
  24623. var zr = api.getZr();
  24624. var isSVG = zr.painter.type === 'svg';
  24625. if (decalObject.dirty) {
  24626. decalMap["delete"](decalObject);
  24627. }
  24628. var oldPattern = decalMap.get(decalObject);
  24629. if (oldPattern) {
  24630. return oldPattern;
  24631. }
  24632. var decalOpt = defaults(decalObject, {
  24633. symbol: 'rect',
  24634. symbolSize: 1,
  24635. symbolKeepAspect: true,
  24636. color: 'rgba(0, 0, 0, 0.2)',
  24637. backgroundColor: null,
  24638. dashArrayX: 5,
  24639. dashArrayY: 5,
  24640. rotation: 0,
  24641. maxTileWidth: 512,
  24642. maxTileHeight: 512
  24643. });
  24644. if (decalOpt.backgroundColor === 'none') {
  24645. decalOpt.backgroundColor = null;
  24646. }
  24647. var pattern = {
  24648. repeat: 'repeat'
  24649. };
  24650. setPatternnSource(pattern);
  24651. pattern.rotation = decalOpt.rotation;
  24652. pattern.scaleX = pattern.scaleY = isSVG ? 1 : 1 / dpr;
  24653. decalMap.set(decalObject, pattern);
  24654. decalObject.dirty = false;
  24655. return pattern;
  24656. function setPatternnSource(pattern) {
  24657. var keys = [dpr];
  24658. var isValidKey = true;
  24659. for (var i = 0; i < decalKeys.length; ++i) {
  24660. var value = decalOpt[decalKeys[i]];
  24661. var valueType = typeof value;
  24662. if (value != null && !isArray(value) && valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') {
  24663. isValidKey = false;
  24664. break;
  24665. }
  24666. keys.push(value);
  24667. }
  24668. var cacheKey;
  24669. if (isValidKey) {
  24670. cacheKey = keys.join(',') + (isSVG ? '-svg' : '');
  24671. var cache = decalCache.get(cacheKey);
  24672. if (cache) {
  24673. isSVG ? pattern.svgElement = cache : pattern.image = cache;
  24674. }
  24675. }
  24676. var dashArrayX = normalizeDashArrayX(decalOpt.dashArrayX);
  24677. var dashArrayY = normalizeDashArrayY(decalOpt.dashArrayY);
  24678. var symbolArray = normalizeSymbolArray(decalOpt.symbol);
  24679. var lineBlockLengthsX = getLineBlockLengthX(dashArrayX);
  24680. var lineBlockLengthY = getLineBlockLengthY(dashArrayY);
  24681. var canvas = !isSVG && createCanvas();
  24682. var svgRoot = isSVG && zr.painter.createSVGElement('g');
  24683. var pSize = getPatternSize();
  24684. var ctx;
  24685. if (canvas) {
  24686. canvas.width = pSize.width * dpr;
  24687. canvas.height = pSize.height * dpr;
  24688. ctx = canvas.getContext('2d');
  24689. }
  24690. brushDecal();
  24691. if (isValidKey) {
  24692. decalCache.put(cacheKey, canvas || svgRoot);
  24693. }
  24694. pattern.image = canvas;
  24695. pattern.svgElement = svgRoot;
  24696. pattern.svgWidth = pSize.width;
  24697. pattern.svgHeight = pSize.height;
  24698. /**
  24699. * Get minumum length that can make a repeatable pattern.
  24700. *
  24701. * @return {Object} pattern width and height
  24702. */
  24703. function getPatternSize() {
  24704. /**
  24705. * For example, if dash is [[3, 2], [2, 1]] for X, it looks like
  24706. * |--- --- --- --- --- ...
  24707. * |-- -- -- -- -- -- -- -- ...
  24708. * |--- --- --- --- --- ...
  24709. * |-- -- -- -- -- -- -- -- ...
  24710. * So the minumum length of X is 15,
  24711. * which is the least common multiple of `3 + 2` and `2 + 1`
  24712. * |--- --- --- |--- --- ...
  24713. * |-- -- -- -- -- |-- -- -- ...
  24714. */
  24715. var width = 1;
  24716. for (var i = 0, xlen = lineBlockLengthsX.length; i < xlen; ++i) {
  24717. width = getLeastCommonMultiple(width, lineBlockLengthsX[i]);
  24718. }
  24719. var symbolRepeats = 1;
  24720. for (var i = 0, xlen = symbolArray.length; i < xlen; ++i) {
  24721. symbolRepeats = getLeastCommonMultiple(symbolRepeats, symbolArray[i].length);
  24722. }
  24723. width *= symbolRepeats;
  24724. var height = lineBlockLengthY * lineBlockLengthsX.length * symbolArray.length;
  24725. if ("development" !== 'production') {
  24726. var warn = function (attrName) {
  24727. /* eslint-disable-next-line */
  24728. 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.");
  24729. };
  24730. if (width > decalOpt.maxTileWidth) {
  24731. warn('maxTileWidth');
  24732. }
  24733. if (height > decalOpt.maxTileHeight) {
  24734. warn('maxTileHeight');
  24735. }
  24736. }
  24737. return {
  24738. width: Math.max(1, Math.min(width, decalOpt.maxTileWidth)),
  24739. height: Math.max(1, Math.min(height, decalOpt.maxTileHeight))
  24740. };
  24741. }
  24742. function brushDecal() {
  24743. if (ctx) {
  24744. ctx.clearRect(0, 0, canvas.width, canvas.height);
  24745. if (decalOpt.backgroundColor) {
  24746. ctx.fillStyle = decalOpt.backgroundColor;
  24747. ctx.fillRect(0, 0, canvas.width, canvas.height);
  24748. }
  24749. }
  24750. var ySum = 0;
  24751. for (var i = 0; i < dashArrayY.length; ++i) {
  24752. ySum += dashArrayY[i];
  24753. }
  24754. if (ySum <= 0) {
  24755. // dashArrayY is 0, draw nothing
  24756. return;
  24757. }
  24758. var y = -lineBlockLengthY;
  24759. var yId = 0;
  24760. var yIdTotal = 0;
  24761. var xId0 = 0;
  24762. while (y < pSize.height) {
  24763. if (yId % 2 === 0) {
  24764. var symbolYId = yIdTotal / 2 % symbolArray.length;
  24765. var x = 0;
  24766. var xId1 = 0;
  24767. var xId1Total = 0;
  24768. while (x < pSize.width * 2) {
  24769. var xSum = 0;
  24770. for (var i = 0; i < dashArrayX[xId0].length; ++i) {
  24771. xSum += dashArrayX[xId0][i];
  24772. }
  24773. if (xSum <= 0) {
  24774. // Skip empty line
  24775. break;
  24776. } // E.g., [15, 5, 20, 5] draws only for 15 and 20
  24777. if (xId1 % 2 === 0) {
  24778. var size = (1 - decalOpt.symbolSize) * 0.5;
  24779. var left = x + dashArrayX[xId0][xId1] * size;
  24780. var top_1 = y + dashArrayY[yId] * size;
  24781. var width = dashArrayX[xId0][xId1] * decalOpt.symbolSize;
  24782. var height = dashArrayY[yId] * decalOpt.symbolSize;
  24783. var symbolXId = xId1Total / 2 % symbolArray[symbolYId].length;
  24784. brushSymbol(left, top_1, width, height, symbolArray[symbolYId][symbolXId]);
  24785. }
  24786. x += dashArrayX[xId0][xId1];
  24787. ++xId1Total;
  24788. ++xId1;
  24789. if (xId1 === dashArrayX[xId0].length) {
  24790. xId1 = 0;
  24791. }
  24792. }
  24793. ++xId0;
  24794. if (xId0 === dashArrayX.length) {
  24795. xId0 = 0;
  24796. }
  24797. }
  24798. y += dashArrayY[yId];
  24799. ++yIdTotal;
  24800. ++yId;
  24801. if (yId === dashArrayY.length) {
  24802. yId = 0;
  24803. }
  24804. }
  24805. function brushSymbol(x, y, width, height, symbolType) {
  24806. var scale = isSVG ? 1 : dpr;
  24807. var symbol = createSymbol(symbolType, x * scale, y * scale, width * scale, height * scale, decalOpt.color, decalOpt.symbolKeepAspect);
  24808. if (isSVG) {
  24809. svgRoot.appendChild(zr.painter.paintOne(symbol));
  24810. } else {
  24811. // Paint to canvas for all other renderers.
  24812. brushSingle(ctx, symbol);
  24813. }
  24814. }
  24815. }
  24816. }
  24817. }
  24818. /**
  24819. * Convert symbol array into normalized array
  24820. *
  24821. * @param {string | (string | string[])[]} symbol symbol input
  24822. * @return {string[][]} normolized symbol array
  24823. */
  24824. function normalizeSymbolArray(symbol) {
  24825. if (!symbol || symbol.length === 0) {
  24826. return [['rect']];
  24827. }
  24828. if (typeof symbol === 'string') {
  24829. return [[symbol]];
  24830. }
  24831. var isAllString = true;
  24832. for (var i = 0; i < symbol.length; ++i) {
  24833. if (typeof symbol[i] !== 'string') {
  24834. isAllString = false;
  24835. break;
  24836. }
  24837. }
  24838. if (isAllString) {
  24839. return normalizeSymbolArray([symbol]);
  24840. }
  24841. var result = [];
  24842. for (var i = 0; i < symbol.length; ++i) {
  24843. if (typeof symbol[i] === 'string') {
  24844. result.push([symbol[i]]);
  24845. } else {
  24846. result.push(symbol[i]);
  24847. }
  24848. }
  24849. return result;
  24850. }
  24851. /**
  24852. * Convert dash input into dashArray
  24853. *
  24854. * @param {DecalDashArrayX} dash dash input
  24855. * @return {number[][]} normolized dash array
  24856. */
  24857. function normalizeDashArrayX(dash) {
  24858. if (!dash || dash.length === 0) {
  24859. return [[0, 0]];
  24860. }
  24861. if (typeof dash === 'number') {
  24862. var dashValue = Math.ceil(dash);
  24863. return [[dashValue, dashValue]];
  24864. }
  24865. /**
  24866. * [20, 5] should be normalized into [[20, 5]],
  24867. * while [20, [5, 10]] should be normalized into [[20, 20], [5, 10]]
  24868. */
  24869. var isAllNumber = true;
  24870. for (var i = 0; i < dash.length; ++i) {
  24871. if (typeof dash[i] !== 'number') {
  24872. isAllNumber = false;
  24873. break;
  24874. }
  24875. }
  24876. if (isAllNumber) {
  24877. return normalizeDashArrayX([dash]);
  24878. }
  24879. var result = [];
  24880. for (var i = 0; i < dash.length; ++i) {
  24881. if (typeof dash[i] === 'number') {
  24882. var dashValue = Math.ceil(dash[i]);
  24883. result.push([dashValue, dashValue]);
  24884. } else {
  24885. var dashValue = map(dash[i], function (n) {
  24886. return Math.ceil(n);
  24887. });
  24888. if (dashValue.length % 2 === 1) {
  24889. // [4, 2, 1] means |---- - -- |---- - -- |
  24890. // so normalize it to be [4, 2, 1, 4, 2, 1]
  24891. result.push(dashValue.concat(dashValue));
  24892. } else {
  24893. result.push(dashValue);
  24894. }
  24895. }
  24896. }
  24897. return result;
  24898. }
  24899. /**
  24900. * Convert dash input into dashArray
  24901. *
  24902. * @param {DecalDashArrayY} dash dash input
  24903. * @return {number[]} normolized dash array
  24904. */
  24905. function normalizeDashArrayY(dash) {
  24906. if (!dash || typeof dash === 'object' && dash.length === 0) {
  24907. return [0, 0];
  24908. }
  24909. if (typeof dash === 'number') {
  24910. var dashValue_1 = Math.ceil(dash);
  24911. return [dashValue_1, dashValue_1];
  24912. }
  24913. var dashValue = map(dash, function (n) {
  24914. return Math.ceil(n);
  24915. });
  24916. return dash.length % 2 ? dashValue.concat(dashValue) : dashValue;
  24917. }
  24918. /**
  24919. * Get block length of each line. A block is the length of dash line and space.
  24920. * For example, a line with [4, 1] has a dash line of 4 and a space of 1 after
  24921. * that, so the block length of this line is 5.
  24922. *
  24923. * @param {number[][]} dash dash arrary of X or Y
  24924. * @return {number[]} block length of each line
  24925. */
  24926. function getLineBlockLengthX(dash) {
  24927. return map(dash, function (line) {
  24928. return getLineBlockLengthY(line);
  24929. });
  24930. }
  24931. function getLineBlockLengthY(dash) {
  24932. var blockLength = 0;
  24933. for (var i = 0; i < dash.length; ++i) {
  24934. blockLength += dash[i];
  24935. }
  24936. if (dash.length % 2 === 1) {
  24937. // [4, 2, 1] means |---- - -- |---- - -- |
  24938. // So total length is (4 + 2 + 1) * 2
  24939. return blockLength * 2;
  24940. }
  24941. return blockLength;
  24942. }
  24943. function decalVisual(ecModel, api) {
  24944. ecModel.eachRawSeries(function (seriesModel) {
  24945. if (ecModel.isSeriesFiltered(seriesModel)) {
  24946. return;
  24947. }
  24948. var data = seriesModel.getData();
  24949. if (data.hasItemVisual()) {
  24950. data.each(function (idx) {
  24951. var decal = data.getItemVisual(idx, 'decal');
  24952. if (decal) {
  24953. var itemStyle = data.ensureUniqueItemVisual(idx, 'style');
  24954. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  24955. }
  24956. });
  24957. }
  24958. var decal = data.getVisual('decal');
  24959. if (decal) {
  24960. var style = data.getVisual('style');
  24961. style.decal = createOrUpdatePatternFromDecal(decal, api);
  24962. }
  24963. });
  24964. }
  24965. var assert$1 = assert;
  24966. var each$3 = each;
  24967. var isFunction$1 = isFunction;
  24968. var isObject$2 = isObject;
  24969. var indexOf$1 = indexOf;
  24970. var hasWindow = typeof window !== 'undefined';
  24971. var version$1 = '5.0.2';
  24972. var dependencies = {
  24973. zrender: '5.0.4'
  24974. };
  24975. var TEST_FRAME_REMAIN_TIME = 1;
  24976. var PRIORITY_PROCESSOR_SERIES_FILTER = 800; // Some data processors depends on the stack result dimension (to calculate data extent).
  24977. // So data stack stage should be in front of data processing stage.
  24978. var PRIORITY_PROCESSOR_DATASTACK = 900; // "Data filter" will block the stream, so it should be
  24979. // put at the begining of data processing.
  24980. var PRIORITY_PROCESSOR_FILTER = 1000;
  24981. var PRIORITY_PROCESSOR_DEFAULT = 2000;
  24982. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  24983. var PRIORITY_VISUAL_LAYOUT = 1000;
  24984. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  24985. var PRIORITY_VISUAL_GLOBAL = 2000;
  24986. var PRIORITY_VISUAL_CHART = 3000;
  24987. var PRIORITY_VISUAL_COMPONENT = 4000; // Visual property in data. Greater than `PRIORITY_VISUAL_COMPONENT` to enable to
  24988. // overwrite the viusal result of component (like `visualMap`)
  24989. // using data item specific setting (like itemStyle.xxx on data item)
  24990. var PRIORITY_VISUAL_CHART_DATA_CUSTOM = 4500; // Greater than `PRIORITY_VISUAL_CHART_DATA_CUSTOM` to enable to layout based on
  24991. // visual result like `symbolSize`.
  24992. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 4600;
  24993. var PRIORITY_VISUAL_BRUSH = 5000;
  24994. var PRIORITY_VISUAL_ARIA = 6000;
  24995. var PRIORITY_VISUAL_DECAL = 7000;
  24996. var PRIORITY = {
  24997. PROCESSOR: {
  24998. FILTER: PRIORITY_PROCESSOR_FILTER,
  24999. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  25000. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  25001. },
  25002. VISUAL: {
  25003. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  25004. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  25005. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  25006. CHART: PRIORITY_VISUAL_CHART,
  25007. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  25008. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  25009. BRUSH: PRIORITY_VISUAL_BRUSH,
  25010. CHART_ITEM: PRIORITY_VISUAL_CHART_DATA_CUSTOM,
  25011. ARIA: PRIORITY_VISUAL_ARIA,
  25012. DECAL: PRIORITY_VISUAL_DECAL
  25013. }
  25014. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  25015. // where they must not be invoked nestedly, except the only case: invoke
  25016. // dispatchAction with updateMethod "none" in main process.
  25017. // This flag is used to carry out this rule.
  25018. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  25019. var IN_MAIN_PROCESS_KEY = '__flagInMainProcess';
  25020. var OPTION_UPDATED_KEY = '__optionUpdated';
  25021. var STATUS_NEEDS_UPDATE_KEY = '__needsUpdateStatus';
  25022. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  25023. var CONNECT_STATUS_KEY = '__connectUpdateStatus';
  25024. var CONNECT_STATUS_PENDING = 0;
  25025. var CONNECT_STATUS_UPDATING = 1;
  25026. var CONNECT_STATUS_UPDATED = 2;
  25027. function createRegisterEventWithLowercaseECharts(method) {
  25028. return function () {
  25029. var args = [];
  25030. for (var _i = 0; _i < arguments.length; _i++) {
  25031. args[_i] = arguments[_i];
  25032. }
  25033. if (this.isDisposed()) {
  25034. disposedWarning(this.id);
  25035. return;
  25036. }
  25037. return toLowercaseNameAndCallEventful(this, method, args);
  25038. };
  25039. }
  25040. function createRegisterEventWithLowercaseMessageCenter(method) {
  25041. return function () {
  25042. var args = [];
  25043. for (var _i = 0; _i < arguments.length; _i++) {
  25044. args[_i] = arguments[_i];
  25045. }
  25046. return toLowercaseNameAndCallEventful(this, method, args);
  25047. };
  25048. }
  25049. function toLowercaseNameAndCallEventful(host, method, args) {
  25050. // `args[0]` is event name. Event name is all lowercase.
  25051. args[0] = args[0] && args[0].toLowerCase();
  25052. return Eventful.prototype[method].apply(host, args);
  25053. }
  25054. var MessageCenter =
  25055. /** @class */
  25056. function (_super) {
  25057. __extends(MessageCenter, _super);
  25058. function MessageCenter() {
  25059. return _super !== null && _super.apply(this, arguments) || this;
  25060. }
  25061. return MessageCenter;
  25062. }(Eventful);
  25063. var messageCenterProto = MessageCenter.prototype;
  25064. messageCenterProto.on = createRegisterEventWithLowercaseMessageCenter('on');
  25065. messageCenterProto.off = createRegisterEventWithLowercaseMessageCenter('off'); // ---------------------------------------
  25066. // Internal method names for class ECharts
  25067. // ---------------------------------------
  25068. var prepare;
  25069. var prepareView;
  25070. var updateDirectly;
  25071. var updateMethods;
  25072. var doConvertPixel;
  25073. var updateStreamModes;
  25074. var doDispatchAction;
  25075. var flushPendingActions;
  25076. var triggerUpdatedEvent;
  25077. var bindRenderedEvent;
  25078. var bindMouseEvent;
  25079. var clearColorPalette;
  25080. var render;
  25081. var renderComponents;
  25082. var renderSeries;
  25083. var performPostUpdateFuncs;
  25084. var createExtensionAPI;
  25085. var enableConnect;
  25086. var setTransitionOpt;
  25087. var markStatusToUpdate;
  25088. var applyChangedStates;
  25089. var ECharts =
  25090. /** @class */
  25091. function (_super) {
  25092. __extends(ECharts, _super);
  25093. function ECharts(dom, // Theme name or themeOption.
  25094. theme, opts) {
  25095. var _this = _super.call(this, new ECEventProcessor()) || this;
  25096. _this._chartsViews = [];
  25097. _this._chartsMap = {};
  25098. _this._componentsViews = [];
  25099. _this._componentsMap = {}; // Can't dispatch action during rendering procedure
  25100. _this._pendingActions = [];
  25101. opts = opts || {}; // Get theme by name
  25102. if (typeof theme === 'string') {
  25103. theme = themeStorage[theme];
  25104. }
  25105. _this._dom = dom;
  25106. var defaultRenderer = 'canvas';
  25107. var defaultUseDirtyRect = false;
  25108. if ("development" !== 'production') {
  25109. var root =
  25110. /* eslint-disable-next-line */
  25111. hasWindow ? window : global;
  25112. defaultRenderer = root.__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  25113. var devUseDirtyRect = root.__ECHARTS__DEFAULT__USE_DIRTY_RECT__;
  25114. defaultUseDirtyRect = devUseDirtyRect == null ? defaultUseDirtyRect : devUseDirtyRect;
  25115. }
  25116. var zr = _this._zr = init(dom, {
  25117. renderer: opts.renderer || defaultRenderer,
  25118. devicePixelRatio: opts.devicePixelRatio,
  25119. width: opts.width,
  25120. height: opts.height,
  25121. useDirtyRect: opts.useDirtyRect == null ? defaultUseDirtyRect : opts.useDirtyRect
  25122. }); // Expect 60 fps.
  25123. _this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  25124. theme = clone(theme);
  25125. theme && globalBackwardCompat(theme, true);
  25126. _this._theme = theme;
  25127. _this._locale = createLocaleObject(opts.locale || SYSTEM_LANG);
  25128. _this._coordSysMgr = new CoordinateSystemManager();
  25129. var api = _this._api = createExtensionAPI(_this); // Sort on demand
  25130. function prioritySortFunc(a, b) {
  25131. return a.__prio - b.__prio;
  25132. }
  25133. sort(visualFuncs, prioritySortFunc);
  25134. sort(dataProcessorFuncs, prioritySortFunc);
  25135. _this._scheduler = new Scheduler(_this, api, dataProcessorFuncs, visualFuncs);
  25136. _this._messageCenter = new MessageCenter();
  25137. _this._labelManager = new LabelManager(); // Init mouse events
  25138. _this._initEvents(); // In case some people write `window.onresize = chart.resize`
  25139. _this.resize = bind(_this.resize, _this);
  25140. zr.animation.on('frame', _this._onframe, _this);
  25141. bindRenderedEvent(zr, _this);
  25142. bindMouseEvent(zr, _this); // ECharts instance can be used as value.
  25143. setAsPrimitive(_this);
  25144. return _this;
  25145. }
  25146. ECharts.prototype._onframe = function () {
  25147. if (this._disposed) {
  25148. return;
  25149. }
  25150. applyChangedStates(this);
  25151. var scheduler = this._scheduler; // Lazy update
  25152. if (this[OPTION_UPDATED_KEY]) {
  25153. var silent = this[OPTION_UPDATED_KEY].silent;
  25154. this[IN_MAIN_PROCESS_KEY] = true;
  25155. prepare(this);
  25156. updateMethods.update.call(this); // At present, in each frame, zrender performs:
  25157. // (1) animation step forward.
  25158. // (2) trigger('frame') (where this `_onframe` is called)
  25159. // (3) zrender flush (render).
  25160. // If we do nothing here, since we use `setToFinal: true`, the step (3) above
  25161. // will render the final state of the elements before the real animation started.
  25162. this._zr.flush();
  25163. this[IN_MAIN_PROCESS_KEY] = false;
  25164. this[OPTION_UPDATED_KEY] = false;
  25165. flushPendingActions.call(this, silent);
  25166. triggerUpdatedEvent.call(this, silent);
  25167. } // Avoid do both lazy update and progress in one frame.
  25168. else if (scheduler.unfinished) {
  25169. // Stream progress.
  25170. var remainTime = TEST_FRAME_REMAIN_TIME;
  25171. var ecModel = this._model;
  25172. var api = this._api;
  25173. scheduler.unfinished = false;
  25174. do {
  25175. var startTime = +new Date();
  25176. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  25177. scheduler.performDataProcessorTasks(ecModel);
  25178. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  25179. // each frame is not a good user experience. So we follow the rule that
  25180. // the extent of the coordinate system is determin in the first frame (the
  25181. // frame is executed immedietely after task reset.
  25182. // this._coordSysMgr.update(ecModel, api);
  25183. // console.log('--- ec frame visual ---', remainTime);
  25184. scheduler.performVisualTasks(ecModel);
  25185. renderSeries(this, this._model, api, 'remain');
  25186. remainTime -= +new Date() - startTime;
  25187. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  25188. if (!scheduler.unfinished) {
  25189. this._zr.flush();
  25190. } // Else, zr flushing be ensue within the same frame,
  25191. // because zr flushing is after onframe event.
  25192. }
  25193. };
  25194. ECharts.prototype.getDom = function () {
  25195. return this._dom;
  25196. };
  25197. ECharts.prototype.getId = function () {
  25198. return this.id;
  25199. };
  25200. ECharts.prototype.getZr = function () {
  25201. return this._zr;
  25202. };
  25203. /* eslint-disable-next-line */
  25204. ECharts.prototype.setOption = function (option, notMerge, lazyUpdate) {
  25205. if ("development" !== 'production') {
  25206. assert$1(!this[IN_MAIN_PROCESS_KEY], '`setOption` should not be called during main process.');
  25207. }
  25208. if (this._disposed) {
  25209. disposedWarning(this.id);
  25210. return;
  25211. }
  25212. var silent;
  25213. var replaceMerge;
  25214. var transitionOpt;
  25215. if (isObject$2(notMerge)) {
  25216. lazyUpdate = notMerge.lazyUpdate;
  25217. silent = notMerge.silent;
  25218. replaceMerge = notMerge.replaceMerge;
  25219. transitionOpt = notMerge.transition;
  25220. notMerge = notMerge.notMerge;
  25221. }
  25222. this[IN_MAIN_PROCESS_KEY] = true;
  25223. if (!this._model || notMerge) {
  25224. var optionManager = new OptionManager(this._api);
  25225. var theme = this._theme;
  25226. var ecModel = this._model = new GlobalModel();
  25227. ecModel.scheduler = this._scheduler;
  25228. ecModel.init(null, null, null, theme, this._locale, optionManager);
  25229. }
  25230. this._model.setOption(option, {
  25231. replaceMerge: replaceMerge
  25232. }, optionPreprocessorFuncs);
  25233. setTransitionOpt(this, transitionOpt);
  25234. if (lazyUpdate) {
  25235. this[OPTION_UPDATED_KEY] = {
  25236. silent: silent
  25237. };
  25238. this[IN_MAIN_PROCESS_KEY] = false; // `setOption(option, {lazyMode: true})` may be called when zrender has been slept.
  25239. // It should wake it up to make sure zrender start to render at the next frame.
  25240. this.getZr().wakeUp();
  25241. } else {
  25242. prepare(this);
  25243. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  25244. // fetched after `setOption`.
  25245. this._zr.flush();
  25246. this[OPTION_UPDATED_KEY] = false;
  25247. this[IN_MAIN_PROCESS_KEY] = false;
  25248. flushPendingActions.call(this, silent);
  25249. triggerUpdatedEvent.call(this, silent);
  25250. }
  25251. };
  25252. /**
  25253. * @DEPRECATED
  25254. */
  25255. ECharts.prototype.setTheme = function () {
  25256. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  25257. }; // We don't want developers to use getModel directly.
  25258. ECharts.prototype.getModel = function () {
  25259. return this._model;
  25260. };
  25261. ECharts.prototype.getOption = function () {
  25262. return this._model && this._model.getOption();
  25263. };
  25264. ECharts.prototype.getWidth = function () {
  25265. return this._zr.getWidth();
  25266. };
  25267. ECharts.prototype.getHeight = function () {
  25268. return this._zr.getHeight();
  25269. };
  25270. ECharts.prototype.getDevicePixelRatio = function () {
  25271. return this._zr.painter.dpr
  25272. /* eslint-disable-next-line */
  25273. || hasWindow && window.devicePixelRatio || 1;
  25274. };
  25275. /**
  25276. * Get canvas which has all thing rendered
  25277. */
  25278. ECharts.prototype.getRenderedCanvas = function (opts) {
  25279. if (!env.canvasSupported) {
  25280. return;
  25281. }
  25282. opts = extend({}, opts || {});
  25283. opts.pixelRatio = opts.pixelRatio || this.getDevicePixelRatio();
  25284. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  25285. var zr = this._zr; // let list = zr.storage.getDisplayList();
  25286. // Stop animations
  25287. // Never works before in init animation, so remove it.
  25288. // zrUtil.each(list, function (el) {
  25289. // el.stopAnimation(true);
  25290. // });
  25291. return zr.painter.getRenderedCanvas(opts);
  25292. };
  25293. /**
  25294. * Get svg data url
  25295. */
  25296. ECharts.prototype.getSvgDataURL = function () {
  25297. if (!env.svgSupported) {
  25298. return;
  25299. }
  25300. var zr = this._zr;
  25301. var list = zr.storage.getDisplayList(); // Stop animations
  25302. each(list, function (el) {
  25303. el.stopAnimation(null, true);
  25304. });
  25305. return zr.painter.toDataURL();
  25306. };
  25307. ECharts.prototype.getDataURL = function (opts) {
  25308. if (this._disposed) {
  25309. disposedWarning(this.id);
  25310. return;
  25311. }
  25312. opts = opts || {};
  25313. var excludeComponents = opts.excludeComponents;
  25314. var ecModel = this._model;
  25315. var excludesComponentViews = [];
  25316. var self = this;
  25317. each$3(excludeComponents, function (componentType) {
  25318. ecModel.eachComponent({
  25319. mainType: componentType
  25320. }, function (component) {
  25321. var view = self._componentsMap[component.__viewId];
  25322. if (!view.group.ignore) {
  25323. excludesComponentViews.push(view);
  25324. view.group.ignore = true;
  25325. }
  25326. });
  25327. });
  25328. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  25329. each$3(excludesComponentViews, function (view) {
  25330. view.group.ignore = false;
  25331. });
  25332. return url;
  25333. };
  25334. ECharts.prototype.getConnectedDataURL = function (opts) {
  25335. if (this._disposed) {
  25336. disposedWarning(this.id);
  25337. return;
  25338. }
  25339. if (!env.canvasSupported) {
  25340. return;
  25341. }
  25342. var isSvg = opts.type === 'svg';
  25343. var groupId = this.group;
  25344. var mathMin = Math.min;
  25345. var mathMax = Math.max;
  25346. var MAX_NUMBER = Infinity;
  25347. if (connectedGroups[groupId]) {
  25348. var left_1 = MAX_NUMBER;
  25349. var top_1 = MAX_NUMBER;
  25350. var right_1 = -MAX_NUMBER;
  25351. var bottom_1 = -MAX_NUMBER;
  25352. var canvasList_1 = [];
  25353. var dpr_1 = opts && opts.pixelRatio || this.getDevicePixelRatio();
  25354. each(instances$1, function (chart, id) {
  25355. if (chart.group === groupId) {
  25356. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  25357. var boundingRect = chart.getDom().getBoundingClientRect();
  25358. left_1 = mathMin(boundingRect.left, left_1);
  25359. top_1 = mathMin(boundingRect.top, top_1);
  25360. right_1 = mathMax(boundingRect.right, right_1);
  25361. bottom_1 = mathMax(boundingRect.bottom, bottom_1);
  25362. canvasList_1.push({
  25363. dom: canvas,
  25364. left: boundingRect.left,
  25365. top: boundingRect.top
  25366. });
  25367. }
  25368. });
  25369. left_1 *= dpr_1;
  25370. top_1 *= dpr_1;
  25371. right_1 *= dpr_1;
  25372. bottom_1 *= dpr_1;
  25373. var width = right_1 - left_1;
  25374. var height = bottom_1 - top_1;
  25375. var targetCanvas = createCanvas();
  25376. var zr_1 = init(targetCanvas, {
  25377. renderer: isSvg ? 'svg' : 'canvas'
  25378. });
  25379. zr_1.resize({
  25380. width: width,
  25381. height: height
  25382. });
  25383. if (isSvg) {
  25384. var content_1 = '';
  25385. each$3(canvasList_1, function (item) {
  25386. var x = item.left - left_1;
  25387. var y = item.top - top_1;
  25388. content_1 += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  25389. });
  25390. zr_1.painter.getSvgRoot().innerHTML = content_1;
  25391. if (opts.connectedBackgroundColor) {
  25392. zr_1.painter.setBackgroundColor(opts.connectedBackgroundColor);
  25393. }
  25394. zr_1.refreshImmediately();
  25395. return zr_1.painter.toDataURL();
  25396. } else {
  25397. // Background between the charts
  25398. if (opts.connectedBackgroundColor) {
  25399. zr_1.add(new Rect({
  25400. shape: {
  25401. x: 0,
  25402. y: 0,
  25403. width: width,
  25404. height: height
  25405. },
  25406. style: {
  25407. fill: opts.connectedBackgroundColor
  25408. }
  25409. }));
  25410. }
  25411. each$3(canvasList_1, function (item) {
  25412. var img = new ZRImage({
  25413. style: {
  25414. x: item.left * dpr_1 - left_1,
  25415. y: item.top * dpr_1 - top_1,
  25416. image: item.dom
  25417. }
  25418. });
  25419. zr_1.add(img);
  25420. });
  25421. zr_1.refreshImmediately();
  25422. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  25423. }
  25424. } else {
  25425. return this.getDataURL(opts);
  25426. }
  25427. };
  25428. ECharts.prototype.convertToPixel = function (finder, value) {
  25429. return doConvertPixel(this, 'convertToPixel', finder, value);
  25430. };
  25431. ECharts.prototype.convertFromPixel = function (finder, value) {
  25432. return doConvertPixel(this, 'convertFromPixel', finder, value);
  25433. };
  25434. /**
  25435. * Is the specified coordinate systems or components contain the given pixel point.
  25436. * @param {Array|number} value
  25437. * @return {boolean} result
  25438. */
  25439. ECharts.prototype.containPixel = function (finder, value) {
  25440. if (this._disposed) {
  25441. disposedWarning(this.id);
  25442. return;
  25443. }
  25444. var ecModel = this._model;
  25445. var result;
  25446. var findResult = parseFinder(ecModel, finder);
  25447. each(findResult, function (models, key) {
  25448. key.indexOf('Models') >= 0 && each(models, function (model) {
  25449. var coordSys = model.coordinateSystem;
  25450. if (coordSys && coordSys.containPoint) {
  25451. result = result || !!coordSys.containPoint(value);
  25452. } else if (key === 'seriesModels') {
  25453. var view = this._chartsMap[model.__viewId];
  25454. if (view && view.containPoint) {
  25455. result = result || view.containPoint(value, model);
  25456. } else {
  25457. if ("development" !== 'production') {
  25458. console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.'));
  25459. }
  25460. }
  25461. } else {
  25462. if ("development" !== 'production') {
  25463. console.warn(key + ': containPoint is not supported');
  25464. }
  25465. }
  25466. }, this);
  25467. }, this);
  25468. return !!result;
  25469. };
  25470. /**
  25471. * Get visual from series or data.
  25472. * @param finder
  25473. * If string, e.g., 'series', means {seriesIndex: 0}.
  25474. * If Object, could contain some of these properties below:
  25475. * {
  25476. * seriesIndex / seriesId / seriesName,
  25477. * dataIndex / dataIndexInside
  25478. * }
  25479. * If dataIndex is not specified, series visual will be fetched,
  25480. * but not data item visual.
  25481. * If all of seriesIndex, seriesId, seriesName are not specified,
  25482. * visual will be fetched from first series.
  25483. * @param visualType 'color', 'symbol', 'symbolSize'
  25484. */
  25485. ECharts.prototype.getVisual = function (finder, visualType) {
  25486. var ecModel = this._model;
  25487. var parsedFinder = parseFinder(ecModel, finder, {
  25488. defaultMainType: 'series'
  25489. });
  25490. var seriesModel = parsedFinder.seriesModel;
  25491. if ("development" !== 'production') {
  25492. if (!seriesModel) {
  25493. console.warn('There is no specified seires model');
  25494. }
  25495. }
  25496. var data = seriesModel.getData();
  25497. var dataIndexInside = parsedFinder.hasOwnProperty('dataIndexInside') ? parsedFinder.dataIndexInside : parsedFinder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(parsedFinder.dataIndex) : null;
  25498. return dataIndexInside != null ? getItemVisualFromData(data, dataIndexInside, visualType) : getVisualFromData(data, visualType);
  25499. };
  25500. /**
  25501. * Get view of corresponding component model
  25502. */
  25503. ECharts.prototype.getViewOfComponentModel = function (componentModel) {
  25504. return this._componentsMap[componentModel.__viewId];
  25505. };
  25506. /**
  25507. * Get view of corresponding series model
  25508. */
  25509. ECharts.prototype.getViewOfSeriesModel = function (seriesModel) {
  25510. return this._chartsMap[seriesModel.__viewId];
  25511. };
  25512. ECharts.prototype._initEvents = function () {
  25513. var _this = this;
  25514. each$3(MOUSE_EVENT_NAMES, function (eveName) {
  25515. var handler = function (e) {
  25516. var ecModel = _this.getModel();
  25517. var el = e.target;
  25518. var params;
  25519. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  25520. if (isGlobalOut) {
  25521. params = {};
  25522. } else {
  25523. el && findEventDispatcher(el, function (parent) {
  25524. var ecData = getECData(parent);
  25525. if (ecData && ecData.dataIndex != null) {
  25526. var dataModel = ecData.dataModel || ecModel.getSeriesByIndex(ecData.seriesIndex);
  25527. params = dataModel && dataModel.getDataParams(ecData.dataIndex, ecData.dataType) || {};
  25528. return true;
  25529. } // If element has custom eventData of components
  25530. else if (ecData.eventData) {
  25531. params = extend({}, ecData.eventData);
  25532. return true;
  25533. }
  25534. }, true);
  25535. } // Contract: if params prepared in mouse event,
  25536. // these properties must be specified:
  25537. // {
  25538. // componentType: string (component main type)
  25539. // componentIndex: number
  25540. // }
  25541. // Otherwise event query can not work.
  25542. if (params) {
  25543. var componentType = params.componentType;
  25544. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  25545. // markLine/markPoint/markArea, the componentType is
  25546. // 'markLine'/'markPoint'/'markArea', but we should better
  25547. // enable them to be queried by seriesIndex, since their
  25548. // option is set in each series.
  25549. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  25550. componentType = 'series';
  25551. componentIndex = params.seriesIndex;
  25552. }
  25553. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  25554. var view = model && _this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  25555. if ("development" !== 'production') {
  25556. // `event.componentType` and `event[componentTpype + 'Index']` must not
  25557. // be missed, otherwise there is no way to distinguish source component.
  25558. // See `dataFormat.getDataParams`.
  25559. if (!isGlobalOut && !(model && view)) {
  25560. console.warn('model or view can not be found by params');
  25561. }
  25562. }
  25563. params.event = e;
  25564. params.type = eveName;
  25565. _this._$eventProcessor.eventInfo = {
  25566. targetEl: el,
  25567. packedEvent: params,
  25568. model: model,
  25569. view: view
  25570. };
  25571. _this.trigger(eveName, params);
  25572. }
  25573. }; // Consider that some component (like tooltip, brush, ...)
  25574. // register zr event handler, but user event handler might
  25575. // do anything, such as call `setOption` or `dispatchAction`,
  25576. // which probably update any of the content and probably
  25577. // cause problem if it is called previous other inner handlers.
  25578. handler.zrEventfulCallAtLast = true;
  25579. _this._zr.on(eveName, handler, _this);
  25580. });
  25581. each$3(eventActionMap, function (actionType, eventType) {
  25582. _this._messageCenter.on(eventType, function (event) {
  25583. this.trigger(eventType, event);
  25584. }, _this);
  25585. }); // Extra events
  25586. // TODO register?
  25587. each$3(['selectchanged'], function (eventType) {
  25588. _this._messageCenter.on(eventType, function (event) {
  25589. this.trigger(eventType, event);
  25590. }, _this);
  25591. });
  25592. handleLegacySelectEvents(this._messageCenter, this, this._api);
  25593. };
  25594. ECharts.prototype.isDisposed = function () {
  25595. return this._disposed;
  25596. };
  25597. ECharts.prototype.clear = function () {
  25598. if (this._disposed) {
  25599. disposedWarning(this.id);
  25600. return;
  25601. }
  25602. this.setOption({
  25603. series: []
  25604. }, true);
  25605. };
  25606. ECharts.prototype.dispose = function () {
  25607. if (this._disposed) {
  25608. disposedWarning(this.id);
  25609. return;
  25610. }
  25611. this._disposed = true;
  25612. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  25613. var api = this._api;
  25614. var ecModel = this._model;
  25615. each$3(this._componentsViews, function (component) {
  25616. component.dispose(ecModel, api);
  25617. });
  25618. each$3(this._chartsViews, function (chart) {
  25619. chart.dispose(ecModel, api);
  25620. }); // Dispose after all views disposed
  25621. this._zr.dispose();
  25622. delete instances$1[this.id];
  25623. };
  25624. /**
  25625. * Resize the chart
  25626. */
  25627. ECharts.prototype.resize = function (opts) {
  25628. if ("development" !== 'production') {
  25629. assert$1(!this[IN_MAIN_PROCESS_KEY], '`resize` should not be called during main process.');
  25630. }
  25631. if (this._disposed) {
  25632. disposedWarning(this.id);
  25633. return;
  25634. }
  25635. this._zr.resize(opts);
  25636. var ecModel = this._model; // Resize loading effect
  25637. this._loadingFX && this._loadingFX.resize();
  25638. if (!ecModel) {
  25639. return;
  25640. }
  25641. var optionChanged = ecModel.resetOption('media');
  25642. var silent = opts && opts.silent;
  25643. this[IN_MAIN_PROCESS_KEY] = true;
  25644. optionChanged && prepare(this);
  25645. updateMethods.update.call(this, {
  25646. type: 'resize',
  25647. animation: {
  25648. // Disable animation
  25649. duration: 0
  25650. }
  25651. });
  25652. this[IN_MAIN_PROCESS_KEY] = false;
  25653. flushPendingActions.call(this, silent);
  25654. triggerUpdatedEvent.call(this, silent);
  25655. };
  25656. ECharts.prototype.showLoading = function (name, cfg) {
  25657. if (this._disposed) {
  25658. disposedWarning(this.id);
  25659. return;
  25660. }
  25661. if (isObject$2(name)) {
  25662. cfg = name;
  25663. name = '';
  25664. }
  25665. name = name || 'default';
  25666. this.hideLoading();
  25667. if (!loadingEffects[name]) {
  25668. if ("development" !== 'production') {
  25669. console.warn('Loading effects ' + name + ' not exists.');
  25670. }
  25671. return;
  25672. }
  25673. var el = loadingEffects[name](this._api, cfg);
  25674. var zr = this._zr;
  25675. this._loadingFX = el;
  25676. zr.add(el);
  25677. };
  25678. /**
  25679. * Hide loading effect
  25680. */
  25681. ECharts.prototype.hideLoading = function () {
  25682. if (this._disposed) {
  25683. disposedWarning(this.id);
  25684. return;
  25685. }
  25686. this._loadingFX && this._zr.remove(this._loadingFX);
  25687. this._loadingFX = null;
  25688. };
  25689. ECharts.prototype.makeActionFromEvent = function (eventObj) {
  25690. var payload = extend({}, eventObj);
  25691. payload.type = eventActionMap[eventObj.type];
  25692. return payload;
  25693. };
  25694. /**
  25695. * @param opt If pass boolean, means opt.silent
  25696. * @param opt.silent Default `false`. Whether trigger events.
  25697. * @param opt.flush Default `undefined`.
  25698. * true: Flush immediately, and then pixel in canvas can be fetched
  25699. * immediately. Caution: it might affect performance.
  25700. * false: Not flush.
  25701. * undefined: Auto decide whether perform flush.
  25702. */
  25703. ECharts.prototype.dispatchAction = function (payload, opt) {
  25704. if (this._disposed) {
  25705. disposedWarning(this.id);
  25706. return;
  25707. }
  25708. if (!isObject$2(opt)) {
  25709. opt = {
  25710. silent: !!opt
  25711. };
  25712. }
  25713. if (!actions[payload.type]) {
  25714. return;
  25715. } // Avoid dispatch action before setOption. Especially in `connect`.
  25716. if (!this._model) {
  25717. return;
  25718. } // May dispatchAction in rendering procedure
  25719. if (this[IN_MAIN_PROCESS_KEY]) {
  25720. this._pendingActions.push(payload);
  25721. return;
  25722. }
  25723. var silent = opt.silent;
  25724. doDispatchAction.call(this, payload, silent);
  25725. var flush = opt.flush;
  25726. if (flush) {
  25727. this._zr.flush();
  25728. } else if (flush !== false && env.browser.weChat) {
  25729. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  25730. // hang when sliding page (on touch event), which cause that zr does not
  25731. // refresh util user interaction finished, which is not expected.
  25732. // But `dispatchAction` may be called too frequently when pan on touch
  25733. // screen, which impacts performance if do not throttle them.
  25734. this._throttledZrFlush();
  25735. }
  25736. flushPendingActions.call(this, silent);
  25737. triggerUpdatedEvent.call(this, silent);
  25738. };
  25739. ECharts.prototype.updateLabelLayout = function () {
  25740. var labelManager = this._labelManager;
  25741. labelManager.updateLayoutConfig(this._api);
  25742. labelManager.layout(this._api);
  25743. labelManager.processLabelsOverall();
  25744. };
  25745. ECharts.prototype.appendData = function (params) {
  25746. if (this._disposed) {
  25747. disposedWarning(this.id);
  25748. return;
  25749. }
  25750. var seriesIndex = params.seriesIndex;
  25751. var ecModel = this.getModel();
  25752. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  25753. if ("development" !== 'production') {
  25754. assert$1(params.data && seriesModel);
  25755. }
  25756. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  25757. // system, util some scenario require that. In the expected usage of
  25758. // `appendData`, the initial extent of coordinate system should better
  25759. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  25760. // the extent changed while `appendData`, the location of the painted
  25761. // graphic elements have to be changed, which make the usage of
  25762. // `appendData` meaningless.
  25763. this._scheduler.unfinished = true;
  25764. this.getZr().wakeUp();
  25765. }; // A work around for no `internal` modifier in ts yet but
  25766. // need to strictly hide private methods to JS users.
  25767. ECharts.internalField = function () {
  25768. prepare = function (ecIns) {
  25769. var scheduler = ecIns._scheduler;
  25770. scheduler.restorePipelines(ecIns._model);
  25771. scheduler.prepareStageTasks();
  25772. prepareView(ecIns, true);
  25773. prepareView(ecIns, false);
  25774. scheduler.plan();
  25775. };
  25776. /**
  25777. * Prepare view instances of charts and components
  25778. */
  25779. prepareView = function (ecIns, isComponent) {
  25780. var ecModel = ecIns._model;
  25781. var scheduler = ecIns._scheduler;
  25782. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  25783. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  25784. var zr = ecIns._zr;
  25785. var api = ecIns._api;
  25786. for (var i = 0; i < viewList.length; i++) {
  25787. viewList[i].__alive = false;
  25788. }
  25789. isComponent ? ecModel.eachComponent(function (componentType, model) {
  25790. componentType !== 'series' && doPrepare(model);
  25791. }) : ecModel.eachSeries(doPrepare);
  25792. function doPrepare(model) {
  25793. // By defaut view will be reused if possible for the case that `setOption` with "notMerge"
  25794. // mode and need to enable transition animation. (Usually, when they have the same id, or
  25795. // especially no id but have the same type & name & index. See the `model.id` generation
  25796. // rule in `makeIdAndName` and `viewId` generation rule here).
  25797. // But in `replaceMerge` mode, this feature should be able to disabled when it is clear that
  25798. // the new model has nothing to do with the old model.
  25799. var requireNewView = model.__requireNewView; // This command should not work twice.
  25800. model.__requireNewView = false; // Consider: id same and type changed.
  25801. var viewId = '_ec_' + model.id + '_' + model.type;
  25802. var view = !requireNewView && viewMap[viewId];
  25803. if (!view) {
  25804. var classType = parseClassType(model.type);
  25805. var Clazz = isComponent ? ComponentView.getClass(classType.main, classType.sub) : // FIXME:TS
  25806. // (ChartView as ChartViewConstructor).getClass('series', classType.sub)
  25807. // For backward compat, still support a chart type declared as only subType
  25808. // like "liquidfill", but recommend "series.liquidfill"
  25809. // But need a base class to make a type series.
  25810. ChartView.getClass(classType.sub);
  25811. if ("development" !== 'production') {
  25812. assert$1(Clazz, classType.sub + ' does not exist.');
  25813. }
  25814. view = new Clazz();
  25815. view.init(ecModel, api);
  25816. viewMap[viewId] = view;
  25817. viewList.push(view);
  25818. zr.add(view.group);
  25819. }
  25820. model.__viewId = view.__id = viewId;
  25821. view.__alive = true;
  25822. view.__model = model;
  25823. view.group.__ecComponentInfo = {
  25824. mainType: model.mainType,
  25825. index: model.componentIndex
  25826. };
  25827. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  25828. }
  25829. for (var i = 0; i < viewList.length;) {
  25830. var view = viewList[i];
  25831. if (!view.__alive) {
  25832. !isComponent && view.renderTask.dispose();
  25833. zr.remove(view.group);
  25834. view.dispose(ecModel, api);
  25835. viewList.splice(i, 1);
  25836. if (viewMap[view.__id] === view) {
  25837. delete viewMap[view.__id];
  25838. }
  25839. view.__id = view.group.__ecComponentInfo = null;
  25840. } else {
  25841. i++;
  25842. }
  25843. }
  25844. };
  25845. updateDirectly = function (ecIns, method, payload, mainType, subType) {
  25846. var ecModel = ecIns._model;
  25847. ecModel.setUpdatePayload(payload); // broadcast
  25848. if (!mainType) {
  25849. // FIXME
  25850. // Chart will not be update directly here, except set dirty.
  25851. // But there is no such scenario now.
  25852. each$3([].concat(ecIns._componentsViews).concat(ecIns._chartsViews), callView);
  25853. return;
  25854. }
  25855. var query = {};
  25856. query[mainType + 'Id'] = payload[mainType + 'Id'];
  25857. query[mainType + 'Index'] = payload[mainType + 'Index'];
  25858. query[mainType + 'Name'] = payload[mainType + 'Name'];
  25859. var condition = {
  25860. mainType: mainType,
  25861. query: query
  25862. };
  25863. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  25864. var excludeSeriesId = payload.excludeSeriesId;
  25865. var excludeSeriesIdMap;
  25866. if (excludeSeriesId != null) {
  25867. excludeSeriesIdMap = createHashMap();
  25868. each$3(normalizeToArray(excludeSeriesId), function (id) {
  25869. var modelId = convertOptionIdName(id, null);
  25870. if (modelId != null) {
  25871. excludeSeriesIdMap.set(modelId, true);
  25872. }
  25873. });
  25874. } // If dispatchAction before setOption, do nothing.
  25875. ecModel && ecModel.eachComponent(condition, function (model) {
  25876. if (!excludeSeriesIdMap || excludeSeriesIdMap.get(model.id) == null) {
  25877. if (isHighDownPayload(payload) && !payload.notBlur) {
  25878. if (model instanceof SeriesModel) {
  25879. toggleSeriesBlurStateFromPayload(model, payload, ecIns._api);
  25880. }
  25881. } else if (isSelectChangePayload(payload)) {
  25882. // TODO geo
  25883. if (model instanceof SeriesModel) {
  25884. toggleSelectionFromPayload(model, payload, ecIns._api);
  25885. updateSeriesElementSelection(model);
  25886. markStatusToUpdate(ecIns);
  25887. }
  25888. }
  25889. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  25890. }
  25891. }, ecIns);
  25892. function callView(view) {
  25893. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  25894. }
  25895. };
  25896. updateMethods = {
  25897. prepareAndUpdate: function (payload) {
  25898. prepare(this);
  25899. updateMethods.update.call(this, payload);
  25900. },
  25901. update: function (payload) {
  25902. // console.profile && console.profile('update');
  25903. var ecModel = this._model;
  25904. var api = this._api;
  25905. var zr = this._zr;
  25906. var coordSysMgr = this._coordSysMgr;
  25907. var scheduler = this._scheduler; // update before setOption
  25908. if (!ecModel) {
  25909. return;
  25910. }
  25911. ecModel.setUpdatePayload(payload);
  25912. scheduler.restoreData(ecModel, payload);
  25913. scheduler.performSeriesTasks(ecModel); // TODO
  25914. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  25915. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  25916. // Create new coordinate system each update
  25917. // In LineView may save the old coordinate system and use it to get the orignal point
  25918. coordSysMgr.create(ecModel, api);
  25919. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  25920. // stream modes after data processing, where the filtered data is used to
  25921. // deteming whether use progressive rendering.
  25922. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  25923. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  25924. // the drawback is the full coord info can not be fetched. Fortunately this full
  25925. // coord is not requied in stream mode updater currently.
  25926. coordSysMgr.update(ecModel, api);
  25927. clearColorPalette(ecModel);
  25928. scheduler.performVisualTasks(ecModel, payload);
  25929. render(this, ecModel, api, payload); // Set background
  25930. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  25931. var darkMode = ecModel.get('darkMode'); // In IE8
  25932. if (!env.canvasSupported) {
  25933. var colorArr = parse(backgroundColor);
  25934. backgroundColor = stringify(colorArr, 'rgb');
  25935. if (colorArr[3] === 0) {
  25936. backgroundColor = 'transparent';
  25937. }
  25938. } else {
  25939. zr.setBackgroundColor(backgroundColor); // Force set dark mode.
  25940. if (darkMode != null && darkMode !== 'auto') {
  25941. zr.setDarkMode(darkMode);
  25942. }
  25943. }
  25944. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  25945. },
  25946. updateTransform: function (payload) {
  25947. var _this = this;
  25948. var ecModel = this._model;
  25949. var api = this._api; // update before setOption
  25950. if (!ecModel) {
  25951. return;
  25952. }
  25953. ecModel.setUpdatePayload(payload); // ChartView.markUpdateMethod(payload, 'updateTransform');
  25954. var componentDirtyList = [];
  25955. ecModel.eachComponent(function (componentType, componentModel) {
  25956. if (componentType === 'series') {
  25957. return;
  25958. }
  25959. var componentView = _this.getViewOfComponentModel(componentModel);
  25960. if (componentView && componentView.__alive) {
  25961. if (componentView.updateTransform) {
  25962. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  25963. result && result.update && componentDirtyList.push(componentView);
  25964. } else {
  25965. componentDirtyList.push(componentView);
  25966. }
  25967. }
  25968. });
  25969. var seriesDirtyMap = createHashMap();
  25970. ecModel.eachSeries(function (seriesModel) {
  25971. var chartView = _this._chartsMap[seriesModel.__viewId];
  25972. if (chartView.updateTransform) {
  25973. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  25974. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  25975. } else {
  25976. seriesDirtyMap.set(seriesModel.uid, 1);
  25977. }
  25978. });
  25979. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25980. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  25981. this._scheduler.performVisualTasks(ecModel, payload, {
  25982. setDirty: true,
  25983. dirtyMap: seriesDirtyMap
  25984. }); // Currently, not call render of components. Geo render cost a lot.
  25985. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  25986. renderSeries(this, ecModel, api, payload, seriesDirtyMap);
  25987. performPostUpdateFuncs(ecModel, this._api);
  25988. },
  25989. updateView: function (payload) {
  25990. var ecModel = this._model; // update before setOption
  25991. if (!ecModel) {
  25992. return;
  25993. }
  25994. ecModel.setUpdatePayload(payload);
  25995. ChartView.markUpdateMethod(payload, 'updateView');
  25996. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  25997. this._scheduler.performVisualTasks(ecModel, payload, {
  25998. setDirty: true
  25999. });
  26000. render(this, this._model, this._api, payload);
  26001. performPostUpdateFuncs(ecModel, this._api);
  26002. },
  26003. updateVisual: function (payload) {
  26004. // updateMethods.update.call(this, payload);
  26005. var _this = this;
  26006. var ecModel = this._model; // update before setOption
  26007. if (!ecModel) {
  26008. return;
  26009. }
  26010. ecModel.setUpdatePayload(payload); // clear all visual
  26011. ecModel.eachSeries(function (seriesModel) {
  26012. seriesModel.getData().clearAllVisual();
  26013. }); // Perform visual
  26014. ChartView.markUpdateMethod(payload, 'updateVisual');
  26015. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  26016. this._scheduler.performVisualTasks(ecModel, payload, {
  26017. visualType: 'visual',
  26018. setDirty: true
  26019. });
  26020. ecModel.eachComponent(function (componentType, componentModel) {
  26021. if (componentType !== 'series') {
  26022. var componentView = _this.getViewOfComponentModel(componentModel);
  26023. componentView && componentView.__alive && componentView.updateVisual(componentModel, ecModel, _this._api, payload);
  26024. }
  26025. });
  26026. ecModel.eachSeries(function (seriesModel) {
  26027. var chartView = _this._chartsMap[seriesModel.__viewId];
  26028. chartView.updateVisual(seriesModel, ecModel, _this._api, payload);
  26029. });
  26030. performPostUpdateFuncs(ecModel, this._api);
  26031. },
  26032. updateLayout: function (payload) {
  26033. updateMethods.update.call(this, payload);
  26034. }
  26035. };
  26036. doConvertPixel = function (ecIns, methodName, finder, value) {
  26037. if (ecIns._disposed) {
  26038. disposedWarning(ecIns.id);
  26039. return;
  26040. }
  26041. var ecModel = ecIns._model;
  26042. var coordSysList = ecIns._coordSysMgr.getCoordinateSystems();
  26043. var result;
  26044. var parsedFinder = parseFinder(ecModel, finder);
  26045. for (var i = 0; i < coordSysList.length; i++) {
  26046. var coordSys = coordSysList[i];
  26047. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, parsedFinder, value)) != null) {
  26048. return result;
  26049. }
  26050. }
  26051. if ("development" !== 'production') {
  26052. console.warn('No coordinate system that supports ' + methodName + ' found by the given finder.');
  26053. }
  26054. };
  26055. updateStreamModes = function (ecIns, ecModel) {
  26056. var chartsMap = ecIns._chartsMap;
  26057. var scheduler = ecIns._scheduler;
  26058. ecModel.eachSeries(function (seriesModel) {
  26059. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  26060. });
  26061. };
  26062. doDispatchAction = function (payload, silent) {
  26063. var _this = this;
  26064. var ecModel = this.getModel();
  26065. var payloadType = payload.type;
  26066. var escapeConnect = payload.escapeConnect;
  26067. var actionWrap = actions[payloadType];
  26068. var actionInfo = actionWrap.actionInfo;
  26069. var cptTypeTmp = (actionInfo.update || 'update').split(':');
  26070. var updateMethod = cptTypeTmp.pop();
  26071. var cptType = cptTypeTmp[0] != null && parseClassType(cptTypeTmp[0]);
  26072. this[IN_MAIN_PROCESS_KEY] = true;
  26073. var payloads = [payload];
  26074. var batched = false; // Batch action
  26075. if (payload.batch) {
  26076. batched = true;
  26077. payloads = map(payload.batch, function (item) {
  26078. item = defaults(extend({}, item), payload);
  26079. item.batch = null;
  26080. return item;
  26081. });
  26082. }
  26083. var eventObjBatch = [];
  26084. var eventObj;
  26085. var isSelectChange = isSelectChangePayload(payload);
  26086. var isStatusChange = isHighDownPayload(payload) || isSelectChange;
  26087. each$3(payloads, function (batchItem) {
  26088. // Action can specify the event by return it.
  26089. eventObj = actionWrap.action(batchItem, _this._model, _this._api); // Emit event outside
  26090. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  26091. eventObj.type = actionInfo.event || eventObj.type;
  26092. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  26093. if (isStatusChange) {
  26094. // method, payload, mainType, subType
  26095. updateDirectly(_this, updateMethod, batchItem, 'series'); // Mark status to update
  26096. markStatusToUpdate(_this);
  26097. } else if (cptType) {
  26098. updateDirectly(_this, updateMethod, batchItem, cptType.main, cptType.sub);
  26099. }
  26100. });
  26101. if (updateMethod !== 'none' && !isStatusChange && !cptType) {
  26102. // Still dirty
  26103. if (this[OPTION_UPDATED_KEY]) {
  26104. prepare(this);
  26105. updateMethods.update.call(this, payload);
  26106. this[OPTION_UPDATED_KEY] = false;
  26107. } else {
  26108. updateMethods[updateMethod].call(this, payload);
  26109. }
  26110. } // Follow the rule of action batch
  26111. if (batched) {
  26112. eventObj = {
  26113. type: actionInfo.event || payloadType,
  26114. escapeConnect: escapeConnect,
  26115. batch: eventObjBatch
  26116. };
  26117. } else {
  26118. eventObj = eventObjBatch[0];
  26119. }
  26120. this[IN_MAIN_PROCESS_KEY] = false;
  26121. if (!silent) {
  26122. var messageCenter = this._messageCenter;
  26123. messageCenter.trigger(eventObj.type, eventObj); // Extra triggered 'selectchanged' event
  26124. if (isSelectChange) {
  26125. var newObj = {
  26126. type: 'selectchanged',
  26127. escapeConnect: escapeConnect,
  26128. selected: getAllSelectedIndices(ecModel),
  26129. isFromClick: payload.isFromClick || false,
  26130. fromAction: payload.type,
  26131. fromActionPayload: payload
  26132. };
  26133. messageCenter.trigger(newObj.type, newObj);
  26134. }
  26135. }
  26136. };
  26137. flushPendingActions = function (silent) {
  26138. var pendingActions = this._pendingActions;
  26139. while (pendingActions.length) {
  26140. var payload = pendingActions.shift();
  26141. doDispatchAction.call(this, payload, silent);
  26142. }
  26143. };
  26144. triggerUpdatedEvent = function (silent) {
  26145. !silent && this.trigger('updated');
  26146. };
  26147. /**
  26148. * Event `rendered` is triggered when zr
  26149. * rendered. It is useful for realtime
  26150. * snapshot (reflect animation).
  26151. *
  26152. * Event `finished` is triggered when:
  26153. * (1) zrender rendering finished.
  26154. * (2) initial animation finished.
  26155. * (3) progressive rendering finished.
  26156. * (4) no pending action.
  26157. * (5) no delayed setOption needs to be processed.
  26158. */
  26159. bindRenderedEvent = function (zr, ecIns) {
  26160. zr.on('rendered', function (params) {
  26161. ecIns.trigger('rendered', params); // The `finished` event should not be triggered repeatly,
  26162. // so it should only be triggered when rendering indeed happend
  26163. // in zrender. (Consider the case that dipatchAction is keep
  26164. // triggering when mouse move).
  26165. if ( // Although zr is dirty if initial animation is not finished
  26166. // and this checking is called on frame, we also check
  26167. // animation finished for robustness.
  26168. zr.animation.isFinished() && !ecIns[OPTION_UPDATED_KEY] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  26169. ecIns.trigger('finished');
  26170. }
  26171. });
  26172. };
  26173. bindMouseEvent = function (zr, ecIns) {
  26174. zr.on('mouseover', function (e) {
  26175. var el = e.target;
  26176. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26177. if (dispatcher) {
  26178. var ecData = getECData(dispatcher); // Try blur all in the related series. Then emphasis the hoverred.
  26179. // TODO. progressive mode.
  26180. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, true);
  26181. enterEmphasisWhenMouseOver(dispatcher, e);
  26182. markStatusToUpdate(ecIns);
  26183. }
  26184. }).on('mouseout', function (e) {
  26185. var el = e.target;
  26186. var dispatcher = findEventDispatcher(el, isHighDownDispatcher);
  26187. if (dispatcher) {
  26188. var ecData = getECData(dispatcher);
  26189. toggleSeriesBlurState(ecData.seriesIndex, ecData.focus, ecData.blurScope, ecIns._api, false);
  26190. leaveEmphasisWhenMouseOut(dispatcher, e);
  26191. markStatusToUpdate(ecIns);
  26192. }
  26193. }).on('click', function (e) {
  26194. var el = e.target;
  26195. var dispatcher = findEventDispatcher(el, function (target) {
  26196. return getECData(target).dataIndex != null;
  26197. }, true);
  26198. if (dispatcher) {
  26199. var actionType = dispatcher.selected ? 'unselect' : 'select';
  26200. var ecData = getECData(dispatcher);
  26201. ecIns._api.dispatchAction({
  26202. type: actionType,
  26203. dataType: ecData.dataType,
  26204. dataIndexInside: ecData.dataIndex,
  26205. seriesIndex: ecData.seriesIndex,
  26206. isFromClick: true
  26207. });
  26208. }
  26209. });
  26210. };
  26211. clearColorPalette = function (ecModel) {
  26212. ecModel.clearColorPalette();
  26213. ecModel.eachSeries(function (seriesModel) {
  26214. seriesModel.clearColorPalette();
  26215. });
  26216. };
  26217. render = function (ecIns, ecModel, api, payload) {
  26218. renderComponents(ecIns, ecModel, api, payload);
  26219. each$3(ecIns._chartsViews, function (chart) {
  26220. chart.__alive = false;
  26221. });
  26222. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  26223. each$3(ecIns._chartsViews, function (chart) {
  26224. if (!chart.__alive) {
  26225. chart.remove(ecModel, api);
  26226. }
  26227. });
  26228. };
  26229. renderComponents = function (ecIns, ecModel, api, payload, dirtyList) {
  26230. each$3(dirtyList || ecIns._componentsViews, function (componentView) {
  26231. var componentModel = componentView.__model;
  26232. clearStates(componentModel, componentView);
  26233. componentView.render(componentModel, ecModel, api, payload);
  26234. updateZ(componentModel, componentView);
  26235. updateStates(componentModel, componentView);
  26236. });
  26237. };
  26238. /**
  26239. * Render each chart and component
  26240. */
  26241. renderSeries = function (ecIns, ecModel, api, payload, dirtyMap) {
  26242. // Render all charts
  26243. var scheduler = ecIns._scheduler;
  26244. var labelManager = ecIns._labelManager;
  26245. labelManager.clearLabels();
  26246. var unfinished = false;
  26247. ecModel.eachSeries(function (seriesModel) {
  26248. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26249. chartView.__alive = true;
  26250. var renderTask = chartView.renderTask;
  26251. scheduler.updatePayload(renderTask, payload); // TODO states on marker.
  26252. clearStates(seriesModel, chartView);
  26253. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  26254. renderTask.dirty();
  26255. }
  26256. if (renderTask.perform(scheduler.getPerformArgs(renderTask))) {
  26257. unfinished = true;
  26258. }
  26259. seriesModel.__transientTransitionOpt = null;
  26260. chartView.group.silent = !!seriesModel.get('silent'); // Should not call markRedraw on group, because it will disable zrender
  26261. // increamental render (alway render from the __startIndex each frame)
  26262. // chartView.group.markRedraw();
  26263. updateBlend(seriesModel, chartView);
  26264. updateSeriesElementSelection(seriesModel); // Add labels.
  26265. labelManager.addLabelsOfSeries(chartView);
  26266. });
  26267. scheduler.unfinished = unfinished || scheduler.unfinished;
  26268. labelManager.updateLayoutConfig(api);
  26269. labelManager.layout(api);
  26270. labelManager.processLabelsOverall();
  26271. ecModel.eachSeries(function (seriesModel) {
  26272. var chartView = ecIns._chartsMap[seriesModel.__viewId]; // Update Z after labels updated. Before applying states.
  26273. updateZ(seriesModel, chartView); // NOTE: Update states after label is updated.
  26274. // label should be in normal status when layouting.
  26275. updateStates(seriesModel, chartView);
  26276. }); // If use hover layer
  26277. updateHoverLayerStatus(ecIns, ecModel);
  26278. };
  26279. performPostUpdateFuncs = function (ecModel, api) {
  26280. each$3(postUpdateFuncs, function (func) {
  26281. func(ecModel, api);
  26282. });
  26283. };
  26284. markStatusToUpdate = function (ecIns) {
  26285. ecIns[STATUS_NEEDS_UPDATE_KEY] = true; // Wake up zrender if it's sleep. Let it update states in the next frame.
  26286. ecIns.getZr().wakeUp();
  26287. };
  26288. applyChangedStates = function (ecIns) {
  26289. if (!ecIns[STATUS_NEEDS_UPDATE_KEY]) {
  26290. return;
  26291. }
  26292. ecIns.getZr().storage.traverse(function (el) {
  26293. // Not applied on removed elements, it may still in fading.
  26294. if (isElementRemoved(el)) {
  26295. return;
  26296. }
  26297. applyElementStates(el);
  26298. });
  26299. ecIns[STATUS_NEEDS_UPDATE_KEY] = false;
  26300. };
  26301. function applyElementStates(el) {
  26302. var newStates = [];
  26303. var oldStates = el.currentStates; // Keep other states.
  26304. for (var i = 0; i < oldStates.length; i++) {
  26305. var stateName = oldStates[i];
  26306. if (!(stateName === 'emphasis' || stateName === 'blur' || stateName === 'select')) {
  26307. newStates.push(stateName);
  26308. }
  26309. } // Only use states when it's exists.
  26310. if (el.selected && el.states.select) {
  26311. newStates.push('select');
  26312. }
  26313. if (el.hoverState === HOVER_STATE_EMPHASIS && el.states.emphasis) {
  26314. newStates.push('emphasis');
  26315. } else if (el.hoverState === HOVER_STATE_BLUR && el.states.blur) {
  26316. newStates.push('blur');
  26317. }
  26318. el.useStates(newStates);
  26319. }
  26320. function updateHoverLayerStatus(ecIns, ecModel) {
  26321. var zr = ecIns._zr;
  26322. var storage = zr.storage;
  26323. var elCount = 0;
  26324. storage.traverse(function (el) {
  26325. if (!el.isGroup) {
  26326. elCount++;
  26327. }
  26328. });
  26329. if (elCount > ecModel.get('hoverLayerThreshold') && !env.node && !env.worker) {
  26330. ecModel.eachSeries(function (seriesModel) {
  26331. if (seriesModel.preventUsingHoverLayer) {
  26332. return;
  26333. }
  26334. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  26335. if (chartView.__alive) {
  26336. chartView.group.traverse(function (el) {
  26337. if (el.states.emphasis) {
  26338. el.states.emphasis.hoverLayer = true;
  26339. }
  26340. });
  26341. }
  26342. });
  26343. }
  26344. }
  26345. /**
  26346. * Update chart and blend.
  26347. */
  26348. function updateBlend(seriesModel, chartView) {
  26349. var blendMode = seriesModel.get('blendMode') || null;
  26350. if ("development" !== 'production') {
  26351. if (!env.canvasSupported && blendMode && blendMode !== 'source-over') {
  26352. console.warn('Only canvas support blendMode');
  26353. }
  26354. }
  26355. chartView.group.traverse(function (el) {
  26356. // FIXME marker and other components
  26357. if (!el.isGroup) {
  26358. // DONT mark the element dirty. In case element is incremental and don't wan't to rerender.
  26359. el.style.blend = blendMode;
  26360. }
  26361. if (el.eachPendingDisplayable) {
  26362. el.eachPendingDisplayable(function (displayable) {
  26363. displayable.style.blend = blendMode;
  26364. });
  26365. }
  26366. });
  26367. }
  26368. function updateZ(model, view) {
  26369. if (model.preventAutoZ) {
  26370. return;
  26371. }
  26372. var z = model.get('z');
  26373. var zlevel = model.get('zlevel'); // Set z and zlevel
  26374. view.group.traverse(function (el) {
  26375. if (!el.isGroup) {
  26376. z != null && (el.z = z);
  26377. zlevel != null && (el.zlevel = zlevel); // TODO if textContent is on group.
  26378. var label = el.getTextContent();
  26379. var labelLine = el.getTextGuideLine();
  26380. if (label) {
  26381. label.z = el.z;
  26382. label.zlevel = el.zlevel; // lift z2 of text content
  26383. // TODO if el.emphasis.z2 is spcefied, what about textContent.
  26384. label.z2 = el.z2 + 2;
  26385. }
  26386. if (labelLine) {
  26387. var showAbove = el.textGuideLineConfig && el.textGuideLineConfig.showAbove;
  26388. labelLine.z = el.z;
  26389. labelLine.zlevel = el.zlevel;
  26390. labelLine.z2 = el.z2 + (showAbove ? 1 : -1);
  26391. }
  26392. }
  26393. });
  26394. }
  26395. // TODO States on component.
  26396. function clearStates(model, view) {
  26397. view.group.traverse(function (el) {
  26398. // Not applied on removed elements, it may still in fading.
  26399. if (isElementRemoved(el)) {
  26400. return;
  26401. }
  26402. var textContent = el.getTextContent();
  26403. var textGuide = el.getTextGuideLine();
  26404. if (el.stateTransition) {
  26405. el.stateTransition = null;
  26406. }
  26407. if (textContent && textContent.stateTransition) {
  26408. textContent.stateTransition = null;
  26409. }
  26410. if (textGuide && textGuide.stateTransition) {
  26411. textGuide.stateTransition = null;
  26412. } // TODO If el is incremental.
  26413. if (el.hasState()) {
  26414. el.prevStates = el.currentStates;
  26415. el.clearStates();
  26416. } else if (el.prevStates) {
  26417. el.prevStates = null;
  26418. }
  26419. });
  26420. }
  26421. function updateStates(model, view) {
  26422. var stateAnimationModel = model.getModel('stateAnimation');
  26423. var enableAnimation = model.isAnimationEnabled();
  26424. var duration = stateAnimationModel.get('duration');
  26425. var stateTransition = duration > 0 ? {
  26426. duration: duration,
  26427. delay: stateAnimationModel.get('delay'),
  26428. easing: stateAnimationModel.get('easing') // additive: stateAnimationModel.get('additive')
  26429. } : null;
  26430. view.group.traverse(function (el) {
  26431. if (el.states && el.states.emphasis) {
  26432. // Not applied on removed elements, it may still in fading.
  26433. if (isElementRemoved(el)) {
  26434. return;
  26435. }
  26436. if (el instanceof Path) {
  26437. savePathStates(el);
  26438. } // Only updated on changed element. In case element is incremental and don't wan't to rerender.
  26439. // TODO, a more proper way?
  26440. if (el.__dirty) {
  26441. var prevStates = el.prevStates; // Restore states without animation
  26442. if (prevStates) {
  26443. el.useStates(prevStates);
  26444. }
  26445. } // Update state transition and enable animation again.
  26446. if (enableAnimation) {
  26447. el.stateTransition = stateTransition;
  26448. var textContent = el.getTextContent();
  26449. var textGuide = el.getTextGuideLine(); // TODO Is it necessary to animate label?
  26450. if (textContent) {
  26451. textContent.stateTransition = stateTransition;
  26452. }
  26453. if (textGuide) {
  26454. textGuide.stateTransition = stateTransition;
  26455. }
  26456. } // The use higlighted and selected flag to toggle states.
  26457. if (el.__dirty) {
  26458. applyElementStates(el);
  26459. }
  26460. }
  26461. });
  26462. }
  26463. createExtensionAPI = function (ecIns) {
  26464. return new (
  26465. /** @class */
  26466. function (_super) {
  26467. __extends(class_1, _super);
  26468. function class_1() {
  26469. return _super !== null && _super.apply(this, arguments) || this;
  26470. }
  26471. class_1.prototype.getCoordinateSystems = function () {
  26472. return ecIns._coordSysMgr.getCoordinateSystems();
  26473. };
  26474. class_1.prototype.getComponentByElement = function (el) {
  26475. while (el) {
  26476. var modelInfo = el.__ecComponentInfo;
  26477. if (modelInfo != null) {
  26478. return ecIns._model.getComponent(modelInfo.mainType, modelInfo.index);
  26479. }
  26480. el = el.parent;
  26481. }
  26482. };
  26483. class_1.prototype.enterEmphasis = function (el, highlightDigit) {
  26484. enterEmphasis(el, highlightDigit);
  26485. markStatusToUpdate(ecIns);
  26486. };
  26487. class_1.prototype.leaveEmphasis = function (el, highlightDigit) {
  26488. leaveEmphasis(el, highlightDigit);
  26489. markStatusToUpdate(ecIns);
  26490. };
  26491. class_1.prototype.enterBlur = function (el) {
  26492. enterBlur(el);
  26493. markStatusToUpdate(ecIns);
  26494. };
  26495. class_1.prototype.leaveBlur = function (el) {
  26496. leaveBlur(el);
  26497. markStatusToUpdate(ecIns);
  26498. };
  26499. class_1.prototype.enterSelect = function (el) {
  26500. enterSelect(el);
  26501. markStatusToUpdate(ecIns);
  26502. };
  26503. class_1.prototype.leaveSelect = function (el) {
  26504. leaveSelect(el);
  26505. markStatusToUpdate(ecIns);
  26506. };
  26507. class_1.prototype.getModel = function () {
  26508. return ecIns.getModel();
  26509. };
  26510. class_1.prototype.getViewOfComponentModel = function (componentModel) {
  26511. return ecIns.getViewOfComponentModel(componentModel);
  26512. };
  26513. class_1.prototype.getViewOfSeriesModel = function (seriesModel) {
  26514. return ecIns.getViewOfSeriesModel(seriesModel);
  26515. };
  26516. return class_1;
  26517. }(ExtensionAPI))(ecIns);
  26518. };
  26519. enableConnect = function (chart) {
  26520. function updateConnectedChartsStatus(charts, status) {
  26521. for (var i = 0; i < charts.length; i++) {
  26522. var otherChart = charts[i];
  26523. otherChart[CONNECT_STATUS_KEY] = status;
  26524. }
  26525. }
  26526. each$3(eventActionMap, function (actionType, eventType) {
  26527. chart._messageCenter.on(eventType, function (event) {
  26528. if (connectedGroups[chart.group] && chart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_PENDING) {
  26529. if (event && event.escapeConnect) {
  26530. return;
  26531. }
  26532. var action_1 = chart.makeActionFromEvent(event);
  26533. var otherCharts_1 = [];
  26534. each$3(instances$1, function (otherChart) {
  26535. if (otherChart !== chart && otherChart.group === chart.group) {
  26536. otherCharts_1.push(otherChart);
  26537. }
  26538. });
  26539. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_PENDING);
  26540. each$3(otherCharts_1, function (otherChart) {
  26541. if (otherChart[CONNECT_STATUS_KEY] !== CONNECT_STATUS_UPDATING) {
  26542. otherChart.dispatchAction(action_1);
  26543. }
  26544. });
  26545. updateConnectedChartsStatus(otherCharts_1, CONNECT_STATUS_UPDATED);
  26546. }
  26547. });
  26548. });
  26549. };
  26550. setTransitionOpt = function (chart, transitionOpt) {
  26551. var ecModel = chart._model;
  26552. each(normalizeToArray(transitionOpt), function (transOpt) {
  26553. var errMsg;
  26554. var fromOpt = transOpt.from;
  26555. var toOpt = transOpt.to;
  26556. if (toOpt == null) {
  26557. if ("development" !== 'production') {
  26558. errMsg = '`transition.to` must be specified.';
  26559. }
  26560. throwError(errMsg);
  26561. }
  26562. var finderOpt = {
  26563. includeMainTypes: ['series'],
  26564. enableAll: false,
  26565. enableNone: false
  26566. };
  26567. var fromResult = fromOpt ? parseFinder(ecModel, fromOpt, finderOpt) : null;
  26568. var toResult = parseFinder(ecModel, toOpt, finderOpt);
  26569. var toSeries = toResult.seriesModel;
  26570. if (toSeries == null) {
  26571. errMsg = '';
  26572. if ("development" !== 'production') {
  26573. errMsg = '`transition` is only supported on series.';
  26574. }
  26575. }
  26576. if (fromResult && fromResult.seriesModel !== toSeries) {
  26577. errMsg = '';
  26578. if ("development" !== 'production') {
  26579. errMsg = '`transition.from` and `transition.to` must be specified to the same series.';
  26580. }
  26581. }
  26582. if (errMsg != null) {
  26583. throwError(errMsg);
  26584. } // Just a temp solution: mount them on series.
  26585. toSeries.__transientTransitionOpt = {
  26586. from: fromOpt ? fromOpt.dimension : null,
  26587. to: toOpt.dimension,
  26588. dividingMethod: transOpt.dividingMethod
  26589. };
  26590. });
  26591. };
  26592. }();
  26593. return ECharts;
  26594. }(Eventful);
  26595. var echartsProto = ECharts.prototype;
  26596. echartsProto.on = createRegisterEventWithLowercaseECharts('on');
  26597. echartsProto.off = createRegisterEventWithLowercaseECharts('off');
  26598. /**
  26599. * @deprecated
  26600. */
  26601. // @ts-ignore
  26602. echartsProto.one = function (eventName, cb, ctx) {
  26603. var self = this;
  26604. deprecateLog('ECharts#one is deprecated.');
  26605. function wrapped() {
  26606. var args2 = [];
  26607. for (var _i = 0; _i < arguments.length; _i++) {
  26608. args2[_i] = arguments[_i];
  26609. }
  26610. cb && cb.apply && cb.apply(this, args2); // @ts-ignore
  26611. self.off(eventName, wrapped);
  26612. }
  26613. this.on.call(this, eventName, wrapped, ctx);
  26614. }; // /**
  26615. // * Encode visual infomation from data after data processing
  26616. // *
  26617. // * @param {module:echarts/model/Global} ecModel
  26618. // * @param {object} layout
  26619. // * @param {boolean} [layoutFilter] `true`: only layout,
  26620. // * `false`: only not layout,
  26621. // * `null`/`undefined`: all.
  26622. // * @param {string} taskBaseTag
  26623. // * @private
  26624. // */
  26625. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  26626. // each(visualFuncs, function (visual, index) {
  26627. // let isLayout = visual.isLayout;
  26628. // if (layoutFilter == null
  26629. // || (layoutFilter === false && !isLayout)
  26630. // || (layoutFilter === true && isLayout)
  26631. // ) {
  26632. // visual.func(ecModel, api, payload);
  26633. // }
  26634. // });
  26635. // }
  26636. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  26637. function disposedWarning(id) {
  26638. if ("development" !== 'production') {
  26639. console.warn('Instance ' + id + ' has been disposed');
  26640. }
  26641. }
  26642. var actions = {};
  26643. /**
  26644. * Map eventType to actionType
  26645. */
  26646. var eventActionMap = {};
  26647. var dataProcessorFuncs = [];
  26648. var optionPreprocessorFuncs = [];
  26649. var postInitFuncs = [];
  26650. var postUpdateFuncs = [];
  26651. var visualFuncs = [];
  26652. var themeStorage = {};
  26653. var loadingEffects = {};
  26654. var instances$1 = {};
  26655. var connectedGroups = {};
  26656. var idBase = +new Date() - 0;
  26657. var groupIdBase = +new Date() - 0;
  26658. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  26659. /**
  26660. * @param opts.devicePixelRatio Use window.devicePixelRatio by default
  26661. * @param opts.renderer Can choose 'canvas' or 'svg' to render the chart.
  26662. * @param opts.width Use clientWidth of the input `dom` by default.
  26663. * Can be 'auto' (the same as null/undefined)
  26664. * @param opts.height Use clientHeight of the input `dom` by default.
  26665. * Can be 'auto' (the same as null/undefined)
  26666. */
  26667. function init$1(dom, theme, opts) {
  26668. if ("development" !== 'production') {
  26669. if (!dom) {
  26670. throw new Error('Initialize failed: invalid dom.');
  26671. }
  26672. }
  26673. var existInstance = getInstanceByDom(dom);
  26674. if (existInstance) {
  26675. if ("development" !== 'production') {
  26676. console.warn('There is a chart instance already initialized on the dom.');
  26677. }
  26678. return existInstance;
  26679. }
  26680. if ("development" !== 'production') {
  26681. if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && (!dom.clientWidth && (!opts || opts.width == null) || !dom.clientHeight && (!opts || opts.height == null))) {
  26682. console.warn('Can\'t get DOM width or height. Please check ' + 'dom.clientWidth and dom.clientHeight. They should not be 0.' + 'For example, you may need to call this in the callback ' + 'of window.onload.');
  26683. }
  26684. }
  26685. var chart = new ECharts(dom, theme, opts);
  26686. chart.id = 'ec_' + idBase++;
  26687. instances$1[chart.id] = chart;
  26688. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  26689. enableConnect(chart);
  26690. each$3(postInitFuncs, function (postInitFunc) {
  26691. postInitFunc(chart);
  26692. });
  26693. return chart;
  26694. }
  26695. /**
  26696. * @usage
  26697. * (A)
  26698. * ```js
  26699. * let chart1 = echarts.init(dom1);
  26700. * let chart2 = echarts.init(dom2);
  26701. * chart1.group = 'xxx';
  26702. * chart2.group = 'xxx';
  26703. * echarts.connect('xxx');
  26704. * ```
  26705. * (B)
  26706. * ```js
  26707. * let chart1 = echarts.init(dom1);
  26708. * let chart2 = echarts.init(dom2);
  26709. * echarts.connect('xxx', [chart1, chart2]);
  26710. * ```
  26711. */
  26712. function connect(groupId) {
  26713. // Is array of charts
  26714. if (isArray(groupId)) {
  26715. var charts = groupId;
  26716. groupId = null; // If any chart has group
  26717. each$3(charts, function (chart) {
  26718. if (chart.group != null) {
  26719. groupId = chart.group;
  26720. }
  26721. });
  26722. groupId = groupId || 'g_' + groupIdBase++;
  26723. each$3(charts, function (chart) {
  26724. chart.group = groupId;
  26725. });
  26726. }
  26727. connectedGroups[groupId] = true;
  26728. return groupId;
  26729. }
  26730. /**
  26731. * @deprecated
  26732. */
  26733. function disConnect(groupId) {
  26734. connectedGroups[groupId] = false;
  26735. }
  26736. /**
  26737. * Alias and backword compat
  26738. */
  26739. var disconnect = disConnect;
  26740. /**
  26741. * Dispose a chart instance
  26742. */
  26743. function dispose$1(chart) {
  26744. if (typeof chart === 'string') {
  26745. chart = instances$1[chart];
  26746. } else if (!(chart instanceof ECharts)) {
  26747. // Try to treat as dom
  26748. chart = getInstanceByDom(chart);
  26749. }
  26750. if (chart instanceof ECharts && !chart.isDisposed()) {
  26751. chart.dispose();
  26752. }
  26753. }
  26754. function getInstanceByDom(dom) {
  26755. return instances$1[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  26756. }
  26757. function getInstanceById(key) {
  26758. return instances$1[key];
  26759. }
  26760. /**
  26761. * Register theme
  26762. */
  26763. function registerTheme(name, theme) {
  26764. themeStorage[name] = theme;
  26765. }
  26766. /**
  26767. * Register option preprocessor
  26768. */
  26769. function registerPreprocessor(preprocessorFunc) {
  26770. if (indexOf$1(optionPreprocessorFuncs, preprocessorFunc) < 0) {
  26771. optionPreprocessorFuncs.push(preprocessorFunc);
  26772. }
  26773. }
  26774. function registerProcessor(priority, processor) {
  26775. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_DEFAULT);
  26776. }
  26777. /**
  26778. * Register postIniter
  26779. * @param {Function} postInitFunc
  26780. */
  26781. function registerPostInit(postInitFunc) {
  26782. if (indexOf$1(postInitFuncs, postInitFunc) < 0) {
  26783. postInitFunc && postInitFuncs.push(postInitFunc);
  26784. }
  26785. }
  26786. /**
  26787. * Register postUpdater
  26788. * @param {Function} postUpdateFunc
  26789. */
  26790. function registerPostUpdate(postUpdateFunc) {
  26791. if (indexOf$1(postUpdateFuncs, postUpdateFunc) < 0) {
  26792. postUpdateFunc && postUpdateFuncs.push(postUpdateFunc);
  26793. }
  26794. }
  26795. function registerAction(actionInfo, eventName, action) {
  26796. if (typeof eventName === 'function') {
  26797. action = eventName;
  26798. eventName = '';
  26799. }
  26800. var actionType = isObject$2(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  26801. event: eventName
  26802. }][0]; // Event name is all lowercase
  26803. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  26804. eventName = actionInfo.event;
  26805. if (eventActionMap[eventName]) {
  26806. // Already registered.
  26807. return;
  26808. } // Validate action type and event name.
  26809. assert$1(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  26810. if (!actions[actionType]) {
  26811. actions[actionType] = {
  26812. action: action,
  26813. actionInfo: actionInfo
  26814. };
  26815. }
  26816. eventActionMap[eventName] = actionType;
  26817. }
  26818. function registerCoordinateSystem(type, coordSysCreator) {
  26819. CoordinateSystemManager.register(type, coordSysCreator);
  26820. }
  26821. /**
  26822. * Get dimensions of specified coordinate system.
  26823. * @param {string} type
  26824. * @return {Array.<string|Object>}
  26825. */
  26826. function getCoordinateSystemDimensions(type) {
  26827. var coordSysCreator = CoordinateSystemManager.get(type);
  26828. if (coordSysCreator) {
  26829. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  26830. }
  26831. }
  26832. function registerLayout(priority, layoutTask) {
  26833. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  26834. }
  26835. function registerVisual(priority, visualTask) {
  26836. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  26837. }
  26838. var registeredTasks = [];
  26839. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  26840. if (isFunction$1(priority) || isObject$2(priority)) {
  26841. fn = priority;
  26842. priority = defaultPriority;
  26843. }
  26844. if ("development" !== 'production') {
  26845. if (isNaN(priority) || priority == null) {
  26846. throw new Error('Illegal priority');
  26847. } // Check duplicate
  26848. each$3(targetList, function (wrap) {
  26849. assert$1(wrap.__raw !== fn);
  26850. });
  26851. } // Already registered
  26852. if (indexOf$1(registeredTasks, fn) >= 0) {
  26853. return;
  26854. }
  26855. registeredTasks.push(fn);
  26856. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  26857. stageHandler.__prio = priority;
  26858. stageHandler.__raw = fn;
  26859. targetList.push(stageHandler);
  26860. }
  26861. function registerLoading(name, loadingFx) {
  26862. loadingEffects[name] = loadingFx;
  26863. }
  26864. /**
  26865. * ZRender need a canvas context to do measureText.
  26866. * But in node environment canvas may be created by node-canvas.
  26867. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  26868. *
  26869. * Be careful of using it in the browser.
  26870. *
  26871. * @example
  26872. * let Canvas = require('canvas');
  26873. * let echarts = require('echarts');
  26874. * echarts.setCanvasCreator(function () {
  26875. * // Small size is enough.
  26876. * return new Canvas(32, 32);
  26877. * });
  26878. */
  26879. function setCanvasCreator(creator) {
  26880. $override('createCanvas', creator);
  26881. }
  26882. /**
  26883. * The parameters and usage: see `mapDataStorage.registerMap`.
  26884. * Compatible with previous `echarts.registerMap`.
  26885. */
  26886. function registerMap(mapName, geoJson, specialAreas) {
  26887. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  26888. }
  26889. function getMap(mapName) {
  26890. // For backward compatibility, only return the first one.
  26891. var records = mapDataStorage.retrieveMap(mapName); // FIXME support SVG, where return not only records[0].
  26892. return records && records[0] && {
  26893. // @ts-ignore
  26894. geoJson: records[0].geoJSON,
  26895. specialAreas: records[0].specialAreas
  26896. };
  26897. }
  26898. var registerTransform = registerExternalTransform;
  26899. /**
  26900. * Globa dispatchAction to a specified chart instance.
  26901. */
  26902. // export function dispatchAction(payload: { chartId: string } & Payload, opt?: Parameters<ECharts['dispatchAction']>[1]) {
  26903. // if (!payload || !payload.chartId) {
  26904. // // Must have chartId to find chart
  26905. // return;
  26906. // }
  26907. // const chart = instances[payload.chartId];
  26908. // if (chart) {
  26909. // chart.dispatchAction(payload, opt);
  26910. // }
  26911. // }
  26912. // Buitlin global visual
  26913. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesStyleTask);
  26914. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataStyleTask);
  26915. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataColorPaletteTask);
  26916. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesSymbolTask);
  26917. registerVisual(PRIORITY_VISUAL_CHART_DATA_CUSTOM, dataSymbolTask);
  26918. registerVisual(PRIORITY_VISUAL_DECAL, decalVisual);
  26919. registerPreprocessor(globalBackwardCompat);
  26920. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  26921. registerLoading('default', defaultLoading); // Default actions
  26922. registerAction({
  26923. type: HIGHLIGHT_ACTION_TYPE,
  26924. event: HIGHLIGHT_ACTION_TYPE,
  26925. update: HIGHLIGHT_ACTION_TYPE
  26926. }, noop);
  26927. registerAction({
  26928. type: DOWNPLAY_ACTION_TYPE,
  26929. event: DOWNPLAY_ACTION_TYPE,
  26930. update: DOWNPLAY_ACTION_TYPE
  26931. }, noop);
  26932. registerAction({
  26933. type: SELECT_ACTION_TYPE,
  26934. event: SELECT_ACTION_TYPE,
  26935. update: SELECT_ACTION_TYPE
  26936. }, noop);
  26937. registerAction({
  26938. type: UNSELECT_ACTION_TYPE,
  26939. event: UNSELECT_ACTION_TYPE,
  26940. update: UNSELECT_ACTION_TYPE
  26941. }, noop);
  26942. registerAction({
  26943. type: TOGGLE_SELECT_ACTION_TYPE,
  26944. event: TOGGLE_SELECT_ACTION_TYPE,
  26945. update: TOGGLE_SELECT_ACTION_TYPE
  26946. }, noop); // Default theme
  26947. registerTheme('light', lightTheme);
  26948. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  26949. // be mounted on `echarts` is the extension `dataTool` is imported.
  26950. var dataTool = {};
  26951. var extensions = [];
  26952. var extensionRegisters = {
  26953. registerPreprocessor: registerPreprocessor,
  26954. registerProcessor: registerProcessor,
  26955. registerPostInit: registerPostInit,
  26956. registerPostUpdate: registerPostUpdate,
  26957. registerAction: registerAction,
  26958. registerCoordinateSystem: registerCoordinateSystem,
  26959. registerLayout: registerLayout,
  26960. registerVisual: registerVisual,
  26961. registerTransform: registerTransform,
  26962. registerLoading: registerLoading,
  26963. registerMap: registerMap,
  26964. PRIORITY: PRIORITY,
  26965. ComponentModel: ComponentModel,
  26966. ComponentView: ComponentView,
  26967. SeriesModel: SeriesModel,
  26968. ChartView: ChartView,
  26969. // TODO Use ComponentModel and SeriesModel instead of Constructor
  26970. registerComponentModel: function (ComponentModelClass) {
  26971. ComponentModel.registerClass(ComponentModelClass);
  26972. },
  26973. registerComponentView: function (ComponentViewClass) {
  26974. ComponentView.registerClass(ComponentViewClass);
  26975. },
  26976. registerSeriesModel: function (SeriesModelClass) {
  26977. SeriesModel.registerClass(SeriesModelClass);
  26978. },
  26979. registerChartView: function (ChartViewClass) {
  26980. ChartView.registerClass(ChartViewClass);
  26981. },
  26982. registerSubTypeDefaulter: function (componentType, defaulter) {
  26983. ComponentModel.registerSubTypeDefaulter(componentType, defaulter);
  26984. },
  26985. registerPainter: function (painterType, PainterCtor) {
  26986. registerPainter(painterType, PainterCtor);
  26987. }
  26988. };
  26989. function use(ext) {
  26990. if (isArray(ext)) {
  26991. // use([ChartLine, ChartBar]);
  26992. each(ext, function (singleExt) {
  26993. use(singleExt);
  26994. });
  26995. return;
  26996. }
  26997. if (indexOf(extensions, ext) >= 0) {
  26998. return;
  26999. }
  27000. extensions.push(ext);
  27001. if (isFunction(ext)) {
  27002. ext = {
  27003. install: ext
  27004. };
  27005. }
  27006. ext.install(extensionRegisters);
  27007. }
  27008. /*
  27009. * Licensed to the Apache Software Foundation (ASF) under one
  27010. * or more contributor license agreements. See the NOTICE file
  27011. * distributed with this work for additional information
  27012. * regarding copyright ownership. The ASF licenses this file
  27013. * to you under the Apache License, Version 2.0 (the
  27014. * "License"); you may not use this file except in compliance
  27015. * with the License. You may obtain a copy of the License at
  27016. *
  27017. * http://www.apache.org/licenses/LICENSE-2.0
  27018. *
  27019. * Unless required by applicable law or agreed to in writing,
  27020. * software distributed under the License is distributed on an
  27021. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27022. * KIND, either express or implied. See the License for the
  27023. * specific language governing permissions and limitations
  27024. * under the License.
  27025. */
  27026. /**
  27027. * AUTO-GENERATED FILE. DO NOT MODIFY.
  27028. */
  27029. /*
  27030. * Licensed to the Apache Software Foundation (ASF) under one
  27031. * or more contributor license agreements. See the NOTICE file
  27032. * distributed with this work for additional information
  27033. * regarding copyright ownership. The ASF licenses this file
  27034. * to you under the Apache License, Version 2.0 (the
  27035. * "License"); you may not use this file except in compliance
  27036. * with the License. You may obtain a copy of the License at
  27037. *
  27038. * http://www.apache.org/licenses/LICENSE-2.0
  27039. *
  27040. * Unless required by applicable law or agreed to in writing,
  27041. * software distributed under the License is distributed on an
  27042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27043. * KIND, either express or implied. See the License for the
  27044. * specific language governing permissions and limitations
  27045. * under the License.
  27046. */
  27047. function dataIndexMapValueLength(valNumOrArrLengthMoreThan2) {
  27048. return valNumOrArrLengthMoreThan2 == null ? 0 : valNumOrArrLengthMoreThan2.length || 1;
  27049. }
  27050. function defaultKeyGetter(item) {
  27051. return item;
  27052. }
  27053. var DataDiffer =
  27054. /** @class */
  27055. function () {
  27056. /**
  27057. * @param context Can be visited by this.context in callback.
  27058. */
  27059. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context, // By default: 'oneToOne'.
  27060. diffMode) {
  27061. this._old = oldArr;
  27062. this._new = newArr;
  27063. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  27064. this._newKeyGetter = newKeyGetter || defaultKeyGetter; // Visible in callback via `this.context`;
  27065. this.context = context;
  27066. this._diffModeMultiple = diffMode === 'multiple';
  27067. }
  27068. /**
  27069. * Callback function when add a data
  27070. */
  27071. DataDiffer.prototype.add = function (func) {
  27072. this._add = func;
  27073. return this;
  27074. };
  27075. /**
  27076. * Callback function when update a data
  27077. */
  27078. DataDiffer.prototype.update = function (func) {
  27079. this._update = func;
  27080. return this;
  27081. };
  27082. /**
  27083. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27084. */
  27085. DataDiffer.prototype.updateManyToOne = function (func) {
  27086. this._updateManyToOne = func;
  27087. return this;
  27088. };
  27089. /**
  27090. * Callback function when update a data and only work in `cbMode: 'byKey'`.
  27091. */
  27092. DataDiffer.prototype.updateOneToMany = function (func) {
  27093. this._updateOneToMany = func;
  27094. return this;
  27095. };
  27096. /**
  27097. * Callback function when remove a data
  27098. */
  27099. DataDiffer.prototype.remove = function (func) {
  27100. this._remove = func;
  27101. return this;
  27102. };
  27103. DataDiffer.prototype.execute = function () {
  27104. this[this._diffModeMultiple ? '_executeMultiple' : '_executeOneToOne']();
  27105. };
  27106. DataDiffer.prototype._executeOneToOne = function () {
  27107. var oldArr = this._old;
  27108. var newArr = this._new;
  27109. var newDataIndexMap = {};
  27110. var oldDataKeyArr = new Array(oldArr.length);
  27111. var newDataKeyArr = new Array(newArr.length);
  27112. this._initIndexMap(oldArr, null, oldDataKeyArr, '_oldKeyGetter');
  27113. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27114. for (var i = 0; i < oldArr.length; i++) {
  27115. var oldKey = oldDataKeyArr[i];
  27116. var newIdxMapVal = newDataIndexMap[oldKey];
  27117. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal); // idx can never be empty array here. see 'set null' logic below.
  27118. if (newIdxMapValLen > 1) {
  27119. // Consider there is duplicate key (for example, use dataItem.name as key).
  27120. // We should make sure every item in newArr and oldArr can be visited.
  27121. var newIdx = newIdxMapVal.shift();
  27122. if (newIdxMapVal.length === 1) {
  27123. newDataIndexMap[oldKey] = newIdxMapVal[0];
  27124. }
  27125. this._update && this._update(newIdx, i);
  27126. } else if (newIdxMapValLen === 1) {
  27127. newDataIndexMap[oldKey] = null;
  27128. this._update && this._update(newIdxMapVal, i);
  27129. } else {
  27130. this._remove && this._remove(i);
  27131. }
  27132. }
  27133. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27134. };
  27135. /**
  27136. * For example, consider the case:
  27137. * oldData: [o0, o1, o2, o3, o4, o5, o6, o7],
  27138. * newData: [n0, n1, n2, n3, n4, n5, n6, n7, n8],
  27139. * Where:
  27140. * o0, o1, n0 has key 'a' (many to one)
  27141. * o5, n4, n5, n6 has key 'b' (one to many)
  27142. * o2, n1 has key 'c' (one to one)
  27143. * n2, n3 has key 'd' (add)
  27144. * o3, o4 has key 'e' (remove)
  27145. * o6, o7, n7, n8 has key 'f' (many to many, treated as add and remove)
  27146. * Then:
  27147. * (The order of the following directives are not ensured.)
  27148. * this._updateManyToOne(n0, [o0, o1]);
  27149. * this._updateOneToMany([n4, n5, n6], o5);
  27150. * this._update(n1, o2);
  27151. * this._remove(o3);
  27152. * this._remove(o4);
  27153. * this._remove(o6);
  27154. * this._remove(o7);
  27155. * this._add(n2);
  27156. * this._add(n3);
  27157. * this._add(n7);
  27158. * this._add(n8);
  27159. */
  27160. DataDiffer.prototype._executeMultiple = function () {
  27161. var oldArr = this._old;
  27162. var newArr = this._new;
  27163. var oldDataIndexMap = {};
  27164. var newDataIndexMap = {};
  27165. var oldDataKeyArr = [];
  27166. var newDataKeyArr = [];
  27167. this._initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter');
  27168. this._initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter');
  27169. for (var i = 0; i < oldDataKeyArr.length; i++) {
  27170. var oldKey = oldDataKeyArr[i];
  27171. var oldIdxMapVal = oldDataIndexMap[oldKey];
  27172. var newIdxMapVal = newDataIndexMap[oldKey];
  27173. var oldIdxMapValLen = dataIndexMapValueLength(oldIdxMapVal);
  27174. var newIdxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27175. if (oldIdxMapValLen > 1 && newIdxMapValLen === 1) {
  27176. this._updateManyToOne && this._updateManyToOne(newIdxMapVal, oldIdxMapVal);
  27177. newDataIndexMap[oldKey] = null;
  27178. } else if (oldIdxMapValLen === 1 && newIdxMapValLen > 1) {
  27179. this._updateOneToMany && this._updateOneToMany(newIdxMapVal, oldIdxMapVal);
  27180. newDataIndexMap[oldKey] = null;
  27181. } else if (oldIdxMapValLen === 1 && newIdxMapValLen === 1) {
  27182. this._update && this._update(newIdxMapVal, oldIdxMapVal);
  27183. newDataIndexMap[oldKey] = null;
  27184. } else if (oldIdxMapValLen > 1) {
  27185. for (var i_1 = 0; i_1 < oldIdxMapValLen; i_1++) {
  27186. this._remove && this._remove(oldIdxMapVal[i_1]);
  27187. }
  27188. } else {
  27189. this._remove && this._remove(oldIdxMapVal);
  27190. }
  27191. }
  27192. this._performRestAdd(newDataKeyArr, newDataIndexMap);
  27193. };
  27194. DataDiffer.prototype._performRestAdd = function (newDataKeyArr, newDataIndexMap) {
  27195. for (var i = 0; i < newDataKeyArr.length; i++) {
  27196. var newKey = newDataKeyArr[i];
  27197. var newIdxMapVal = newDataIndexMap[newKey];
  27198. var idxMapValLen = dataIndexMapValueLength(newIdxMapVal);
  27199. if (idxMapValLen > 1) {
  27200. for (var j = 0; j < idxMapValLen; j++) {
  27201. this._add && this._add(newIdxMapVal[j]);
  27202. }
  27203. } else if (idxMapValLen === 1) {
  27204. this._add && this._add(newIdxMapVal);
  27205. } // Support both `newDataKeyArr` are duplication removed or not removed.
  27206. newDataIndexMap[newKey] = null;
  27207. }
  27208. };
  27209. DataDiffer.prototype._initIndexMap = function (arr, // Can be null.
  27210. map, // In 'byKey', the output `keyArr` is duplication removed.
  27211. // In 'byIndex', the output `keyArr` is not duplication removed and
  27212. // its indices are accurately corresponding to `arr`.
  27213. keyArr, keyGetterName) {
  27214. var cbModeMultiple = this._diffModeMultiple;
  27215. for (var i = 0; i < arr.length; i++) {
  27216. // Add prefix to avoid conflict with Object.prototype.
  27217. var key = '_ec_' + this[keyGetterName](arr[i], i);
  27218. if (!cbModeMultiple) {
  27219. keyArr[i] = key;
  27220. }
  27221. if (!map) {
  27222. continue;
  27223. }
  27224. var idxMapVal = map[key];
  27225. var idxMapValLen = dataIndexMapValueLength(idxMapVal);
  27226. if (idxMapValLen === 0) {
  27227. // Simple optimize: in most cases, one index has one key,
  27228. // do not need array.
  27229. map[key] = i;
  27230. if (cbModeMultiple) {
  27231. keyArr.push(key);
  27232. }
  27233. } else if (idxMapValLen === 1) {
  27234. map[key] = [idxMapVal, i];
  27235. } else {
  27236. idxMapVal.push(i);
  27237. }
  27238. }
  27239. };
  27240. return DataDiffer;
  27241. }();
  27242. function summarizeDimensions(data) {
  27243. var summary = {};
  27244. var encode = summary.encode = {};
  27245. var notExtraCoordDimMap = createHashMap();
  27246. var defaultedLabel = [];
  27247. var defaultedTooltip = []; // See the comment of `List.js#userOutput`.
  27248. var userOutput = summary.userOutput = {
  27249. dimensionNames: data.dimensions.slice(),
  27250. encode: {}
  27251. };
  27252. each(data.dimensions, function (dimName) {
  27253. var dimItem = data.getDimensionInfo(dimName);
  27254. var coordDim = dimItem.coordDim;
  27255. if (coordDim) {
  27256. if ("development" !== 'production') {
  27257. assert(VISUAL_DIMENSIONS.get(coordDim) == null);
  27258. }
  27259. var coordDimIndex = dimItem.coordDimIndex;
  27260. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  27261. if (!dimItem.isExtraCoord) {
  27262. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  27263. // because when dataset is used, it is hard to guess which dimension
  27264. // can be value dimension. If both show x, y on label is not look good,
  27265. // and conventionally y axis is focused more.
  27266. if (mayLabelDimType(dimItem.type)) {
  27267. defaultedLabel[0] = dimName;
  27268. } // User output encode do not contain generated coords.
  27269. // And it only has index. User can use index to retrieve value from the raw item array.
  27270. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  27271. }
  27272. if (dimItem.defaultTooltip) {
  27273. defaultedTooltip.push(dimName);
  27274. }
  27275. }
  27276. VISUAL_DIMENSIONS.each(function (v, otherDim) {
  27277. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  27278. var dimIndex = dimItem.otherDims[otherDim];
  27279. if (dimIndex != null && dimIndex !== false) {
  27280. encodeArr[dimIndex] = dimItem.name;
  27281. }
  27282. });
  27283. });
  27284. var dataDimsOnCoord = [];
  27285. var encodeFirstDimNotExtra = {};
  27286. notExtraCoordDimMap.each(function (v, coordDim) {
  27287. var dimArr = encode[coordDim];
  27288. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  27289. // dim canot on more than one coordDim.
  27290. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  27291. });
  27292. summary.dataDimsOnCoord = dataDimsOnCoord;
  27293. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  27294. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  27295. // in this way. Use label.formatter instead. May be remove this approach someday.
  27296. if (encodeLabel && encodeLabel.length) {
  27297. defaultedLabel = encodeLabel.slice();
  27298. }
  27299. var encodeTooltip = encode.tooltip;
  27300. if (encodeTooltip && encodeTooltip.length) {
  27301. defaultedTooltip = encodeTooltip.slice();
  27302. } else if (!defaultedTooltip.length) {
  27303. defaultedTooltip = defaultedLabel.slice();
  27304. }
  27305. encode.defaultedLabel = defaultedLabel;
  27306. encode.defaultedTooltip = defaultedTooltip;
  27307. return summary;
  27308. }
  27309. function getOrCreateEncodeArr(encode, dim) {
  27310. if (!encode.hasOwnProperty(dim)) {
  27311. encode[dim] = [];
  27312. }
  27313. return encode[dim];
  27314. } // FIXME:TS should be type `AxisType`
  27315. function getDimensionTypeByAxis(axisType) {
  27316. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  27317. }
  27318. function mayLabelDimType(dimType) {
  27319. // In most cases, ordinal and time do not suitable for label.
  27320. // Ordinal info can be displayed on axis. Time is too long.
  27321. return !(dimType === 'ordinal' || dimType === 'time');
  27322. } // function findTheLastDimMayLabel(data) {
  27323. // // Get last value dim
  27324. // let dimensions = data.dimensions.slice();
  27325. // let valueType;
  27326. // let valueDim;
  27327. // while (dimensions.length && (
  27328. // valueDim = dimensions.pop(),
  27329. // valueType = data.getDimensionInfo(valueDim).type,
  27330. // valueType === 'ordinal' || valueType === 'time'
  27331. // )) {} // jshint ignore:line
  27332. // return valueDim;
  27333. // }
  27334. var DataDimensionInfo =
  27335. /** @class */
  27336. function () {
  27337. /**
  27338. * @param opt All of the fields will be shallow copied.
  27339. */
  27340. function DataDimensionInfo(opt) {
  27341. /**
  27342. * The format of `otherDims` is:
  27343. * ```js
  27344. * {
  27345. * tooltip: number optional,
  27346. * label: number optional,
  27347. * itemName: number optional,
  27348. * seriesName: number optional,
  27349. * }
  27350. * ```
  27351. *
  27352. * A `series.encode` can specified these fields:
  27353. * ```js
  27354. * encode: {
  27355. * // "3, 1, 5" is the index of data dimension.
  27356. * tooltip: [3, 1, 5],
  27357. * label: [0, 3],
  27358. * ...
  27359. * }
  27360. * ```
  27361. * `otherDims` is the parse result of the `series.encode` above, like:
  27362. * ```js
  27363. * // Suppose the index of this data dimension is `3`.
  27364. * this.otherDims = {
  27365. * // `3` is at the index `0` of the `encode.tooltip`
  27366. * tooltip: 0,
  27367. * // `3` is at the index `1` of the `encode.tooltip`
  27368. * label: 1
  27369. * };
  27370. * ```
  27371. *
  27372. * This prop should never be `null`/`undefined` after initialized.
  27373. */
  27374. this.otherDims = {};
  27375. if (opt != null) {
  27376. extend(this, opt);
  27377. }
  27378. }
  27379. return DataDimensionInfo;
  27380. }();
  27381. var mathFloor = Math.floor;
  27382. var isObject$3 = isObject;
  27383. var map$1 = map;
  27384. var UNDEFINED = 'undefined';
  27385. var INDEX_NOT_FOUND = -1; // Use prefix to avoid index to be the same as otherIdList[idx],
  27386. // which will cause weird udpate animation.
  27387. var ID_PREFIX = 'e\0\0';
  27388. var dataCtors = {
  27389. 'float': typeof Float64Array === UNDEFINED ? Array : Float64Array,
  27390. 'int': typeof Int32Array === UNDEFINED ? Array : Int32Array,
  27391. // Ordinal data type can be string or int
  27392. 'ordinal': Array,
  27393. 'number': Array,
  27394. 'time': Array
  27395. }; // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  27396. // different from the Ctor of typed array.
  27397. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  27398. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  27399. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  27400. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx', '_nameRepeatCount'];
  27401. var CLONE_PROPERTIES = ['_extent', '_approximateExtent', '_rawExtent']; // -----------------------------
  27402. // Internal method declarations:
  27403. // -----------------------------
  27404. var defaultDimValueGetters;
  27405. var prepareInvertedIndex;
  27406. var getIndicesCtor;
  27407. var prepareStorage;
  27408. var getRawIndexWithoutIndices;
  27409. var getRawIndexWithIndices;
  27410. var getId;
  27411. var getIdNameFromStore;
  27412. var makeIdFromName;
  27413. var normalizeDimensions;
  27414. var validateDimensions;
  27415. var cloneListForMapAndSample;
  27416. var getInitialExtent;
  27417. var setItemDataAndSeriesIndex;
  27418. var transferProperties;
  27419. var List =
  27420. /** @class */
  27421. function () {
  27422. /**
  27423. * @param dimensions
  27424. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  27425. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  27426. */
  27427. function List(dimensions, hostModel) {
  27428. this.type = 'list';
  27429. this._count = 0;
  27430. this._rawCount = 0;
  27431. this._storage = {}; // We have an extra array store here. It's faster to be acessed than KV structured `_storage`.
  27432. // We profile the code `storage[dim]` and it seems to be KeyedLoadIC_Megamorphic instead of fast property access.
  27433. // Not sure why this happens. But using an extra array seems leads to faster `initData`
  27434. // See https://github.com/apache/incubator-echarts/pull/13314 for more explanation.
  27435. this._storageArr = [];
  27436. this._nameList = [];
  27437. this._idList = []; // Models of data option is stored sparse for optimizing memory cost
  27438. // Never used yet (not used yet).
  27439. // private _optionModels: Model[] = [];
  27440. // Global visual properties after visual coding
  27441. this._visual = {}; // Globel layout properties.
  27442. this._layout = {}; // Item visual properties after visual coding
  27443. this._itemVisuals = []; // Item layout properties after layout
  27444. this._itemLayouts = []; // Graphic elemnents
  27445. this._graphicEls = []; // Raw extent will not be cloned, but only transfered.
  27446. // It will not be calculated util needed.
  27447. this._rawExtent = {};
  27448. this._extent = {}; // key: dim, value: extent
  27449. this._approximateExtent = {};
  27450. this._calculationInfo = {}; // Having detected that there is data item is non primitive type
  27451. // (in type `OptionDataItemObject`).
  27452. // Like `data: [ { value: xx, itemStyle: {...} }, ...]`
  27453. // At present it only happen in `SOURCE_FORMAT_ORIGINAL`.
  27454. this.hasItemOption = true; // Methods that create a new list based on this list should be listed here.
  27455. // Notice that those method should `RETURN` the new list.
  27456. this.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'lttbDownSample', 'map']; // Methods that change indices of this list should be listed here.
  27457. this.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  27458. this.DOWNSAMPLE_METHODS = ['downSample', 'lttbDownSample'];
  27459. /**
  27460. * Get raw data index.
  27461. * Do not initialize.
  27462. * Default `getRawIndex`. And it can be changed.
  27463. */
  27464. this.getRawIndex = getRawIndexWithoutIndices;
  27465. dimensions = dimensions || ['x', 'y'];
  27466. var dimensionInfos = {};
  27467. var dimensionNames = [];
  27468. var invertedIndicesMap = {};
  27469. for (var i = 0; i < dimensions.length; i++) {
  27470. // Use the original dimensions[i], where other flag props may exists.
  27471. var dimInfoInput = dimensions[i];
  27472. var dimensionInfo = isString(dimInfoInput) ? new DataDimensionInfo({
  27473. name: dimInfoInput
  27474. }) : !(dimInfoInput instanceof DataDimensionInfo) ? new DataDimensionInfo(dimInfoInput) : dimInfoInput;
  27475. var dimensionName = dimensionInfo.name;
  27476. dimensionInfo.type = dimensionInfo.type || 'float';
  27477. if (!dimensionInfo.coordDim) {
  27478. dimensionInfo.coordDim = dimensionName;
  27479. dimensionInfo.coordDimIndex = 0;
  27480. }
  27481. var otherDims = dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  27482. dimensionNames.push(dimensionName);
  27483. dimensionInfos[dimensionName] = dimensionInfo;
  27484. dimensionInfo.index = i;
  27485. if (dimensionInfo.createInvertedIndices) {
  27486. invertedIndicesMap[dimensionName] = [];
  27487. }
  27488. if (otherDims.itemName === 0) {
  27489. this._nameDimIdx = i;
  27490. this._nameOrdinalMeta = dimensionInfo.ordinalMeta;
  27491. }
  27492. if (otherDims.itemId === 0) {
  27493. this._idDimIdx = i;
  27494. this._idOrdinalMeta = dimensionInfo.ordinalMeta;
  27495. }
  27496. }
  27497. this.dimensions = dimensionNames;
  27498. this._dimensionInfos = dimensionInfos;
  27499. this.hostModel = hostModel; // Cache summary info for fast visit. See "dimensionHelper".
  27500. this._dimensionsSummary = summarizeDimensions(this);
  27501. this._invertedIndicesMap = invertedIndicesMap;
  27502. this.userOutput = this._dimensionsSummary.userOutput;
  27503. }
  27504. /**
  27505. * The meanings of the input parameter `dim`:
  27506. *
  27507. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  27508. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  27509. * + If dim is a number-like string (e.g., `"1"`):
  27510. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  27511. * + If not, it will be converted to a number, which means the index of the dimension.
  27512. * (why? because of the backward compatbility. We have been tolerating number-like string in
  27513. * dimension setting, although now it seems that it is not a good idea.)
  27514. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  27515. * if no dimension name is defined as `"1"`.
  27516. * + If dim is a not-number-like string, it means the concrete dim name.
  27517. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  27518. * or customized in `dimensions` property of option like `"age"`.
  27519. *
  27520. * Get dimension name
  27521. * @param dim See above.
  27522. * @return Concrete dim name.
  27523. */
  27524. List.prototype.getDimension = function (dim) {
  27525. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  27526. || !isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim)) {
  27527. dim = this.dimensions[dim];
  27528. }
  27529. return dim;
  27530. };
  27531. /**
  27532. * Get type and calculation info of particular dimension
  27533. * @param dim
  27534. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  27535. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  27536. */
  27537. List.prototype.getDimensionInfo = function (dim) {
  27538. // Do not clone, because there may be categories in dimInfo.
  27539. return this._dimensionInfos[this.getDimension(dim)];
  27540. };
  27541. /**
  27542. * concrete dimension name list on coord.
  27543. */
  27544. List.prototype.getDimensionsOnCoord = function () {
  27545. return this._dimensionsSummary.dataDimsOnCoord.slice();
  27546. };
  27547. List.prototype.mapDimension = function (coordDim, idx) {
  27548. var dimensionsSummary = this._dimensionsSummary;
  27549. if (idx == null) {
  27550. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  27551. }
  27552. var dims = dimensionsSummary.encode[coordDim];
  27553. return dims ? dims[idx] : null;
  27554. };
  27555. List.prototype.mapDimensionsAll = function (coordDim) {
  27556. var dimensionsSummary = this._dimensionsSummary;
  27557. var dims = dimensionsSummary.encode[coordDim];
  27558. return (dims || []).slice();
  27559. };
  27560. /**
  27561. * Initialize from data
  27562. * @param data source or data or data provider.
  27563. * @param nameList The name of a datum is used on data diff and
  27564. * default label/tooltip.
  27565. * A name can be specified in encode.itemName,
  27566. * or dataItem.name (only for series option data),
  27567. * or provided in nameList from outside.
  27568. */
  27569. List.prototype.initData = function (data, nameList, dimValueGetter) {
  27570. var notProvider = isSourceInstance(data) || isArrayLike(data);
  27571. var provider = notProvider ? new DefaultDataProvider(data, this.dimensions.length) : data;
  27572. if ("development" !== 'production') {
  27573. assert(notProvider || isFunction(provider.getItem) && isFunction(provider.count), 'Inavlid data provider.');
  27574. }
  27575. this._rawData = provider;
  27576. var sourceFormat = provider.getSource().sourceFormat; // Clear
  27577. this._storage = {};
  27578. this._indices = null;
  27579. this._dontMakeIdFromName = this._idDimIdx != null || sourceFormat === SOURCE_FORMAT_TYPED_ARRAY // Cosndier performance.
  27580. || !!provider.fillStorage;
  27581. this._nameList = (nameList || []).slice();
  27582. this._idList = [];
  27583. this._nameRepeatCount = {};
  27584. if (!dimValueGetter) {
  27585. this.hasItemOption = false;
  27586. }
  27587. this.defaultDimValueGetter = defaultDimValueGetters[sourceFormat]; // Default dim value getter
  27588. this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter;
  27589. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows; // Reset raw extent.
  27590. this._rawExtent = {};
  27591. this._initDataFromProvider(0, provider.count()); // If data has no item option.
  27592. if (provider.pure) {
  27593. this.hasItemOption = false;
  27594. }
  27595. };
  27596. List.prototype.getProvider = function () {
  27597. return this._rawData;
  27598. };
  27599. /**
  27600. * Caution: Can be only called on raw data (before `this._indices` created).
  27601. */
  27602. List.prototype.appendData = function (data) {
  27603. if ("development" !== 'production') {
  27604. assert(!this._indices, 'appendData can only be called on raw data.');
  27605. }
  27606. var rawData = this._rawData;
  27607. var start = this.count();
  27608. rawData.appendData(data);
  27609. var end = rawData.count();
  27610. if (!rawData.persistent) {
  27611. end += start;
  27612. }
  27613. this._initDataFromProvider(start, end, true);
  27614. };
  27615. /**
  27616. * Caution: Can be only called on raw data (before `this._indices` created).
  27617. * This method does not modify `rawData` (`dataProvider`), but only
  27618. * add values to storage.
  27619. *
  27620. * The final count will be increased by `Math.max(values.length, names.length)`.
  27621. *
  27622. * @param values That is the SourceType: 'arrayRows', like
  27623. * [
  27624. * [12, 33, 44],
  27625. * [NaN, 43, 1],
  27626. * ['-', 'asdf', 0]
  27627. * ]
  27628. * Each item is exaclty cooresponding to a dimension.
  27629. */
  27630. List.prototype.appendValues = function (values, names) {
  27631. var storage = this._storage;
  27632. var dimensions = this.dimensions;
  27633. var dimLen = dimensions.length;
  27634. var rawExtent = this._rawExtent;
  27635. var start = this.count();
  27636. var end = start + Math.max(values.length, names ? names.length : 0);
  27637. for (var i = 0; i < dimLen; i++) {
  27638. var dim = dimensions[i];
  27639. if (!rawExtent[dim]) {
  27640. rawExtent[dim] = getInitialExtent();
  27641. }
  27642. prepareStorage(storage, this._dimensionInfos[dim], end, true);
  27643. }
  27644. var rawExtentArr = map$1(dimensions, function (dim) {
  27645. return rawExtent[dim];
  27646. });
  27647. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  27648. return storage[dim];
  27649. });
  27650. var emptyDataItem = [];
  27651. for (var idx = start; idx < end; idx++) {
  27652. var sourceIdx = idx - start; // Store the data by dimensions
  27653. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  27654. var dim = dimensions[dimIdx];
  27655. var val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, dimIdx);
  27656. storageArr[dimIdx][idx] = val;
  27657. var dimRawExtent = rawExtentArr[dimIdx];
  27658. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27659. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27660. }
  27661. if (names) {
  27662. this._nameList[idx] = names[sourceIdx];
  27663. if (!this._dontMakeIdFromName) {
  27664. makeIdFromName(this, idx);
  27665. }
  27666. }
  27667. }
  27668. this._rawCount = this._count = end; // Reset data extent
  27669. this._extent = {};
  27670. prepareInvertedIndex(this);
  27671. };
  27672. List.prototype._initDataFromProvider = function (start, end, append) {
  27673. if (start >= end) {
  27674. return;
  27675. }
  27676. var rawData = this._rawData;
  27677. var storage = this._storage;
  27678. var dimensions = this.dimensions;
  27679. var dimLen = dimensions.length;
  27680. var dimensionInfoMap = this._dimensionInfos;
  27681. var nameList = this._nameList;
  27682. var idList = this._idList;
  27683. var rawExtent = this._rawExtent;
  27684. var sourceFormat = rawData.getSource().sourceFormat;
  27685. var isFormatOriginal = sourceFormat === SOURCE_FORMAT_ORIGINAL;
  27686. for (var i = 0; i < dimLen; i++) {
  27687. var dim = dimensions[i];
  27688. if (!rawExtent[dim]) {
  27689. rawExtent[dim] = getInitialExtent();
  27690. }
  27691. prepareStorage(storage, dimensionInfoMap[dim], end, append);
  27692. }
  27693. var storageArr = this._storageArr = map$1(dimensions, function (dim) {
  27694. return storage[dim];
  27695. });
  27696. var rawExtentArr = map$1(dimensions, function (dim) {
  27697. return rawExtent[dim];
  27698. });
  27699. if (rawData.fillStorage) {
  27700. rawData.fillStorage(start, end, storageArr, rawExtentArr);
  27701. } else {
  27702. var dataItem = [];
  27703. for (var idx = start; idx < end; idx++) {
  27704. // NOTICE: Try not to write things into dataItem
  27705. dataItem = rawData.getItem(idx, dataItem); // Each data item is value
  27706. // [1, 2]
  27707. // 2
  27708. // Bar chart, line chart which uses category axis
  27709. // only gives the 'y' value. 'x' value is the indices of category
  27710. // Use a tempValue to normalize the value to be a (x, y) value
  27711. // Store the data by dimensions
  27712. for (var dimIdx = 0; dimIdx < dimLen; dimIdx++) {
  27713. var dim = dimensions[dimIdx];
  27714. var dimStorage = storageArr[dimIdx]; // PENDING NULL is empty or zero
  27715. var val = this._dimValueGetter(dataItem, dim, idx, dimIdx);
  27716. dimStorage[idx] = val;
  27717. var dimRawExtent = rawExtentArr[dimIdx];
  27718. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  27719. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  27720. } // If dataItem is {name: ...} or {id: ...}, it has highest priority.
  27721. // This kind of ids and names are always stored `_nameList` and `_idList`.
  27722. if (isFormatOriginal && !rawData.pure && dataItem) {
  27723. var itemName = dataItem.name;
  27724. if (nameList[idx] == null && itemName != null) {
  27725. nameList[idx] = convertOptionIdName(itemName, null);
  27726. }
  27727. var itemId = dataItem.id;
  27728. if (idList[idx] == null && itemId != null) {
  27729. idList[idx] = convertOptionIdName(itemId, null);
  27730. }
  27731. }
  27732. if (!this._dontMakeIdFromName) {
  27733. makeIdFromName(this, idx);
  27734. }
  27735. }
  27736. }
  27737. if (!rawData.persistent && rawData.clean) {
  27738. // Clean unused data if data source is typed array.
  27739. rawData.clean();
  27740. }
  27741. this._rawCount = this._count = end; // Reset data extent
  27742. this._extent = {};
  27743. prepareInvertedIndex(this);
  27744. };
  27745. List.prototype.count = function () {
  27746. return this._count;
  27747. };
  27748. List.prototype.getIndices = function () {
  27749. var newIndices;
  27750. var indices = this._indices;
  27751. if (indices) {
  27752. var Ctor = indices.constructor;
  27753. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  27754. if (Ctor === Array) {
  27755. newIndices = new Ctor(thisCount);
  27756. for (var i = 0; i < thisCount; i++) {
  27757. newIndices[i] = indices[i];
  27758. }
  27759. } else {
  27760. newIndices = new Ctor(indices.buffer, 0, thisCount);
  27761. }
  27762. } else {
  27763. var Ctor = getIndicesCtor(this);
  27764. newIndices = new Ctor(this.count());
  27765. for (var i = 0; i < newIndices.length; i++) {
  27766. newIndices[i] = i;
  27767. }
  27768. }
  27769. return newIndices;
  27770. }; // Get data by index of dimension.
  27771. // Because in v8 access array by number variable is faster than access object by string variable
  27772. // Not sure why but the optimization just works.
  27773. List.prototype.getByDimIdx = function (dimIdx, idx) {
  27774. if (!(idx >= 0 && idx < this._count)) {
  27775. return NaN;
  27776. }
  27777. var dimStore = this._storageArr[dimIdx];
  27778. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  27779. };
  27780. /**
  27781. * Get value. Return NaN if idx is out of range.
  27782. * @param dim Dim must be concrete name.
  27783. */
  27784. List.prototype.get = function (dim, idx) {
  27785. if (!(idx >= 0 && idx < this._count)) {
  27786. return NaN;
  27787. }
  27788. var dimStore = this._storage[dim];
  27789. return dimStore ? dimStore[this.getRawIndex(idx)] : NaN;
  27790. };
  27791. /**
  27792. * @param dim concrete dim
  27793. */
  27794. List.prototype.getByRawIndex = function (dim, rawIdx) {
  27795. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  27796. return NaN;
  27797. }
  27798. var dimStore = this._storage[dim];
  27799. return dimStore ? dimStore[rawIdx] : NaN;
  27800. };
  27801. List.prototype.getValues = function (dimensions, idx) {
  27802. var values = [];
  27803. if (!isArray(dimensions)) {
  27804. // stack = idx;
  27805. idx = dimensions;
  27806. dimensions = this.dimensions;
  27807. }
  27808. for (var i = 0, len = dimensions.length; i < len; i++) {
  27809. values.push(this.get(dimensions[i], idx
  27810. /*, stack */
  27811. ));
  27812. }
  27813. return values;
  27814. };
  27815. /**
  27816. * If value is NaN. Inlcuding '-'
  27817. * Only check the coord dimensions.
  27818. */
  27819. List.prototype.hasValue = function (idx) {
  27820. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  27821. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  27822. // Ordinal type originally can be string or number.
  27823. // But when an ordinal type is used on coord, it can
  27824. // not be string but only number. So we can also use isNaN.
  27825. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  27826. return false;
  27827. }
  27828. }
  27829. return true;
  27830. };
  27831. /**
  27832. * Get extent of data in one dimension
  27833. */
  27834. List.prototype.getDataExtent = function (dim) {
  27835. // Make sure use concrete dim as cache name.
  27836. dim = this.getDimension(dim);
  27837. var dimData = this._storage[dim];
  27838. var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim));
  27839. if (!dimData) {
  27840. return initialExtent;
  27841. } // Make more strict checkings to ensure hitting cache.
  27842. var currEnd = this.count(); // let cacheName = [dim, !!stack].join('_');
  27843. // let cacheName = dim;
  27844. // Consider the most cases when using data zoom, `getDataExtent`
  27845. // happened before filtering. We cache raw extent, which is not
  27846. // necessary to be cleared and recalculated when restore data.
  27847. var useRaw = !this._indices; // && !stack;
  27848. var dimExtent;
  27849. if (useRaw) {
  27850. return this._rawExtent[dim].slice();
  27851. }
  27852. dimExtent = this._extent[dim];
  27853. if (dimExtent) {
  27854. return dimExtent.slice();
  27855. }
  27856. dimExtent = initialExtent;
  27857. var min = dimExtent[0];
  27858. var max = dimExtent[1];
  27859. for (var i = 0; i < currEnd; i++) {
  27860. var rawIdx = this.getRawIndex(i);
  27861. var value = dimData[rawIdx];
  27862. value < min && (min = value);
  27863. value > max && (max = value);
  27864. }
  27865. dimExtent = [min, max];
  27866. this._extent[dim] = dimExtent;
  27867. return dimExtent;
  27868. };
  27869. /**
  27870. * PENDING: In fact currently this function is only used to short-circuit
  27871. * the calling of `scale.unionExtentFromData` when data have been filtered by modules
  27872. * like "dataZoom". `scale.unionExtentFromData` is used to calculate data extent for series on
  27873. * an axis, but if a "axis related data filter module" is used, the extent of the axis have
  27874. * been fixed and no need to calling `scale.unionExtentFromData` actually.
  27875. * But if we add "custom data filter" in future, which is not "axis related", this method may
  27876. * be still needed.
  27877. *
  27878. * Optimize for the scenario that data is filtered by a given extent.
  27879. * Consider that if data amount is more than hundreds of thousand,
  27880. * extent calculation will cost more than 10ms and the cache will
  27881. * be erased because of the filtering.
  27882. */
  27883. List.prototype.getApproximateExtent = function (dim) {
  27884. dim = this.getDimension(dim);
  27885. return this._approximateExtent[dim] || this.getDataExtent(dim);
  27886. };
  27887. /**
  27888. * Calculate extent on a filtered data might be time consuming.
  27889. * Approximate extent is only used for: calculte extent of filtered data outside.
  27890. */
  27891. List.prototype.setApproximateExtent = function (extent, dim) {
  27892. dim = this.getDimension(dim);
  27893. this._approximateExtent[dim] = extent.slice();
  27894. };
  27895. List.prototype.getCalculationInfo = function (key) {
  27896. return this._calculationInfo[key];
  27897. };
  27898. List.prototype.setCalculationInfo = function (key, value) {
  27899. isObject$3(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  27900. };
  27901. /**
  27902. * Get sum of data in one dimension
  27903. */
  27904. List.prototype.getSum = function (dim) {
  27905. var dimData = this._storage[dim];
  27906. var sum = 0;
  27907. if (dimData) {
  27908. for (var i = 0, len = this.count(); i < len; i++) {
  27909. var value = this.get(dim, i);
  27910. if (!isNaN(value)) {
  27911. sum += value;
  27912. }
  27913. }
  27914. }
  27915. return sum;
  27916. };
  27917. /**
  27918. * Get median of data in one dimension
  27919. */
  27920. List.prototype.getMedian = function (dim) {
  27921. var dimDataArray = []; // map all data of one dimension
  27922. this.each(dim, function (val) {
  27923. if (!isNaN(val)) {
  27924. dimDataArray.push(val);
  27925. }
  27926. }); // TODO
  27927. // Use quick select?
  27928. var sortedDimDataArray = dimDataArray.sort(function (a, b) {
  27929. return a - b;
  27930. });
  27931. var len = this.count(); // calculate median
  27932. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  27933. }; // /**
  27934. // * Retreive the index with given value
  27935. // * @param {string} dim Concrete dimension.
  27936. // * @param {number} value
  27937. // * @return {number}
  27938. // */
  27939. // Currently incorrect: should return dataIndex but not rawIndex.
  27940. // Do not fix it until this method is to be used somewhere.
  27941. // FIXME Precision of float value
  27942. // indexOf(dim, value) {
  27943. // let storage = this._storage;
  27944. // let dimData = storage[dim];
  27945. // let chunkSize = this._chunkSize;
  27946. // if (dimData) {
  27947. // for (let i = 0, len = this.count(); i < len; i++) {
  27948. // let chunkIndex = mathFloor(i / chunkSize);
  27949. // let chunkOffset = i % chunkSize;
  27950. // if (dimData[chunkIndex][chunkOffset] === value) {
  27951. // return i;
  27952. // }
  27953. // }
  27954. // }
  27955. // return -1;
  27956. // }
  27957. /**
  27958. * Only support the dimension which inverted index created.
  27959. * Do not support other cases until required.
  27960. * @param dim concrete dim
  27961. * @param value ordinal index
  27962. * @return rawIndex
  27963. */
  27964. List.prototype.rawIndexOf = function (dim, value) {
  27965. var invertedIndices = dim && this._invertedIndicesMap[dim];
  27966. if ("development" !== 'production') {
  27967. if (!invertedIndices) {
  27968. throw new Error('Do not supported yet');
  27969. }
  27970. }
  27971. var rawIndex = invertedIndices[value];
  27972. if (rawIndex == null || isNaN(rawIndex)) {
  27973. return INDEX_NOT_FOUND;
  27974. }
  27975. return rawIndex;
  27976. };
  27977. /**
  27978. * Retreive the index with given name
  27979. */
  27980. List.prototype.indexOfName = function (name) {
  27981. for (var i = 0, len = this.count(); i < len; i++) {
  27982. if (this.getName(i) === name) {
  27983. return i;
  27984. }
  27985. }
  27986. return -1;
  27987. };
  27988. /**
  27989. * Retreive the index with given raw data index
  27990. */
  27991. List.prototype.indexOfRawIndex = function (rawIndex) {
  27992. if (rawIndex >= this._rawCount || rawIndex < 0) {
  27993. return -1;
  27994. }
  27995. if (!this._indices) {
  27996. return rawIndex;
  27997. } // Indices are ascending
  27998. var indices = this._indices; // If rawIndex === dataIndex
  27999. var rawDataIndex = indices[rawIndex];
  28000. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  28001. return rawIndex;
  28002. }
  28003. var left = 0;
  28004. var right = this._count - 1;
  28005. while (left <= right) {
  28006. var mid = (left + right) / 2 | 0;
  28007. if (indices[mid] < rawIndex) {
  28008. left = mid + 1;
  28009. } else if (indices[mid] > rawIndex) {
  28010. right = mid - 1;
  28011. } else {
  28012. return mid;
  28013. }
  28014. }
  28015. return -1;
  28016. };
  28017. /**
  28018. * Retreive the index of nearest value
  28019. * @param dim
  28020. * @param value
  28021. * @param [maxDistance=Infinity]
  28022. * @return If and only if multiple indices has
  28023. * the same value, they are put to the result.
  28024. */
  28025. List.prototype.indicesOfNearest = function (dim, value, maxDistance) {
  28026. var storage = this._storage;
  28027. var dimData = storage[dim];
  28028. var nearestIndices = [];
  28029. if (!dimData) {
  28030. return nearestIndices;
  28031. }
  28032. if (maxDistance == null) {
  28033. maxDistance = Infinity;
  28034. }
  28035. var minDist = Infinity;
  28036. var minDiff = -1;
  28037. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/List.js`.
  28038. for (var i = 0, len = this.count(); i < len; i++) {
  28039. var dataIndex = this.getRawIndex(i);
  28040. var diff = value - dimData[dataIndex];
  28041. var dist = Math.abs(diff);
  28042. if (dist <= maxDistance) {
  28043. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  28044. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  28045. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  28046. // So we chose the one that `diff >= 0` in this csae.
  28047. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  28048. // should be push to `nearestIndices`.
  28049. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  28050. minDist = dist;
  28051. minDiff = diff;
  28052. nearestIndicesLen = 0;
  28053. }
  28054. if (diff === minDiff) {
  28055. nearestIndices[nearestIndicesLen++] = i;
  28056. }
  28057. }
  28058. }
  28059. nearestIndices.length = nearestIndicesLen;
  28060. return nearestIndices;
  28061. };
  28062. /**
  28063. * Get raw data item
  28064. */
  28065. List.prototype.getRawDataItem = function (idx) {
  28066. if (!this._rawData.persistent) {
  28067. var val = [];
  28068. for (var i = 0; i < this.dimensions.length; i++) {
  28069. var dim = this.dimensions[i];
  28070. val.push(this.get(dim, idx));
  28071. }
  28072. return val;
  28073. } else {
  28074. return this._rawData.getItem(this.getRawIndex(idx));
  28075. }
  28076. };
  28077. /**
  28078. * @return Never be null/undefined. `number` will be converted to string. Becuase:
  28079. * In most cases, name is used in display, where returning a string is more convenient.
  28080. * In other cases, name is used in query (see `indexOfName`), where we can keep the
  28081. * rule that name `2` equals to name `'2'`.
  28082. */
  28083. List.prototype.getName = function (idx) {
  28084. var rawIndex = this.getRawIndex(idx);
  28085. var name = this._nameList[rawIndex];
  28086. if (name == null && this._nameDimIdx != null) {
  28087. name = getIdNameFromStore(this, this._nameDimIdx, this._nameOrdinalMeta, rawIndex);
  28088. }
  28089. if (name == null) {
  28090. name = '';
  28091. }
  28092. return name;
  28093. };
  28094. /**
  28095. * @return Never null/undefined. `number` will be converted to string. Becuase:
  28096. * In all cases having encountered at present, id is used in making diff comparison, which
  28097. * are usually based on hash map. We can keep the rule that the internal id are always string
  28098. * (treat `2` is the same as `'2'`) to make the related logic simple.
  28099. */
  28100. List.prototype.getId = function (idx) {
  28101. return getId(this, this.getRawIndex(idx));
  28102. };
  28103. List.prototype.each = function (dims, cb, ctx, ctxCompat) {
  28104. var _this = this;
  28105. if (!this._count) {
  28106. return;
  28107. }
  28108. if (typeof dims === 'function') {
  28109. ctxCompat = ctx;
  28110. ctx = cb;
  28111. cb = dims;
  28112. dims = [];
  28113. } // ctxCompat just for compat echarts3
  28114. var fCtx = ctx || ctxCompat || this;
  28115. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  28116. if ("development" !== 'production') {
  28117. validateDimensions(this, dimNames);
  28118. }
  28119. var dimSize = dimNames.length;
  28120. var dimIndices = map$1(dimNames, function (dimName) {
  28121. return _this._dimensionInfos[dimName].index;
  28122. });
  28123. var storageArr = this._storageArr;
  28124. for (var i = 0, len = this.count(); i < len; i++) {
  28125. var rawIdx = this.getRawIndex(i); // Simple optimization
  28126. switch (dimSize) {
  28127. case 0:
  28128. cb.call(fCtx, i);
  28129. break;
  28130. case 1:
  28131. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], i);
  28132. break;
  28133. case 2:
  28134. cb.call(fCtx, storageArr[dimIndices[0]][rawIdx], storageArr[dimIndices[1]][rawIdx], i);
  28135. break;
  28136. default:
  28137. var k = 0;
  28138. var value = [];
  28139. for (; k < dimSize; k++) {
  28140. value[k] = storageArr[dimIndices[k]][rawIdx];
  28141. } // Index
  28142. value[k] = i;
  28143. cb.apply(fCtx, value);
  28144. }
  28145. }
  28146. };
  28147. List.prototype.filterSelf = function (dims, cb, ctx, ctxCompat) {
  28148. var _this = this;
  28149. if (!this._count) {
  28150. return;
  28151. }
  28152. if (typeof dims === 'function') {
  28153. ctxCompat = ctx;
  28154. ctx = cb;
  28155. cb = dims;
  28156. dims = [];
  28157. } // ctxCompat just for compat echarts3
  28158. var fCtx = ctx || ctxCompat || this;
  28159. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  28160. if ("development" !== 'production') {
  28161. validateDimensions(this, dimNames);
  28162. }
  28163. var count = this.count();
  28164. var Ctor = getIndicesCtor(this);
  28165. var newIndices = new Ctor(count);
  28166. var value = [];
  28167. var dimSize = dimNames.length;
  28168. var offset = 0;
  28169. var dimIndices = map$1(dimNames, function (dimName) {
  28170. return _this._dimensionInfos[dimName].index;
  28171. });
  28172. var dim0 = dimIndices[0];
  28173. var storageArr = this._storageArr;
  28174. for (var i = 0; i < count; i++) {
  28175. var keep = void 0;
  28176. var rawIdx = this.getRawIndex(i); // Simple optimization
  28177. if (dimSize === 0) {
  28178. keep = cb.call(fCtx, i);
  28179. } else if (dimSize === 1) {
  28180. var val = storageArr[dim0][rawIdx];
  28181. keep = cb.call(fCtx, val, i);
  28182. } else {
  28183. var k = 0;
  28184. for (; k < dimSize; k++) {
  28185. value[k] = storageArr[dimIndices[k]][rawIdx];
  28186. }
  28187. value[k] = i;
  28188. keep = cb.apply(fCtx, value);
  28189. }
  28190. if (keep) {
  28191. newIndices[offset++] = rawIdx;
  28192. }
  28193. } // Set indices after filtered.
  28194. if (offset < count) {
  28195. this._indices = newIndices;
  28196. }
  28197. this._count = offset; // Reset data extent
  28198. this._extent = {};
  28199. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28200. return this;
  28201. };
  28202. /**
  28203. * Select data in range. (For optimization of filter)
  28204. * (Manually inline code, support 5 million data filtering in data zoom.)
  28205. */
  28206. List.prototype.selectRange = function (range) {
  28207. var _this = this;
  28208. var len = this._count;
  28209. if (!len) {
  28210. return;
  28211. }
  28212. var dimensions = [];
  28213. for (var dim in range) {
  28214. if (range.hasOwnProperty(dim)) {
  28215. dimensions.push(dim);
  28216. }
  28217. }
  28218. if ("development" !== 'production') {
  28219. validateDimensions(this, dimensions);
  28220. }
  28221. var dimSize = dimensions.length;
  28222. if (!dimSize) {
  28223. return;
  28224. }
  28225. var originalCount = this.count();
  28226. var Ctor = getIndicesCtor(this);
  28227. var newIndices = new Ctor(originalCount);
  28228. var offset = 0;
  28229. var dim0 = dimensions[0];
  28230. var dimIndices = map$1(dimensions, function (dimName) {
  28231. return _this._dimensionInfos[dimName].index;
  28232. });
  28233. var min = range[dim0][0];
  28234. var max = range[dim0][1];
  28235. var storageArr = this._storageArr;
  28236. var quickFinished = false;
  28237. if (!this._indices) {
  28238. // Extreme optimization for common case. About 2x faster in chrome.
  28239. var idx = 0;
  28240. if (dimSize === 1) {
  28241. var dimStorage = storageArr[dimIndices[0]];
  28242. for (var i = 0; i < len; i++) {
  28243. var val = dimStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  28244. // value indicates the line should be broken. But for the case like
  28245. // scatter plot, a data item with empty value will not be rendered,
  28246. // but the axis extent may be effected if some other dim of the data
  28247. // item has value. Fortunately it is not a significant negative effect.
  28248. if (val >= min && val <= max || isNaN(val)) {
  28249. newIndices[offset++] = idx;
  28250. }
  28251. idx++;
  28252. }
  28253. quickFinished = true;
  28254. } else if (dimSize === 2) {
  28255. var dimStorage = storageArr[dimIndices[0]];
  28256. var dimStorage2 = storageArr[dimIndices[1]];
  28257. var min2 = range[dimensions[1]][0];
  28258. var max2 = range[dimensions[1]][1];
  28259. for (var i = 0; i < len; i++) {
  28260. var val = dimStorage[i];
  28261. var val2 = dimStorage2[i]; // Do not filter NaN, see comment above.
  28262. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  28263. newIndices[offset++] = idx;
  28264. }
  28265. idx++;
  28266. }
  28267. quickFinished = true;
  28268. }
  28269. }
  28270. if (!quickFinished) {
  28271. if (dimSize === 1) {
  28272. for (var i = 0; i < originalCount; i++) {
  28273. var rawIndex = this.getRawIndex(i);
  28274. var val = storageArr[dimIndices[0]][rawIndex]; // Do not filter NaN, see comment above.
  28275. if (val >= min && val <= max || isNaN(val)) {
  28276. newIndices[offset++] = rawIndex;
  28277. }
  28278. }
  28279. } else {
  28280. for (var i = 0; i < originalCount; i++) {
  28281. var keep = true;
  28282. var rawIndex = this.getRawIndex(i);
  28283. for (var k = 0; k < dimSize; k++) {
  28284. var dimk = dimensions[k];
  28285. var val = storageArr[dimIndices[k]][rawIndex]; // Do not filter NaN, see comment above.
  28286. if (val < range[dimk][0] || val > range[dimk][1]) {
  28287. keep = false;
  28288. }
  28289. }
  28290. if (keep) {
  28291. newIndices[offset++] = this.getRawIndex(i);
  28292. }
  28293. }
  28294. }
  28295. } // Set indices after filtered.
  28296. if (offset < originalCount) {
  28297. this._indices = newIndices;
  28298. }
  28299. this._count = offset; // Reset data extent
  28300. this._extent = {};
  28301. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28302. return this;
  28303. };
  28304. /* eslint-enable */
  28305. List.prototype.mapArray = function (dims, cb, ctx, ctxCompat) {
  28306. if (typeof dims === 'function') {
  28307. ctxCompat = ctx;
  28308. ctx = cb;
  28309. cb = dims;
  28310. dims = [];
  28311. } // ctxCompat just for compat echarts3
  28312. ctx = ctx || ctxCompat || this;
  28313. var result = [];
  28314. this.each(dims, function () {
  28315. result.push(cb && cb.apply(this, arguments));
  28316. }, ctx);
  28317. return result;
  28318. };
  28319. List.prototype.map = function (dims, cb, ctx, ctxCompat) {
  28320. var fCtx = ctx || ctxCompat || this;
  28321. var dimNames = map$1(normalizeDimensions(dims), this.getDimension, this);
  28322. if ("development" !== 'production') {
  28323. validateDimensions(this, dimNames);
  28324. }
  28325. var list = cloneListForMapAndSample(this, dimNames);
  28326. var storage = list._storage; // Following properties are all immutable.
  28327. // So we can reference to the same value
  28328. list._indices = this._indices;
  28329. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28330. var tmpRetValue = [];
  28331. var dimSize = dimNames.length;
  28332. var dataCount = this.count();
  28333. var values = [];
  28334. var rawExtent = list._rawExtent;
  28335. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  28336. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  28337. values[dimIndex] = this.get(dimNames[dimIndex], dataIndex);
  28338. }
  28339. values[dimSize] = dataIndex;
  28340. var retValue = cb && cb.apply(fCtx, values);
  28341. if (retValue != null) {
  28342. // a number or string (in oridinal dimension)?
  28343. if (typeof retValue !== 'object') {
  28344. tmpRetValue[0] = retValue;
  28345. retValue = tmpRetValue;
  28346. }
  28347. var rawIndex = this.getRawIndex(dataIndex);
  28348. for (var i = 0; i < retValue.length; i++) {
  28349. var dim = dimNames[i];
  28350. var val = retValue[i];
  28351. var rawExtentOnDim = rawExtent[dim];
  28352. var dimStore = storage[dim];
  28353. if (dimStore) {
  28354. dimStore[rawIndex] = val;
  28355. }
  28356. if (val < rawExtentOnDim[0]) {
  28357. rawExtentOnDim[0] = val;
  28358. }
  28359. if (val > rawExtentOnDim[1]) {
  28360. rawExtentOnDim[1] = val;
  28361. }
  28362. }
  28363. }
  28364. }
  28365. return list;
  28366. };
  28367. /**
  28368. * Large data down sampling on given dimension
  28369. * @param sampleIndex Sample index for name and id
  28370. */
  28371. List.prototype.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  28372. var list = cloneListForMapAndSample(this, [dimension]);
  28373. var targetStorage = list._storage;
  28374. var frameValues = [];
  28375. var frameSize = mathFloor(1 / rate);
  28376. var dimStore = targetStorage[dimension];
  28377. var len = this.count();
  28378. var rawExtentOnDim = list._rawExtent[dimension];
  28379. var newIndices = new (getIndicesCtor(this))(len);
  28380. var offset = 0;
  28381. for (var i = 0; i < len; i += frameSize) {
  28382. // Last frame
  28383. if (frameSize > len - i) {
  28384. frameSize = len - i;
  28385. frameValues.length = frameSize;
  28386. }
  28387. for (var k = 0; k < frameSize; k++) {
  28388. var dataIdx = this.getRawIndex(i + k);
  28389. frameValues[k] = dimStore[dataIdx];
  28390. }
  28391. var value = sampleValue(frameValues);
  28392. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)); // Only write value on the filtered data
  28393. dimStore[sampleFrameIdx] = value;
  28394. if (value < rawExtentOnDim[0]) {
  28395. rawExtentOnDim[0] = value;
  28396. }
  28397. if (value > rawExtentOnDim[1]) {
  28398. rawExtentOnDim[1] = value;
  28399. }
  28400. newIndices[offset++] = sampleFrameIdx;
  28401. }
  28402. list._count = offset;
  28403. list._indices = newIndices;
  28404. list.getRawIndex = getRawIndexWithIndices;
  28405. return list;
  28406. };
  28407. /**
  28408. * Large data down sampling using largest-triangle-three-buckets
  28409. * @param {string} valueDimension
  28410. * @param {number} targetCount
  28411. */
  28412. List.prototype.lttbDownSample = function (valueDimension, rate) {
  28413. var list = cloneListForMapAndSample(this, []);
  28414. var targetStorage = list._storage;
  28415. var dimStore = targetStorage[valueDimension];
  28416. var len = this.count();
  28417. var newIndices = new (getIndicesCtor(this))(len);
  28418. var sampledIndex = 0;
  28419. var frameSize = mathFloor(1 / rate);
  28420. var currentRawIndex = this.getRawIndex(0);
  28421. var maxArea;
  28422. var area;
  28423. var nextRawIndex; // First frame use the first data.
  28424. newIndices[sampledIndex++] = currentRawIndex;
  28425. for (var i = 1; i < len - 1; i += frameSize) {
  28426. var nextFrameStart = Math.min(i + frameSize, len - 1);
  28427. var nextFrameEnd = Math.min(i + frameSize * 2, len);
  28428. var avgX = (nextFrameEnd + nextFrameStart) / 2;
  28429. var avgY = 0;
  28430. for (var idx = nextFrameStart; idx < nextFrameEnd; idx++) {
  28431. var rawIndex = this.getRawIndex(idx);
  28432. var y = dimStore[rawIndex];
  28433. if (isNaN(y)) {
  28434. continue;
  28435. }
  28436. avgY += y;
  28437. }
  28438. avgY /= nextFrameEnd - nextFrameStart;
  28439. var frameStart = i;
  28440. var frameEnd = Math.min(i + frameSize, len);
  28441. var pointAX = i - 1;
  28442. var pointAY = dimStore[currentRawIndex];
  28443. maxArea = -1;
  28444. nextRawIndex = frameStart; // Find a point from current frame that construct a triangel with largest area with previous selected point
  28445. // And the average of next frame.
  28446. for (var idx = frameStart; idx < frameEnd; idx++) {
  28447. var rawIndex = this.getRawIndex(idx);
  28448. var y = dimStore[rawIndex];
  28449. if (isNaN(y)) {
  28450. continue;
  28451. } // Calculate triangle area over three buckets
  28452. area = Math.abs((pointAX - avgX) * (y - pointAY) - (pointAX - idx) * (avgY - pointAY));
  28453. if (area > maxArea) {
  28454. maxArea = area;
  28455. nextRawIndex = rawIndex; // Next a is this b
  28456. }
  28457. }
  28458. newIndices[sampledIndex++] = nextRawIndex;
  28459. currentRawIndex = nextRawIndex; // This a is the next a (chosen b)
  28460. } // First frame use the last data.
  28461. newIndices[sampledIndex++] = this.getRawIndex(len - 1);
  28462. list._count = sampledIndex;
  28463. list._indices = newIndices;
  28464. list.getRawIndex = getRawIndexWithIndices;
  28465. return list;
  28466. };
  28467. /**
  28468. * Get model of one data item.
  28469. */
  28470. // TODO: Type of data item
  28471. List.prototype.getItemModel = function (idx) {
  28472. var hostModel = this.hostModel;
  28473. var dataItem = this.getRawDataItem(idx);
  28474. return new Model(dataItem, hostModel, hostModel && hostModel.ecModel);
  28475. };
  28476. /**
  28477. * Create a data differ
  28478. */
  28479. List.prototype.diff = function (otherList) {
  28480. var thisList = this;
  28481. return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) {
  28482. return getId(otherList, idx);
  28483. }, function (idx) {
  28484. return getId(thisList, idx);
  28485. });
  28486. };
  28487. /**
  28488. * Get visual property.
  28489. */
  28490. List.prototype.getVisual = function (key) {
  28491. var visual = this._visual;
  28492. return visual && visual[key];
  28493. };
  28494. List.prototype.setVisual = function (kvObj, val) {
  28495. this._visual = this._visual || {};
  28496. if (isObject$3(kvObj)) {
  28497. extend(this._visual, kvObj);
  28498. } else {
  28499. this._visual[kvObj] = val;
  28500. }
  28501. };
  28502. /**
  28503. * Get visual property of single data item
  28504. */
  28505. // eslint-disable-next-line
  28506. List.prototype.getItemVisual = function (idx, key) {
  28507. var itemVisual = this._itemVisuals[idx];
  28508. var val = itemVisual && itemVisual[key];
  28509. if (val == null) {
  28510. // Use global visual property
  28511. return this.getVisual(key);
  28512. }
  28513. return val;
  28514. };
  28515. /**
  28516. * If exists visual property of single data item
  28517. */
  28518. List.prototype.hasItemVisual = function () {
  28519. return this._itemVisuals.length > 0;
  28520. };
  28521. /**
  28522. * Make sure itemVisual property is unique
  28523. */
  28524. // TODO: use key to save visual to reduce memory.
  28525. List.prototype.ensureUniqueItemVisual = function (idx, key) {
  28526. var itemVisuals = this._itemVisuals;
  28527. var itemVisual = itemVisuals[idx];
  28528. if (!itemVisual) {
  28529. itemVisual = itemVisuals[idx] = {};
  28530. }
  28531. var val = itemVisual[key];
  28532. if (val == null) {
  28533. val = this.getVisual(key); // TODO Performance?
  28534. if (isArray(val)) {
  28535. val = val.slice();
  28536. } else if (isObject$3(val)) {
  28537. val = extend({}, val);
  28538. }
  28539. itemVisual[key] = val;
  28540. }
  28541. return val;
  28542. }; // eslint-disable-next-line
  28543. List.prototype.setItemVisual = function (idx, key, value) {
  28544. var itemVisual = this._itemVisuals[idx] || {};
  28545. this._itemVisuals[idx] = itemVisual;
  28546. if (isObject$3(key)) {
  28547. extend(itemVisual, key);
  28548. } else {
  28549. itemVisual[key] = value;
  28550. }
  28551. };
  28552. /**
  28553. * Clear itemVisuals and list visual.
  28554. */
  28555. List.prototype.clearAllVisual = function () {
  28556. this._visual = {};
  28557. this._itemVisuals = [];
  28558. };
  28559. List.prototype.setLayout = function (key, val) {
  28560. if (isObject$3(key)) {
  28561. for (var name_1 in key) {
  28562. if (key.hasOwnProperty(name_1)) {
  28563. this.setLayout(name_1, key[name_1]);
  28564. }
  28565. }
  28566. return;
  28567. }
  28568. this._layout[key] = val;
  28569. };
  28570. /**
  28571. * Get layout property.
  28572. */
  28573. List.prototype.getLayout = function (key) {
  28574. return this._layout[key];
  28575. };
  28576. /**
  28577. * Get layout of single data item
  28578. */
  28579. List.prototype.getItemLayout = function (idx) {
  28580. return this._itemLayouts[idx];
  28581. };
  28582. /**
  28583. * Set layout of single data item
  28584. */
  28585. List.prototype.setItemLayout = function (idx, layout, merge) {
  28586. this._itemLayouts[idx] = merge ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  28587. };
  28588. /**
  28589. * Clear all layout of single data item
  28590. */
  28591. List.prototype.clearItemLayouts = function () {
  28592. this._itemLayouts.length = 0;
  28593. };
  28594. /**
  28595. * Set graphic element relative to data. It can be set as null
  28596. */
  28597. List.prototype.setItemGraphicEl = function (idx, el) {
  28598. var hostModel = this.hostModel;
  28599. if (el) {
  28600. var ecData = getECData(el); // Add data index and series index for indexing the data by element
  28601. // Useful in tooltip
  28602. ecData.dataIndex = idx;
  28603. ecData.dataType = this.dataType;
  28604. ecData.seriesIndex = hostModel && hostModel.seriesIndex; // TODO: not store dataIndex on children.
  28605. if (el.type === 'group') {
  28606. el.traverse(setItemDataAndSeriesIndex, el);
  28607. }
  28608. }
  28609. this._graphicEls[idx] = el;
  28610. };
  28611. List.prototype.getItemGraphicEl = function (idx) {
  28612. return this._graphicEls[idx];
  28613. };
  28614. List.prototype.eachItemGraphicEl = function (cb, context) {
  28615. each(this._graphicEls, function (el, idx) {
  28616. if (el) {
  28617. cb && cb.call(context, el, idx);
  28618. }
  28619. });
  28620. };
  28621. /**
  28622. * Shallow clone a new list except visual and layout properties, and graph elements.
  28623. * New list only change the indices.
  28624. */
  28625. List.prototype.cloneShallow = function (list) {
  28626. if (!list) {
  28627. var dimensionInfoList = map$1(this.dimensions, this.getDimensionInfo, this);
  28628. list = new List(dimensionInfoList, this.hostModel);
  28629. } // FIXME
  28630. list._storage = this._storage;
  28631. list._storageArr = this._storageArr;
  28632. transferProperties(list, this); // Clone will not change the data extent and indices
  28633. if (this._indices) {
  28634. var Ctor = this._indices.constructor;
  28635. if (Ctor === Array) {
  28636. var thisCount = this._indices.length;
  28637. list._indices = new Ctor(thisCount);
  28638. for (var i = 0; i < thisCount; i++) {
  28639. list._indices[i] = this._indices[i];
  28640. }
  28641. } else {
  28642. list._indices = new Ctor(this._indices);
  28643. }
  28644. } else {
  28645. list._indices = null;
  28646. }
  28647. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  28648. return list;
  28649. };
  28650. /**
  28651. * Wrap some method to add more feature
  28652. */
  28653. List.prototype.wrapMethod = function (methodName, injectFunction) {
  28654. var originalMethod = this[methodName];
  28655. if (typeof originalMethod !== 'function') {
  28656. return;
  28657. }
  28658. this.__wrappedMethods = this.__wrappedMethods || [];
  28659. this.__wrappedMethods.push(methodName);
  28660. this[methodName] = function () {
  28661. var res = originalMethod.apply(this, arguments);
  28662. return injectFunction.apply(this, [res].concat(slice(arguments)));
  28663. };
  28664. }; // ----------------------------------------------------------
  28665. // A work around for internal method visiting private member.
  28666. // ----------------------------------------------------------
  28667. List.internalField = function () {
  28668. defaultDimValueGetters = {
  28669. arrayRows: getDimValueSimply,
  28670. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  28671. return parseDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  28672. },
  28673. keyedColumns: getDimValueSimply,
  28674. original: function (dataItem, dimName, dataIndex, dimIndex) {
  28675. // Performance sensitive, do not use modelUtil.getDataItemValue.
  28676. // If dataItem is an plain object with no value field, the let `value`
  28677. // will be assigned with the object, but it will be tread correctly
  28678. // in the `convertValue`.
  28679. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 }
  28680. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  28681. this.hasItemOption = true;
  28682. }
  28683. return parseDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  28684. : value, this._dimensionInfos[dimName]);
  28685. },
  28686. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  28687. return dataItem[dimIndex];
  28688. }
  28689. };
  28690. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  28691. return parseDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  28692. }
  28693. prepareInvertedIndex = function (list) {
  28694. var invertedIndicesMap = list._invertedIndicesMap;
  28695. each(invertedIndicesMap, function (invertedIndices, dim) {
  28696. var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  28697. var ordinalMeta = dimInfo.ordinalMeta;
  28698. if (ordinalMeta) {
  28699. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  28700. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  28701. for (var i = 0; i < invertedIndices.length; i++) {
  28702. invertedIndices[i] = INDEX_NOT_FOUND;
  28703. }
  28704. for (var i = 0; i < list._count; i++) {
  28705. // Only support the case that all values are distinct.
  28706. invertedIndices[list.get(dim, i)] = i;
  28707. }
  28708. }
  28709. });
  28710. };
  28711. getIdNameFromStore = function (list, dimIdx, ordinalMeta, rawIndex) {
  28712. var val;
  28713. var chunk = list._storageArr[dimIdx];
  28714. if (chunk) {
  28715. val = chunk[rawIndex];
  28716. if (ordinalMeta && ordinalMeta.categories.length) {
  28717. val = ordinalMeta.categories[val];
  28718. }
  28719. }
  28720. return convertOptionIdName(val, null);
  28721. };
  28722. getIndicesCtor = function (list) {
  28723. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  28724. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  28725. };
  28726. prepareStorage = function (storage, dimInfo, end, append) {
  28727. var DataCtor = dataCtors[dimInfo.type];
  28728. var dim = dimInfo.name;
  28729. if (append) {
  28730. var oldStore = storage[dim];
  28731. var oldLen = oldStore && oldStore.length;
  28732. if (!(oldLen === end)) {
  28733. var newStore = new DataCtor(end); // The cost of the copy is probably inconsiderable
  28734. // within the initial chunkSize.
  28735. for (var j = 0; j < oldLen; j++) {
  28736. newStore[j] = oldStore[j];
  28737. }
  28738. storage[dim] = newStore;
  28739. }
  28740. } else {
  28741. storage[dim] = new DataCtor(end);
  28742. }
  28743. };
  28744. getRawIndexWithoutIndices = function (idx) {
  28745. return idx;
  28746. };
  28747. getRawIndexWithIndices = function (idx) {
  28748. if (idx < this._count && idx >= 0) {
  28749. return this._indices[idx];
  28750. }
  28751. return -1;
  28752. };
  28753. /**
  28754. * @see the comment of `List['getId']`.
  28755. */
  28756. getId = function (list, rawIndex) {
  28757. var id = list._idList[rawIndex];
  28758. if (id == null && list._idDimIdx != null) {
  28759. id = getIdNameFromStore(list, list._idDimIdx, list._idOrdinalMeta, rawIndex);
  28760. }
  28761. if (id == null) {
  28762. id = ID_PREFIX + rawIndex;
  28763. }
  28764. return id;
  28765. };
  28766. normalizeDimensions = function (dimensions) {
  28767. if (!isArray(dimensions)) {
  28768. dimensions = dimensions != null ? [dimensions] : [];
  28769. }
  28770. return dimensions;
  28771. };
  28772. validateDimensions = function (list, dims) {
  28773. for (var i = 0; i < dims.length; i++) {
  28774. // stroage may be empty when no data, so use
  28775. // dimensionInfos to check.
  28776. if (!list._dimensionInfos[dims[i]]) {
  28777. console.error('Unkown dimension ' + dims[i]);
  28778. }
  28779. }
  28780. }; // Data in excludeDimensions is copied, otherwise transfered.
  28781. cloneListForMapAndSample = function (original, excludeDimensions) {
  28782. var allDimensions = original.dimensions;
  28783. var list = new List(map$1(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  28784. transferProperties(list, original);
  28785. var storage = list._storage = {};
  28786. var originalStorage = original._storage;
  28787. var storageArr = list._storageArr = []; // Init storage
  28788. for (var i = 0; i < allDimensions.length; i++) {
  28789. var dim = allDimensions[i];
  28790. if (originalStorage[dim]) {
  28791. // Notice that we do not reset invertedIndicesMap here, becuase
  28792. // there is no scenario of mapping or sampling ordinal dimension.
  28793. if (indexOf(excludeDimensions, dim) >= 0) {
  28794. storage[dim] = cloneChunk(originalStorage[dim]);
  28795. list._rawExtent[dim] = getInitialExtent();
  28796. list._extent[dim] = null;
  28797. } else {
  28798. // Direct reference for other dimensions
  28799. storage[dim] = originalStorage[dim];
  28800. }
  28801. storageArr.push(storage[dim]);
  28802. }
  28803. }
  28804. return list;
  28805. };
  28806. function cloneChunk(originalChunk) {
  28807. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  28808. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  28809. }
  28810. getInitialExtent = function () {
  28811. return [Infinity, -Infinity];
  28812. };
  28813. setItemDataAndSeriesIndex = function (child) {
  28814. var childECData = getECData(child);
  28815. var thisECData = getECData(this);
  28816. childECData.seriesIndex = thisECData.seriesIndex;
  28817. childECData.dataIndex = thisECData.dataIndex;
  28818. childECData.dataType = thisECData.dataType;
  28819. };
  28820. transferProperties = function (target, source) {
  28821. each(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  28822. if (source.hasOwnProperty(propName)) {
  28823. target[propName] = source[propName];
  28824. }
  28825. });
  28826. target.__wrappedMethods = source.__wrappedMethods;
  28827. each(CLONE_PROPERTIES, function (propName) {
  28828. target[propName] = clone(source[propName]);
  28829. });
  28830. target._calculationInfo = extend({}, source._calculationInfo);
  28831. };
  28832. makeIdFromName = function (list, idx) {
  28833. var nameList = list._nameList;
  28834. var idList = list._idList;
  28835. var nameDimIdx = list._nameDimIdx;
  28836. var idDimIdx = list._idDimIdx;
  28837. var name = nameList[idx];
  28838. var id = idList[idx];
  28839. if (name == null && nameDimIdx != null) {
  28840. nameList[idx] = name = getIdNameFromStore(list, nameDimIdx, list._nameOrdinalMeta, idx);
  28841. }
  28842. if (id == null && idDimIdx != null) {
  28843. idList[idx] = id = getIdNameFromStore(list, idDimIdx, list._idOrdinalMeta, idx);
  28844. }
  28845. if (id == null && name != null) {
  28846. var nameRepeatCount = list._nameRepeatCount;
  28847. var nmCnt = nameRepeatCount[name] = (nameRepeatCount[name] || 0) + 1;
  28848. id = name;
  28849. if (nmCnt > 1) {
  28850. id += '__ec__' + nmCnt;
  28851. }
  28852. idList[idx] = id;
  28853. }
  28854. };
  28855. }();
  28856. return List;
  28857. }();
  28858. /**
  28859. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  28860. *
  28861. * This method builds the relationship between:
  28862. * + "what the coord sys or series requires (see `sysDims`)",
  28863. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  28864. * + "what the data source provids (see `source`)".
  28865. *
  28866. * Some guess strategy will be adapted if user does not define something.
  28867. * If no 'value' dimension specified, the first no-named dimension will be
  28868. * named as 'value'.
  28869. *
  28870. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  28871. * provides not only dim template, but also default order.
  28872. * properties: 'name', 'type', 'displayName'.
  28873. * `name` of each item provides default coord name.
  28874. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  28875. * provide dims count that the sysDim required.
  28876. * [{ordinalMeta}] can be specified.
  28877. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  28878. * @param {Object} [opt]
  28879. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  28880. * For example: ['asdf', {name, type}, ...].
  28881. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  28882. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  28883. * If not specified, auto find the next available data dim.
  28884. * param source {module:data/Source}
  28885. * param dimCount {number}
  28886. * return {Object} encode Never be `null/undefined`.
  28887. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  28888. * If not specified, extra dim names will be:
  28889. * 'value', 'value0', 'value1', ...
  28890. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  28891. * If `generateCoordCount` specified, the generated dim names will be:
  28892. * `generateCoord` + 0, `generateCoord` + 1, ...
  28893. * can be Infinity, indicate that use all of the remain columns.
  28894. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  28895. * @return {Array.<module:data/DataDimensionInfo>}
  28896. */
  28897. function completeDimensions(sysDims, source, opt) {
  28898. if (!isSourceInstance(source)) {
  28899. source = createSourceFromSeriesDataOption(source);
  28900. }
  28901. opt = opt || {};
  28902. sysDims = (sysDims || []).slice();
  28903. var dimsDef = (opt.dimsDef || []).slice();
  28904. var dataDimNameMap = createHashMap();
  28905. var coordDimNameMap = createHashMap(); // let valueCandidate;
  28906. var result = [];
  28907. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result.
  28908. for (var i = 0; i < dimCount; i++) {
  28909. var dimDefItemRaw = dimsDef[i];
  28910. var dimDefItem = dimsDef[i] = extend({}, isObject(dimDefItemRaw) ? dimDefItemRaw : {
  28911. name: dimDefItemRaw
  28912. });
  28913. var userDimName = dimDefItem.name;
  28914. var resultItem = result[i] = new DataDimensionInfo(); // Name will be applied later for avoiding duplication.
  28915. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  28916. // Only if `series.dimensions` is defined in option
  28917. // displayName, will be set, and dimension will be diplayed vertically in
  28918. // tooltip by default.
  28919. resultItem.name = resultItem.displayName = userDimName;
  28920. dataDimNameMap.set(userDimName, i);
  28921. }
  28922. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  28923. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  28924. }
  28925. var encodeDef = opt.encodeDef;
  28926. if (!encodeDef && opt.encodeDefaulter) {
  28927. encodeDef = opt.encodeDefaulter(source, dimCount);
  28928. }
  28929. var encodeDefMap = createHashMap(encodeDef); // Set `coordDim` and `coordDimIndex` by `encodeDefMap` and normalize `encodeDefMap`.
  28930. encodeDefMap.each(function (dataDimsRaw, coordDim) {
  28931. var dataDims = normalizeToArray(dataDimsRaw).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  28932. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  28933. // this case.
  28934. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  28935. encodeDefMap.set(coordDim, false);
  28936. return;
  28937. }
  28938. var validDataDims = encodeDefMap.set(coordDim, []);
  28939. each(dataDims, function (resultDimIdxOrName, idx) {
  28940. // The input resultDimIdx can be dim name or index.
  28941. var resultDimIdx = isString(resultDimIdxOrName) ? dataDimNameMap.get(resultDimIdxOrName) : resultDimIdxOrName;
  28942. if (resultDimIdx != null && resultDimIdx < dimCount) {
  28943. validDataDims[idx] = resultDimIdx;
  28944. applyDim(result[resultDimIdx], coordDim, idx);
  28945. }
  28946. });
  28947. }); // Apply templetes and default order from `sysDims`.
  28948. var availDimIdx = 0;
  28949. each(sysDims, function (sysDimItemRaw) {
  28950. var coordDim;
  28951. var sysDimItemDimsDef;
  28952. var sysDimItemOtherDims;
  28953. var sysDimItem;
  28954. if (isString(sysDimItemRaw)) {
  28955. coordDim = sysDimItemRaw;
  28956. sysDimItem = {};
  28957. } else {
  28958. sysDimItem = sysDimItemRaw;
  28959. coordDim = sysDimItem.name;
  28960. var ordinalMeta = sysDimItem.ordinalMeta;
  28961. sysDimItem.ordinalMeta = null;
  28962. sysDimItem = clone(sysDimItem);
  28963. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  28964. sysDimItemDimsDef = sysDimItem.dimsDef;
  28965. sysDimItemOtherDims = sysDimItem.otherDims;
  28966. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  28967. }
  28968. var dataDims = encodeDefMap.get(coordDim); // negative resultDimIdx means no need to mapping.
  28969. if (dataDims === false) {
  28970. return;
  28971. }
  28972. dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  28973. if (!dataDims.length) {
  28974. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  28975. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  28976. availDimIdx++;
  28977. }
  28978. availDimIdx < result.length && dataDims.push(availDimIdx++);
  28979. }
  28980. } // Apply templates.
  28981. each(dataDims, function (resultDimIdx, coordDimIndex) {
  28982. var resultItem = result[resultDimIdx];
  28983. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  28984. if (resultItem.name == null && sysDimItemDimsDef) {
  28985. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  28986. !isObject(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  28987. name: sysDimItemDimsDefItem
  28988. });
  28989. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  28990. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  28991. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  28992. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  28993. });
  28994. });
  28995. function applyDim(resultItem, coordDim, coordDimIndex) {
  28996. if (VISUAL_DIMENSIONS.get(coordDim) != null) {
  28997. resultItem.otherDims[coordDim] = coordDimIndex;
  28998. } else {
  28999. resultItem.coordDim = coordDim;
  29000. resultItem.coordDimIndex = coordDimIndex;
  29001. coordDimNameMap.set(coordDim, true);
  29002. }
  29003. } // Make sure the first extra dim is 'value'.
  29004. var generateCoord = opt.generateCoord;
  29005. var generateCoordCount = opt.generateCoordCount;
  29006. var fromZero = generateCoordCount != null;
  29007. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  29008. var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props.
  29009. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  29010. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  29011. var coordDim = resultItem.coordDim;
  29012. if (coordDim == null) {
  29013. resultItem.coordDim = genName(extra, coordDimNameMap, fromZero);
  29014. resultItem.coordDimIndex = 0;
  29015. if (!generateCoord || generateCoordCount <= 0) {
  29016. resultItem.isExtraCoord = true;
  29017. }
  29018. generateCoordCount--;
  29019. }
  29020. resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap, false));
  29021. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx) === BE_ORDINAL.Must // Consider the case:
  29022. // {
  29023. // dataset: {source: [
  29024. // ['2001', 123],
  29025. // ['2002', 456],
  29026. // ...
  29027. // ['The others', 987],
  29028. // ]},
  29029. // series: {type: 'pie'}
  29030. // }
  29031. // The first colum should better be treated as a "ordinal" although it
  29032. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  29033. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  29034. resultItem.type = 'ordinal';
  29035. }
  29036. }
  29037. return result;
  29038. } // ??? TODO
  29039. // Originally detect dimCount by data[0]. Should we
  29040. // optimize it to only by sysDims and dimensions and encode.
  29041. // So only necessary dims will be initialized.
  29042. // But
  29043. // (1) custom series should be considered. where other dims
  29044. // may be visited.
  29045. // (2) sometimes user need to calcualte bubble size or use visualMap
  29046. // on other dimensions besides coordSys needed.
  29047. // So, dims that is not used by system, should be shared in storage?
  29048. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  29049. // Note that the result dimCount should not small than columns count
  29050. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  29051. var dimCount = Math.max(source.dimensionsDetectedCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  29052. each(sysDims, function (sysDimItem) {
  29053. var sysDimItemDimsDef;
  29054. if (isObject(sysDimItem) && (sysDimItemDimsDef = sysDimItem.dimsDef)) {
  29055. dimCount = Math.max(dimCount, sysDimItemDimsDef.length);
  29056. }
  29057. });
  29058. return dimCount;
  29059. }
  29060. function genName(name, map, fromZero) {
  29061. if (fromZero || map.get(name) != null) {
  29062. var i = 0;
  29063. while (map.get(name + i) != null) {
  29064. i++;
  29065. }
  29066. name += i;
  29067. }
  29068. map.set(name, true);
  29069. return name;
  29070. }
  29071. /**
  29072. * @param opt.coordDimensions
  29073. * @param opt.dimensionsDefine By default `source.dimensionsDefine` Overwrite source define.
  29074. * @param opt.encodeDefine By default `source.encodeDefine` Overwrite source define.
  29075. * @param opt.encodeDefaulter Make default encode if user not specified.
  29076. */
  29077. function createDimensions( // TODO: TYPE completeDimensions type
  29078. source, opt) {
  29079. opt = opt || {};
  29080. return completeDimensions(opt.coordDimensions || [], source, {
  29081. // FIXME:TS detect whether source then call `.dimensionsDefine` and `.encodeDefine`?
  29082. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  29083. encodeDef: opt.encodeDefine || source.encodeDefine,
  29084. dimCount: opt.dimensionsCount,
  29085. encodeDefaulter: opt.encodeDefaulter,
  29086. generateCoord: opt.generateCoord,
  29087. generateCoordCount: opt.generateCoordCount
  29088. });
  29089. }
  29090. /**
  29091. * @class
  29092. * For example:
  29093. * {
  29094. * coordSysName: 'cartesian2d',
  29095. * coordSysDims: ['x', 'y', ...],
  29096. * axisMap: HashMap({
  29097. * x: xAxisModel,
  29098. * y: yAxisModel
  29099. * }),
  29100. * categoryAxisMap: HashMap({
  29101. * x: xAxisModel,
  29102. * y: undefined
  29103. * }),
  29104. * // The index of the first category axis in `coordSysDims`.
  29105. * // `null/undefined` means no category axis exists.
  29106. * firstCategoryDimIndex: 1,
  29107. * // To replace user specified encode.
  29108. * }
  29109. */
  29110. var CoordSysInfo =
  29111. /** @class */
  29112. function () {
  29113. function CoordSysInfo(coordSysName) {
  29114. this.coordSysDims = [];
  29115. this.axisMap = createHashMap();
  29116. this.categoryAxisMap = createHashMap();
  29117. this.coordSysName = coordSysName;
  29118. }
  29119. return CoordSysInfo;
  29120. }();
  29121. function getCoordSysInfoBySeries(seriesModel) {
  29122. var coordSysName = seriesModel.get('coordinateSystem');
  29123. var result = new CoordSysInfo(coordSysName);
  29124. var fetch = fetchers[coordSysName];
  29125. if (fetch) {
  29126. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  29127. return result;
  29128. }
  29129. }
  29130. var fetchers = {
  29131. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  29132. var xAxisModel = seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  29133. var yAxisModel = seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  29134. if ("development" !== 'production') {
  29135. if (!xAxisModel) {
  29136. throw new Error('xAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0) + '" not found');
  29137. }
  29138. if (!yAxisModel) {
  29139. throw new Error('yAxis "' + retrieve(seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0) + '" not found');
  29140. }
  29141. }
  29142. result.coordSysDims = ['x', 'y'];
  29143. axisMap.set('x', xAxisModel);
  29144. axisMap.set('y', yAxisModel);
  29145. if (isCategory(xAxisModel)) {
  29146. categoryAxisMap.set('x', xAxisModel);
  29147. result.firstCategoryDimIndex = 0;
  29148. }
  29149. if (isCategory(yAxisModel)) {
  29150. categoryAxisMap.set('y', yAxisModel);
  29151. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29152. }
  29153. },
  29154. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  29155. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  29156. if ("development" !== 'production') {
  29157. if (!singleAxisModel) {
  29158. throw new Error('singleAxis should be specified.');
  29159. }
  29160. }
  29161. result.coordSysDims = ['single'];
  29162. axisMap.set('single', singleAxisModel);
  29163. if (isCategory(singleAxisModel)) {
  29164. categoryAxisMap.set('single', singleAxisModel);
  29165. result.firstCategoryDimIndex = 0;
  29166. }
  29167. },
  29168. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  29169. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  29170. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  29171. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  29172. if ("development" !== 'production') {
  29173. if (!angleAxisModel) {
  29174. throw new Error('angleAxis option not found');
  29175. }
  29176. if (!radiusAxisModel) {
  29177. throw new Error('radiusAxis option not found');
  29178. }
  29179. }
  29180. result.coordSysDims = ['radius', 'angle'];
  29181. axisMap.set('radius', radiusAxisModel);
  29182. axisMap.set('angle', angleAxisModel);
  29183. if (isCategory(radiusAxisModel)) {
  29184. categoryAxisMap.set('radius', radiusAxisModel);
  29185. result.firstCategoryDimIndex = 0;
  29186. }
  29187. if (isCategory(angleAxisModel)) {
  29188. categoryAxisMap.set('angle', angleAxisModel);
  29189. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  29190. }
  29191. },
  29192. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  29193. result.coordSysDims = ['lng', 'lat'];
  29194. },
  29195. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  29196. var ecModel = seriesModel.ecModel;
  29197. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  29198. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  29199. each(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  29200. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  29201. var axisDim = coordSysDims[index];
  29202. axisMap.set(axisDim, axisModel);
  29203. if (isCategory(axisModel)) {
  29204. categoryAxisMap.set(axisDim, axisModel);
  29205. if (result.firstCategoryDimIndex == null) {
  29206. result.firstCategoryDimIndex = index;
  29207. }
  29208. }
  29209. });
  29210. }
  29211. };
  29212. function isCategory(axisModel) {
  29213. return axisModel.get('type') === 'category';
  29214. }
  29215. /**
  29216. * Note that it is too complicated to support 3d stack by value
  29217. * (have to create two-dimension inverted index), so in 3d case
  29218. * we just support that stacked by index.
  29219. *
  29220. * @param seriesModel
  29221. * @param dimensionInfoList The same as the input of <module:echarts/data/List>.
  29222. * The input dimensionInfoList will be modified.
  29223. * @param opt
  29224. * @param opt.stackedCoordDimension Specify a coord dimension if needed.
  29225. * @param opt.byIndex=false
  29226. * @return calculationInfo
  29227. * {
  29228. * stackedDimension: string
  29229. * stackedByDimension: string
  29230. * isStackedByIndex: boolean
  29231. * stackedOverDimension: string
  29232. * stackResultDimension: string
  29233. * }
  29234. */
  29235. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  29236. opt = opt || {};
  29237. var byIndex = opt.byIndex;
  29238. var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack.
  29239. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  29240. var stackedByDimInfo;
  29241. var stackedDimInfo;
  29242. var stackResultDimension;
  29243. var stackedOverDimension;
  29244. each(dimensionInfoList, function (dimensionInfo, index) {
  29245. if (isString(dimensionInfo)) {
  29246. dimensionInfoList[index] = dimensionInfo = {
  29247. name: dimensionInfo
  29248. };
  29249. }
  29250. if (mayStack && !dimensionInfo.isExtraCoord) {
  29251. // Find the first ordinal dimension as the stackedByDimInfo.
  29252. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  29253. stackedByDimInfo = dimensionInfo;
  29254. } // Find the first stackable dimension as the stackedDimInfo.
  29255. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  29256. stackedDimInfo = dimensionInfo;
  29257. }
  29258. }
  29259. });
  29260. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  29261. // Compatible with previous design, value axis (time axis) only stack by index.
  29262. // It may make sense if the user provides elaborately constructed data.
  29263. byIndex = true;
  29264. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  29265. // That put stack logic in List is for using conveniently in echarts extensions, but it
  29266. // might not be a good way.
  29267. if (stackedDimInfo) {
  29268. // Use a weird name that not duplicated with other names.
  29269. stackResultDimension = '__\0ecstackresult';
  29270. stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value.
  29271. if (stackedByDimInfo) {
  29272. stackedByDimInfo.createInvertedIndices = true;
  29273. }
  29274. var stackedDimCoordDim_1 = stackedDimInfo.coordDim;
  29275. var stackedDimType = stackedDimInfo.type;
  29276. var stackedDimCoordIndex_1 = 0;
  29277. each(dimensionInfoList, function (dimensionInfo) {
  29278. if (dimensionInfo.coordDim === stackedDimCoordDim_1) {
  29279. stackedDimCoordIndex_1++;
  29280. }
  29281. });
  29282. dimensionInfoList.push({
  29283. name: stackResultDimension,
  29284. coordDim: stackedDimCoordDim_1,
  29285. coordDimIndex: stackedDimCoordIndex_1,
  29286. type: stackedDimType,
  29287. isExtraCoord: true,
  29288. isCalculationCoord: true
  29289. });
  29290. stackedDimCoordIndex_1++;
  29291. dimensionInfoList.push({
  29292. name: stackedOverDimension,
  29293. // This dimension contains stack base (generally, 0), so do not set it as
  29294. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  29295. coordDim: stackedOverDimension,
  29296. coordDimIndex: stackedDimCoordIndex_1,
  29297. type: stackedDimType,
  29298. isExtraCoord: true,
  29299. isCalculationCoord: true
  29300. });
  29301. }
  29302. return {
  29303. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  29304. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  29305. isStackedByIndex: byIndex,
  29306. stackedOverDimension: stackedOverDimension,
  29307. stackResultDimension: stackResultDimension
  29308. };
  29309. }
  29310. function isDimensionStacked(data, stackedDim
  29311. /*, stackedByDim*/
  29312. ) {
  29313. // Each single series only maps to one pair of axis. So we do not need to
  29314. // check stackByDim, whatever stacked by a dimension or stacked by index.
  29315. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); // && (
  29316. // stackedByDim != null
  29317. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  29318. // : data.getCalculationInfo('isStackedByIndex')
  29319. // );
  29320. }
  29321. function getStackedDimension(data, targetDim) {
  29322. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  29323. }
  29324. function createListFromArray(source, seriesModel, opt) {
  29325. opt = opt || {};
  29326. if (!isSourceInstance(source)) {
  29327. source = createSourceFromSeriesDataOption(source);
  29328. }
  29329. var coordSysName = seriesModel.get('coordinateSystem');
  29330. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  29331. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  29332. var coordSysDimDefs;
  29333. if (coordSysInfo && coordSysInfo.coordSysDims) {
  29334. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  29335. var dimInfo = {
  29336. name: dim
  29337. };
  29338. var axisModel = coordSysInfo.axisMap.get(dim);
  29339. if (axisModel) {
  29340. var axisType = axisModel.get('type');
  29341. dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType);
  29342. }
  29343. return dimInfo;
  29344. });
  29345. }
  29346. if (!coordSysDimDefs) {
  29347. // Get dimensions from registered coordinate system
  29348. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  29349. }
  29350. var useEncodeDefaulter = opt.useEncodeDefaulter;
  29351. var dimInfoList = createDimensions(source, {
  29352. coordDimensions: coordSysDimDefs,
  29353. generateCoord: opt.generateCoord,
  29354. encodeDefaulter: isFunction(useEncodeDefaulter) ? useEncodeDefaulter : useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null
  29355. });
  29356. var firstCategoryDimIndex;
  29357. var hasNameEncode;
  29358. coordSysInfo && each(dimInfoList, function (dimInfo, dimIndex) {
  29359. var coordDim = dimInfo.coordDim;
  29360. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  29361. if (categoryAxisModel) {
  29362. if (firstCategoryDimIndex == null) {
  29363. firstCategoryDimIndex = dimIndex;
  29364. }
  29365. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  29366. if (opt.createInvertedIndices) {
  29367. dimInfo.createInvertedIndices = true;
  29368. }
  29369. }
  29370. if (dimInfo.otherDims.itemName != null) {
  29371. hasNameEncode = true;
  29372. }
  29373. });
  29374. if (!hasNameEncode && firstCategoryDimIndex != null) {
  29375. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  29376. }
  29377. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  29378. var list = new List(dimInfoList, seriesModel);
  29379. list.setCalculationInfo(stackCalculationInfo);
  29380. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  29381. // Use dataIndex as ordinal value in categoryAxis
  29382. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  29383. } : null;
  29384. list.hasItemOption = false;
  29385. list.initData(source, null, dimValueGetter);
  29386. return list;
  29387. }
  29388. function isNeedCompleteOrdinalData(source) {
  29389. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  29390. var sampleItem = firstDataNotNull(source.data || []);
  29391. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  29392. }
  29393. }
  29394. function firstDataNotNull(data) {
  29395. var i = 0;
  29396. while (i < data.length && data[i] == null) {
  29397. i++;
  29398. }
  29399. return data[i];
  29400. }
  29401. var Scale =
  29402. /** @class */
  29403. function () {
  29404. function Scale(setting) {
  29405. this._setting = setting || {};
  29406. this._extent = [Infinity, -Infinity];
  29407. }
  29408. Scale.prototype.getSetting = function (name) {
  29409. return this._setting[name];
  29410. };
  29411. /**
  29412. * Set extent from data
  29413. */
  29414. Scale.prototype.unionExtent = function (other) {
  29415. var extent = this._extent;
  29416. other[0] < extent[0] && (extent[0] = other[0]);
  29417. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  29418. // this.setExtent(extent[0], extent[1]);
  29419. };
  29420. /**
  29421. * Set extent from data
  29422. */
  29423. Scale.prototype.unionExtentFromData = function (data, dim) {
  29424. this.unionExtent(data.getApproximateExtent(dim));
  29425. };
  29426. /**
  29427. * Get extent
  29428. *
  29429. * Extent is always in increase order.
  29430. */
  29431. Scale.prototype.getExtent = function () {
  29432. return this._extent.slice();
  29433. };
  29434. /**
  29435. * Set extent
  29436. */
  29437. Scale.prototype.setExtent = function (start, end) {
  29438. var thisExtent = this._extent;
  29439. if (!isNaN(start)) {
  29440. thisExtent[0] = start;
  29441. }
  29442. if (!isNaN(end)) {
  29443. thisExtent[1] = end;
  29444. }
  29445. };
  29446. /**
  29447. * If value is in extent range
  29448. */
  29449. Scale.prototype.isInExtentRange = function (value) {
  29450. return this._extent[0] <= value && this._extent[1] >= value;
  29451. };
  29452. /**
  29453. * When axis extent depends on data and no data exists,
  29454. * axis ticks should not be drawn, which is named 'blank'.
  29455. */
  29456. Scale.prototype.isBlank = function () {
  29457. return this._isBlank;
  29458. };
  29459. /**
  29460. * When axis extent depends on data and no data exists,
  29461. * axis ticks should not be drawn, which is named 'blank'.
  29462. */
  29463. Scale.prototype.setBlank = function (isBlank) {
  29464. this._isBlank = isBlank;
  29465. };
  29466. return Scale;
  29467. }();
  29468. enableClassManagement(Scale);
  29469. var OrdinalMeta =
  29470. /** @class */
  29471. function () {
  29472. function OrdinalMeta(opt) {
  29473. this.categories = opt.categories || [];
  29474. this._needCollect = opt.needCollect;
  29475. this._deduplication = opt.deduplication;
  29476. }
  29477. OrdinalMeta.createByAxisModel = function (axisModel) {
  29478. var option = axisModel.option;
  29479. var data = option.data;
  29480. var categories = data && map(data, getName);
  29481. return new OrdinalMeta({
  29482. categories: categories,
  29483. needCollect: !categories,
  29484. // deduplication is default in axis.
  29485. deduplication: option.dedplication !== false
  29486. });
  29487. };
  29488. OrdinalMeta.prototype.getOrdinal = function (category) {
  29489. // @ts-ignore
  29490. return this._getOrCreateMap().get(category);
  29491. };
  29492. /**
  29493. * @return The ordinal. If not found, return NaN.
  29494. */
  29495. OrdinalMeta.prototype.parseAndCollect = function (category) {
  29496. var index;
  29497. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  29498. // This feature is only supported when !needCollect, because we should
  29499. // consider a common case: a value is 2017, which is a number but is
  29500. // expected to be tread as a category. This case usually happen in dataset,
  29501. // where it happent to be no need of the index feature.
  29502. if (typeof category !== 'string' && !needCollect) {
  29503. return category;
  29504. } // Optimize for the scenario:
  29505. // category is ['2012-01-01', '2012-01-02', ...], where the input
  29506. // data has been ensured not duplicate and is large data.
  29507. // Notice, if a dataset dimension provide categroies, usually echarts
  29508. // should remove duplication except user tell echarts dont do that
  29509. // (set axis.deduplication = false), because echarts do not know whether
  29510. // the values in the category dimension has duplication (consider the
  29511. // parallel-aqi example)
  29512. if (needCollect && !this._deduplication) {
  29513. index = this.categories.length;
  29514. this.categories[index] = category;
  29515. return index;
  29516. }
  29517. var map = this._getOrCreateMap(); // @ts-ignore
  29518. index = map.get(category);
  29519. if (index == null) {
  29520. if (needCollect) {
  29521. index = this.categories.length;
  29522. this.categories[index] = category; // @ts-ignore
  29523. map.set(category, index);
  29524. } else {
  29525. index = NaN;
  29526. }
  29527. }
  29528. return index;
  29529. }; // Consider big data, do not create map until needed.
  29530. OrdinalMeta.prototype._getOrCreateMap = function () {
  29531. return this._map || (this._map = createHashMap(this.categories));
  29532. };
  29533. return OrdinalMeta;
  29534. }();
  29535. function getName(obj) {
  29536. if (isObject(obj) && obj.value != null) {
  29537. return obj.value;
  29538. } else {
  29539. return obj + '';
  29540. }
  29541. }
  29542. var roundNumber = round;
  29543. /**
  29544. * @param extent Both extent[0] and extent[1] should be valid number.
  29545. * Should be extent[0] < extent[1].
  29546. * @param splitNumber splitNumber should be >= 1.
  29547. */
  29548. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  29549. var result = {};
  29550. var span = extent[1] - extent[0];
  29551. var interval = result.interval = nice(span / splitNumber, true);
  29552. if (minInterval != null && interval < minInterval) {
  29553. interval = result.interval = minInterval;
  29554. }
  29555. if (maxInterval != null && interval > maxInterval) {
  29556. interval = result.interval = maxInterval;
  29557. } // Tow more digital for tick.
  29558. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  29559. var niceTickExtent = result.niceTickExtent = [roundNumber(Math.ceil(extent[0] / interval) * interval, precision), roundNumber(Math.floor(extent[1] / interval) * interval, precision)];
  29560. fixExtent(niceTickExtent, extent);
  29561. return result;
  29562. }
  29563. /**
  29564. * @return interval precision
  29565. */
  29566. function getIntervalPrecision(interval) {
  29567. // Tow more digital for tick.
  29568. return getPrecisionSafe(interval) + 2;
  29569. }
  29570. function clamp(niceTickExtent, idx, extent) {
  29571. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  29572. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  29573. function fixExtent(niceTickExtent, extent) {
  29574. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  29575. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  29576. clamp(niceTickExtent, 0, extent);
  29577. clamp(niceTickExtent, 1, extent);
  29578. if (niceTickExtent[0] > niceTickExtent[1]) {
  29579. niceTickExtent[0] = niceTickExtent[1];
  29580. }
  29581. }
  29582. function contain$1(val, extent) {
  29583. return val >= extent[0] && val <= extent[1];
  29584. }
  29585. function normalize$1(val, extent) {
  29586. if (extent[1] === extent[0]) {
  29587. return 0.5;
  29588. }
  29589. return (val - extent[0]) / (extent[1] - extent[0]);
  29590. }
  29591. function scale$2(val, extent) {
  29592. return val * (extent[1] - extent[0]) + extent[0];
  29593. }
  29594. var OrdinalScale =
  29595. /** @class */
  29596. function (_super) {
  29597. __extends(OrdinalScale, _super);
  29598. function OrdinalScale(setting) {
  29599. var _this = _super.call(this, setting) || this;
  29600. _this.type = 'ordinal';
  29601. var ordinalMeta = _this.getSetting('ordinalMeta'); // Caution: Should not use instanceof, consider ec-extensions using
  29602. // import approach to get OrdinalMeta class.
  29603. if (!ordinalMeta) {
  29604. ordinalMeta = new OrdinalMeta({});
  29605. }
  29606. if (isArray(ordinalMeta)) {
  29607. ordinalMeta = new OrdinalMeta({
  29608. categories: map(ordinalMeta, function (item) {
  29609. return isObject(item) ? item.value : item;
  29610. })
  29611. });
  29612. }
  29613. _this._ordinalMeta = ordinalMeta;
  29614. _this._extent = _this.getSetting('extent') || [0, ordinalMeta.categories.length - 1];
  29615. return _this;
  29616. }
  29617. OrdinalScale.prototype.parse = function (val) {
  29618. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  29619. : Math.round(val);
  29620. };
  29621. OrdinalScale.prototype.contain = function (rank) {
  29622. rank = this.parse(rank);
  29623. return contain$1(rank, this._extent) && this._ordinalMeta.categories[rank] != null;
  29624. };
  29625. /**
  29626. * Normalize given rank or name to linear [0, 1]
  29627. * @param val raw ordinal number.
  29628. * @return normalized value in [0, 1].
  29629. */
  29630. OrdinalScale.prototype.normalize = function (val) {
  29631. val = this._getTickNumber(this.parse(val));
  29632. return normalize$1(val, this._extent);
  29633. };
  29634. /**
  29635. * @param val normalized value in [0, 1].
  29636. * @return raw ordinal number.
  29637. */
  29638. OrdinalScale.prototype.scale = function (val) {
  29639. val = Math.round(scale$2(val, this._extent));
  29640. return this.getRawOrdinalNumber(val);
  29641. };
  29642. OrdinalScale.prototype.getTicks = function () {
  29643. var ticks = [];
  29644. var extent = this._extent;
  29645. var rank = extent[0];
  29646. while (rank <= extent[1]) {
  29647. ticks.push({
  29648. value: rank
  29649. });
  29650. rank++;
  29651. }
  29652. return ticks;
  29653. };
  29654. OrdinalScale.prototype.getMinorTicks = function (splitNumber) {
  29655. // Not support.
  29656. return;
  29657. };
  29658. /**
  29659. * @see `Ordinal['_ordinalNumbersByTick']`
  29660. */
  29661. OrdinalScale.prototype.setSortInfo = function (info) {
  29662. if (info == null) {
  29663. this._ordinalNumbersByTick = this._ticksByOrdinalNumber = null;
  29664. return;
  29665. }
  29666. var infoOrdinalNumbers = info.ordinalNumbers;
  29667. var ordinalsByTick = this._ordinalNumbersByTick = [];
  29668. var ticksByOrdinal = this._ticksByOrdinalNumber = []; // Unnecessary support negative tick in `realtimeSort`.
  29669. var tickNum = 0;
  29670. var allCategoryLen = this._ordinalMeta.categories.length;
  29671. for (var len = Math.min(allCategoryLen, infoOrdinalNumbers.length); tickNum < len; ++tickNum) {
  29672. var ordinalNumber = infoOrdinalNumbers[tickNum];
  29673. ordinalsByTick[tickNum] = ordinalNumber;
  29674. ticksByOrdinal[ordinalNumber] = tickNum;
  29675. } // Handle that `series.data` only covers part of the `axis.category.data`.
  29676. var unusedOrdinal = 0;
  29677. for (; tickNum < allCategoryLen; ++tickNum) {
  29678. while (ticksByOrdinal[unusedOrdinal] != null) {
  29679. unusedOrdinal++;
  29680. }
  29681. ordinalsByTick.push(unusedOrdinal);
  29682. ticksByOrdinal[unusedOrdinal] = tickNum;
  29683. }
  29684. };
  29685. OrdinalScale.prototype._getTickNumber = function (ordinal) {
  29686. var ticksByOrdinalNumber = this._ticksByOrdinalNumber; // also support ordinal out of range of `ordinalMeta.categories.length`,
  29687. // where ordinal numbers are used as tick value directly.
  29688. return ticksByOrdinalNumber && ordinal >= 0 && ordinal < ticksByOrdinalNumber.length ? ticksByOrdinalNumber[ordinal] : ordinal;
  29689. };
  29690. /**
  29691. * @usage
  29692. * ```js
  29693. * const ordinalNumber = ordinalScale.getRawOrdinalNumber(tickVal);
  29694. *
  29695. * // case0
  29696. * const rawOrdinalValue = axisModel.getCategories()[ordinalNumber];
  29697. * // case1
  29698. * const rawOrdinalValue = this._ordinalMeta.categories[ordinalNumber];
  29699. * // case2
  29700. * const coord = axis.dataToCoord(ordinalNumber);
  29701. * ```
  29702. *
  29703. * @param {OrdinalNumber} tickNumber index of display
  29704. */
  29705. OrdinalScale.prototype.getRawOrdinalNumber = function (tickNumber) {
  29706. var ordinalNumbersByTick = this._ordinalNumbersByTick; // tickNumber may be out of range, e.g., when axis max is larger than `ordinalMeta.categories.length`.,
  29707. // where ordinal numbers are used as tick value directly.
  29708. return ordinalNumbersByTick && tickNumber >= 0 && tickNumber < ordinalNumbersByTick.length ? ordinalNumbersByTick[tickNumber] : tickNumber;
  29709. };
  29710. /**
  29711. * Get item on tick
  29712. */
  29713. OrdinalScale.prototype.getLabel = function (tick) {
  29714. if (!this.isBlank()) {
  29715. var ordinalNumber = this.getRawOrdinalNumber(tick.value);
  29716. var cateogry = this._ordinalMeta.categories[ordinalNumber]; // Note that if no data, ordinalMeta.categories is an empty array.
  29717. // Return empty if it's not exist.
  29718. return cateogry == null ? '' : cateogry + '';
  29719. }
  29720. };
  29721. OrdinalScale.prototype.count = function () {
  29722. return this._extent[1] - this._extent[0] + 1;
  29723. };
  29724. OrdinalScale.prototype.unionExtentFromData = function (data, dim) {
  29725. this.unionExtent(data.getApproximateExtent(dim));
  29726. };
  29727. /**
  29728. * @override
  29729. * If value is in extent range
  29730. */
  29731. OrdinalScale.prototype.isInExtentRange = function (value) {
  29732. value = this._getTickNumber(value);
  29733. return this._extent[0] <= value && this._extent[1] >= value;
  29734. };
  29735. OrdinalScale.prototype.getOrdinalMeta = function () {
  29736. return this._ordinalMeta;
  29737. };
  29738. OrdinalScale.prototype.niceTicks = function () {};
  29739. OrdinalScale.prototype.niceExtent = function () {};
  29740. OrdinalScale.type = 'ordinal';
  29741. return OrdinalScale;
  29742. }(Scale);
  29743. Scale.registerClass(OrdinalScale);
  29744. var roundNumber$1 = round;
  29745. var IntervalScale =
  29746. /** @class */
  29747. function (_super) {
  29748. __extends(IntervalScale, _super);
  29749. function IntervalScale() {
  29750. var _this = _super !== null && _super.apply(this, arguments) || this;
  29751. _this.type = 'interval'; // Step is calculated in adjustExtent.
  29752. _this._interval = 0;
  29753. _this._intervalPrecision = 2;
  29754. return _this;
  29755. }
  29756. IntervalScale.prototype.parse = function (val) {
  29757. return val;
  29758. };
  29759. IntervalScale.prototype.contain = function (val) {
  29760. return contain$1(val, this._extent);
  29761. };
  29762. IntervalScale.prototype.normalize = function (val) {
  29763. return normalize$1(val, this._extent);
  29764. };
  29765. IntervalScale.prototype.scale = function (val) {
  29766. return scale$2(val, this._extent);
  29767. };
  29768. IntervalScale.prototype.setExtent = function (start, end) {
  29769. var thisExtent = this._extent; // start,end may be a Number like '25',so...
  29770. if (!isNaN(start)) {
  29771. thisExtent[0] = parseFloat(start);
  29772. }
  29773. if (!isNaN(end)) {
  29774. thisExtent[1] = parseFloat(end);
  29775. }
  29776. };
  29777. IntervalScale.prototype.unionExtent = function (other) {
  29778. var extent = this._extent;
  29779. other[0] < extent[0] && (extent[0] = other[0]);
  29780. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  29781. this.setExtent(extent[0], extent[1]);
  29782. };
  29783. IntervalScale.prototype.getInterval = function () {
  29784. return this._interval;
  29785. };
  29786. IntervalScale.prototype.setInterval = function (interval) {
  29787. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  29788. // We assume user wan't to set both interval, min, max to get a better result
  29789. this._niceExtent = this._extent.slice();
  29790. this._intervalPrecision = getIntervalPrecision(interval);
  29791. };
  29792. /**
  29793. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  29794. */
  29795. IntervalScale.prototype.getTicks = function (expandToNicedExtent) {
  29796. var interval = this._interval;
  29797. var extent = this._extent;
  29798. var niceTickExtent = this._niceExtent;
  29799. var intervalPrecision = this._intervalPrecision;
  29800. var ticks = []; // If interval is 0, return [];
  29801. if (!interval) {
  29802. return ticks;
  29803. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  29804. var safeLimit = 10000;
  29805. if (extent[0] < niceTickExtent[0]) {
  29806. if (expandToNicedExtent) {
  29807. ticks.push({
  29808. value: roundNumber$1(niceTickExtent[0] - interval, intervalPrecision)
  29809. });
  29810. } else {
  29811. ticks.push({
  29812. value: extent[0]
  29813. });
  29814. }
  29815. }
  29816. var tick = niceTickExtent[0];
  29817. while (tick <= niceTickExtent[1]) {
  29818. ticks.push({
  29819. value: tick
  29820. }); // Avoid rounding error
  29821. tick = roundNumber$1(tick + interval, intervalPrecision);
  29822. if (tick === ticks[ticks.length - 1].value) {
  29823. // Consider out of safe float point, e.g.,
  29824. // -3711126.9907707 + 2e-10 === -3711126.9907707
  29825. break;
  29826. }
  29827. if (ticks.length > safeLimit) {
  29828. return [];
  29829. }
  29830. } // Consider this case: the last item of ticks is smaller
  29831. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  29832. var lastNiceTick = ticks.length ? ticks[ticks.length - 1].value : niceTickExtent[1];
  29833. if (extent[1] > lastNiceTick) {
  29834. if (expandToNicedExtent) {
  29835. ticks.push({
  29836. value: roundNumber$1(lastNiceTick + interval, intervalPrecision)
  29837. });
  29838. } else {
  29839. ticks.push({
  29840. value: extent[1]
  29841. });
  29842. }
  29843. }
  29844. return ticks;
  29845. };
  29846. IntervalScale.prototype.getMinorTicks = function (splitNumber) {
  29847. var ticks = this.getTicks(true);
  29848. var minorTicks = [];
  29849. var extent = this.getExtent();
  29850. for (var i = 1; i < ticks.length; i++) {
  29851. var nextTick = ticks[i];
  29852. var prevTick = ticks[i - 1];
  29853. var count = 0;
  29854. var minorTicksGroup = [];
  29855. var interval = nextTick.value - prevTick.value;
  29856. var minorInterval = interval / splitNumber;
  29857. while (count < splitNumber - 1) {
  29858. var minorTick = roundNumber$1(prevTick.value + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  29859. if (minorTick > extent[0] && minorTick < extent[1]) {
  29860. minorTicksGroup.push(minorTick);
  29861. }
  29862. count++;
  29863. }
  29864. minorTicks.push(minorTicksGroup);
  29865. }
  29866. return minorTicks;
  29867. };
  29868. /**
  29869. * @param opt.precision If 'auto', use nice presision.
  29870. * @param opt.pad returns 1.50 but not 1.5 if precision is 2.
  29871. */
  29872. IntervalScale.prototype.getLabel = function (data, opt) {
  29873. if (data == null) {
  29874. return '';
  29875. }
  29876. var precision = opt && opt.precision;
  29877. if (precision == null) {
  29878. precision = getPrecisionSafe(data.value) || 0;
  29879. } else if (precision === 'auto') {
  29880. // Should be more precise then tick.
  29881. precision = this._intervalPrecision;
  29882. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  29883. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  29884. var dataNum = roundNumber$1(data.value, precision, true);
  29885. return addCommas(dataNum);
  29886. };
  29887. /**
  29888. * @param splitNumber By default `5`.
  29889. */
  29890. IntervalScale.prototype.niceTicks = function (splitNumber, minInterval, maxInterval) {
  29891. splitNumber = splitNumber || 5;
  29892. var extent = this._extent;
  29893. var span = extent[1] - extent[0];
  29894. if (!isFinite(span)) {
  29895. return;
  29896. } // User may set axis min 0 and data are all negative
  29897. // FIXME If it needs to reverse ?
  29898. if (span < 0) {
  29899. span = -span;
  29900. extent.reverse();
  29901. }
  29902. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  29903. this._intervalPrecision = result.intervalPrecision;
  29904. this._interval = result.interval;
  29905. this._niceExtent = result.niceTickExtent;
  29906. };
  29907. IntervalScale.prototype.niceExtent = function (opt) {
  29908. var extent = this._extent; // If extent start and end are same, expand them
  29909. if (extent[0] === extent[1]) {
  29910. if (extent[0] !== 0) {
  29911. // Expand extent
  29912. var expandSize = extent[0]; // In the fowllowing case
  29913. // Axis has been fixed max 100
  29914. // Plus data are all 100 and axis extent are [100, 100].
  29915. // Extend to the both side will cause expanded max is larger than fixed max.
  29916. // So only expand to the smaller side.
  29917. if (!opt.fixMax) {
  29918. extent[1] += expandSize / 2;
  29919. extent[0] -= expandSize / 2;
  29920. } else {
  29921. extent[0] -= expandSize / 2;
  29922. }
  29923. } else {
  29924. extent[1] = 1;
  29925. }
  29926. }
  29927. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  29928. if (!isFinite(span)) {
  29929. extent[0] = 0;
  29930. extent[1] = 1;
  29931. }
  29932. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // let extent = this._extent;
  29933. var interval = this._interval;
  29934. if (!opt.fixMin) {
  29935. extent[0] = roundNumber$1(Math.floor(extent[0] / interval) * interval);
  29936. }
  29937. if (!opt.fixMax) {
  29938. extent[1] = roundNumber$1(Math.ceil(extent[1] / interval) * interval);
  29939. }
  29940. };
  29941. IntervalScale.type = 'interval';
  29942. return IntervalScale;
  29943. }(Scale);
  29944. Scale.registerClass(IntervalScale);
  29945. var STACK_PREFIX = '__ec_stack_';
  29946. var LARGE_BAR_MIN_WIDTH = 0.5;
  29947. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  29948. function getSeriesStackId(seriesModel) {
  29949. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  29950. }
  29951. function getAxisKey(axis) {
  29952. return axis.dim + axis.index;
  29953. }
  29954. /**
  29955. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  29956. */
  29957. function getLayoutOnAxis(opt) {
  29958. var params = [];
  29959. var baseAxis = opt.axis;
  29960. var axisKey = 'axis0';
  29961. if (baseAxis.type !== 'category') {
  29962. return;
  29963. }
  29964. var bandWidth = baseAxis.getBandWidth();
  29965. for (var i = 0; i < opt.count || 0; i++) {
  29966. params.push(defaults({
  29967. bandWidth: bandWidth,
  29968. axisKey: axisKey,
  29969. stackId: STACK_PREFIX + i
  29970. }, opt));
  29971. }
  29972. var widthAndOffsets = doCalBarWidthAndOffset(params);
  29973. var result = [];
  29974. for (var i = 0; i < opt.count; i++) {
  29975. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  29976. item.offsetCenter = item.offset + item.width / 2;
  29977. result.push(item);
  29978. }
  29979. return result;
  29980. }
  29981. function prepareLayoutBarSeries(seriesType, ecModel) {
  29982. var seriesModels = [];
  29983. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  29984. // Check series coordinate, do layout for cartesian2d only
  29985. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  29986. seriesModels.push(seriesModel);
  29987. }
  29988. });
  29989. return seriesModels;
  29990. }
  29991. /**
  29992. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  29993. * values.
  29994. * This works for time axes, value axes, and log axes.
  29995. * For a single time axis, return value is in the form like
  29996. * {'x_0': [1000000]}.
  29997. * The value of 1000000 is in milliseconds.
  29998. */
  29999. function getValueAxesMinGaps(barSeries) {
  30000. /**
  30001. * Map from axis.index to values.
  30002. * For a single time axis, axisValues is in the form like
  30003. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  30004. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  30005. * series.
  30006. */
  30007. var axisValues = {};
  30008. each(barSeries, function (seriesModel) {
  30009. var cartesian = seriesModel.coordinateSystem;
  30010. var baseAxis = cartesian.getBaseAxis();
  30011. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  30012. return;
  30013. }
  30014. var data = seriesModel.getData();
  30015. var key = baseAxis.dim + '_' + baseAxis.index;
  30016. var dim = data.mapDimension(baseAxis.dim);
  30017. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  30018. var value = data.get(dim, i);
  30019. if (!axisValues[key]) {
  30020. // No previous data for the axis
  30021. axisValues[key] = [value];
  30022. } else {
  30023. // No value in previous series
  30024. axisValues[key].push(value);
  30025. } // Ignore duplicated time values in the same axis
  30026. }
  30027. });
  30028. var axisMinGaps = {};
  30029. for (var key in axisValues) {
  30030. if (axisValues.hasOwnProperty(key)) {
  30031. var valuesInAxis = axisValues[key];
  30032. if (valuesInAxis) {
  30033. // Sort axis values into ascending order to calculate gaps
  30034. valuesInAxis.sort(function (a, b) {
  30035. return a - b;
  30036. });
  30037. var min = null;
  30038. for (var j = 1; j < valuesInAxis.length; ++j) {
  30039. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  30040. if (delta > 0) {
  30041. // Ignore 0 delta because they are of the same axis value
  30042. min = min === null ? delta : Math.min(min, delta);
  30043. }
  30044. } // Set to null if only have one data
  30045. axisMinGaps[key] = min;
  30046. }
  30047. }
  30048. }
  30049. return axisMinGaps;
  30050. }
  30051. function makeColumnLayout(barSeries) {
  30052. var axisMinGaps = getValueAxesMinGaps(barSeries);
  30053. var seriesInfoList = [];
  30054. each(barSeries, function (seriesModel) {
  30055. var cartesian = seriesModel.coordinateSystem;
  30056. var baseAxis = cartesian.getBaseAxis();
  30057. var axisExtent = baseAxis.getExtent();
  30058. var bandWidth;
  30059. if (baseAxis.type === 'category') {
  30060. bandWidth = baseAxis.getBandWidth();
  30061. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  30062. var key = baseAxis.dim + '_' + baseAxis.index;
  30063. var minGap = axisMinGaps[key];
  30064. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  30065. var scale = baseAxis.scale.getExtent();
  30066. var scaleSpan = Math.abs(scale[1] - scale[0]);
  30067. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  30068. } else {
  30069. var data = seriesModel.getData();
  30070. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  30071. }
  30072. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  30073. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  30074. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  30075. // the auto-calculated bar width might be less than 1.
  30076. seriesModel.get('barMinWidth') || 1, bandWidth);
  30077. var barGap = seriesModel.get('barGap');
  30078. var barCategoryGap = seriesModel.get('barCategoryGap');
  30079. seriesInfoList.push({
  30080. bandWidth: bandWidth,
  30081. barWidth: barWidth,
  30082. barMaxWidth: barMaxWidth,
  30083. barMinWidth: barMinWidth,
  30084. barGap: barGap,
  30085. barCategoryGap: barCategoryGap,
  30086. axisKey: getAxisKey(baseAxis),
  30087. stackId: getSeriesStackId(seriesModel)
  30088. });
  30089. });
  30090. return doCalBarWidthAndOffset(seriesInfoList);
  30091. }
  30092. function doCalBarWidthAndOffset(seriesInfoList) {
  30093. // Columns info on each category axis. Key is cartesian name
  30094. var columnsMap = {};
  30095. each(seriesInfoList, function (seriesInfo, idx) {
  30096. var axisKey = seriesInfo.axisKey;
  30097. var bandWidth = seriesInfo.bandWidth;
  30098. var columnsOnAxis = columnsMap[axisKey] || {
  30099. bandWidth: bandWidth,
  30100. remainedWidth: bandWidth,
  30101. autoWidthCount: 0,
  30102. categoryGap: null,
  30103. gap: '20%',
  30104. stacks: {}
  30105. };
  30106. var stacks = columnsOnAxis.stacks;
  30107. columnsMap[axisKey] = columnsOnAxis;
  30108. var stackId = seriesInfo.stackId;
  30109. if (!stacks[stackId]) {
  30110. columnsOnAxis.autoWidthCount++;
  30111. }
  30112. stacks[stackId] = stacks[stackId] || {
  30113. width: 0,
  30114. maxWidth: 0
  30115. }; // Caution: In a single coordinate system, these barGrid attributes
  30116. // will be shared by series. Consider that they have default values,
  30117. // only the attributes set on the last series will work.
  30118. // Do not change this fact unless there will be a break change.
  30119. var barWidth = seriesInfo.barWidth;
  30120. if (barWidth && !stacks[stackId].width) {
  30121. // See #6312, do not restrict width.
  30122. stacks[stackId].width = barWidth;
  30123. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  30124. columnsOnAxis.remainedWidth -= barWidth;
  30125. }
  30126. var barMaxWidth = seriesInfo.barMaxWidth;
  30127. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  30128. var barMinWidth = seriesInfo.barMinWidth;
  30129. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  30130. var barGap = seriesInfo.barGap;
  30131. barGap != null && (columnsOnAxis.gap = barGap);
  30132. var barCategoryGap = seriesInfo.barCategoryGap;
  30133. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  30134. });
  30135. var result = {};
  30136. each(columnsMap, function (columnsOnAxis, coordSysName) {
  30137. result[coordSysName] = {};
  30138. var stacks = columnsOnAxis.stacks;
  30139. var bandWidth = columnsOnAxis.bandWidth;
  30140. var categoryGapPercent = columnsOnAxis.categoryGap;
  30141. if (categoryGapPercent == null) {
  30142. var columnCount = keys(stacks).length; // More columns in one group
  30143. // the spaces between group is smaller. Or the column will be too thin.
  30144. categoryGapPercent = Math.max(35 - columnCount * 4, 15) + '%';
  30145. }
  30146. var categoryGap = parsePercent$1(categoryGapPercent, bandWidth);
  30147. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  30148. var remainedWidth = columnsOnAxis.remainedWidth;
  30149. var autoWidthCount = columnsOnAxis.autoWidthCount;
  30150. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30151. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  30152. each(stacks, function (column) {
  30153. var maxWidth = column.maxWidth;
  30154. var minWidth = column.minWidth;
  30155. if (!column.width) {
  30156. var finalWidth = autoWidth;
  30157. if (maxWidth && maxWidth < finalWidth) {
  30158. finalWidth = Math.min(maxWidth, remainedWidth);
  30159. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  30160. // bar is able to be visible. So `minWidth` should not be restricted
  30161. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  30162. // the extreme cases for `value` axis, bars are allowed to overlap
  30163. // with each other if `minWidth` specified.
  30164. if (minWidth && minWidth > finalWidth) {
  30165. finalWidth = minWidth;
  30166. }
  30167. if (finalWidth !== autoWidth) {
  30168. column.width = finalWidth;
  30169. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30170. autoWidthCount--;
  30171. }
  30172. } else {
  30173. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  30174. // CSS does. Becuase barWidth can be a percent value, where
  30175. // `barMaxWidth` can be used to restrict the final width.
  30176. var finalWidth = column.width;
  30177. if (maxWidth) {
  30178. finalWidth = Math.min(finalWidth, maxWidth);
  30179. } // `minWidth` has higher priority, as described above
  30180. if (minWidth) {
  30181. finalWidth = Math.max(finalWidth, minWidth);
  30182. }
  30183. column.width = finalWidth;
  30184. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  30185. autoWidthCount--;
  30186. }
  30187. }); // Recalculate width again
  30188. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  30189. autoWidth = Math.max(autoWidth, 0);
  30190. var widthSum = 0;
  30191. var lastColumn;
  30192. each(stacks, function (column, idx) {
  30193. if (!column.width) {
  30194. column.width = autoWidth;
  30195. }
  30196. lastColumn = column;
  30197. widthSum += column.width * (1 + barGapPercent);
  30198. });
  30199. if (lastColumn) {
  30200. widthSum -= lastColumn.width * barGapPercent;
  30201. }
  30202. var offset = -widthSum / 2;
  30203. each(stacks, function (column, stackId) {
  30204. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  30205. bandWidth: bandWidth,
  30206. offset: offset,
  30207. width: column.width
  30208. };
  30209. offset += column.width * (1 + barGapPercent);
  30210. });
  30211. });
  30212. return result;
  30213. }
  30214. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  30215. if (barWidthAndOffset && axis) {
  30216. var result = barWidthAndOffset[getAxisKey(axis)];
  30217. if (result != null && seriesModel != null) {
  30218. return result[getSeriesStackId(seriesModel)];
  30219. }
  30220. return result;
  30221. }
  30222. }
  30223. function layout(seriesType, ecModel) {
  30224. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  30225. var barWidthAndOffset = makeColumnLayout(seriesModels);
  30226. var lastStackCoords = {};
  30227. each(seriesModels, function (seriesModel) {
  30228. var data = seriesModel.getData();
  30229. var cartesian = seriesModel.coordinateSystem;
  30230. var baseAxis = cartesian.getBaseAxis();
  30231. var stackId = getSeriesStackId(seriesModel);
  30232. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  30233. var columnOffset = columnLayoutInfo.offset;
  30234. var columnWidth = columnLayoutInfo.width;
  30235. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30236. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  30237. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  30238. data.setLayout({
  30239. bandWidth: columnLayoutInfo.bandWidth,
  30240. offset: columnOffset,
  30241. size: columnWidth
  30242. });
  30243. var valueDim = data.mapDimension(valueAxis.dim);
  30244. var baseDim = data.mapDimension(baseAxis.dim);
  30245. var stacked = isDimensionStacked(data, valueDim
  30246. /*, baseDim*/
  30247. );
  30248. var isValueAxisH = valueAxis.isHorizontal();
  30249. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis);
  30250. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30251. var value = data.get(valueDim, idx);
  30252. var baseValue = data.get(baseDim, idx);
  30253. var sign = value >= 0 ? 'p' : 'n';
  30254. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  30255. // stackResultDimension directly.
  30256. if (stacked) {
  30257. // Only ordinal axis can be stacked.
  30258. if (!lastStackCoords[stackId][baseValue]) {
  30259. lastStackCoords[stackId][baseValue] = {
  30260. p: valueAxisStart,
  30261. n: valueAxisStart // Negative stack
  30262. };
  30263. } // Should also consider #4243
  30264. baseCoord = lastStackCoords[stackId][baseValue][sign];
  30265. }
  30266. var x = void 0;
  30267. var y = void 0;
  30268. var width = void 0;
  30269. var height = void 0;
  30270. if (isValueAxisH) {
  30271. var coord = cartesian.dataToPoint([value, baseValue]);
  30272. x = baseCoord;
  30273. y = coord[1] + columnOffset;
  30274. width = coord[0] - valueAxisStart;
  30275. height = columnWidth;
  30276. if (Math.abs(width) < barMinHeight) {
  30277. width = (width < 0 ? -1 : 1) * barMinHeight;
  30278. } // Ignore stack from NaN value
  30279. if (!isNaN(width)) {
  30280. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  30281. }
  30282. } else {
  30283. var coord = cartesian.dataToPoint([baseValue, value]);
  30284. x = coord[0] + columnOffset;
  30285. y = baseCoord;
  30286. width = columnWidth;
  30287. height = coord[1] - valueAxisStart;
  30288. if (Math.abs(height) < barMinHeight) {
  30289. // Include zero to has a positive bar
  30290. height = (height <= 0 ? -1 : 1) * barMinHeight;
  30291. } // Ignore stack from NaN value
  30292. if (!isNaN(height)) {
  30293. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  30294. }
  30295. }
  30296. data.setItemLayout(idx, {
  30297. x: x,
  30298. y: y,
  30299. width: width,
  30300. height: height
  30301. });
  30302. }
  30303. });
  30304. } // TODO: Do not support stack in large mode yet.
  30305. var largeLayout = {
  30306. seriesType: 'bar',
  30307. plan: createRenderPlanner(),
  30308. reset: function (seriesModel) {
  30309. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  30310. return;
  30311. }
  30312. var data = seriesModel.getData();
  30313. var cartesian = seriesModel.coordinateSystem;
  30314. var coordLayout = cartesian.master.getRect();
  30315. var baseAxis = cartesian.getBaseAxis();
  30316. var valueAxis = cartesian.getOtherAxis(baseAxis);
  30317. var valueDim = data.mapDimension(valueAxis.dim);
  30318. var baseDim = data.mapDimension(baseAxis.dim);
  30319. var valueAxisHorizontal = valueAxis.isHorizontal();
  30320. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  30321. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  30322. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  30323. // jshint ignore:line
  30324. barWidth = LARGE_BAR_MIN_WIDTH;
  30325. }
  30326. return {
  30327. progress: function (params, data) {
  30328. var count = params.count;
  30329. var largePoints = new LargeArr(count * 2);
  30330. var largeBackgroundPoints = new LargeArr(count * 2);
  30331. var largeDataIndices = new LargeArr(count);
  30332. var dataIndex;
  30333. var coord = [];
  30334. var valuePair = [];
  30335. var pointsOffset = 0;
  30336. var idxOffset = 0;
  30337. while ((dataIndex = params.next()) != null) {
  30338. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  30339. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  30340. coord = cartesian.dataToPoint(valuePair, null, coord); // Data index might not be in order, depends on `progressiveChunkMode`.
  30341. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  30342. largePoints[pointsOffset++] = coord[0];
  30343. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  30344. largePoints[pointsOffset++] = coord[1];
  30345. largeDataIndices[idxOffset++] = dataIndex;
  30346. }
  30347. data.setLayout({
  30348. largePoints: largePoints,
  30349. largeDataIndices: largeDataIndices,
  30350. largeBackgroundPoints: largeBackgroundPoints,
  30351. barWidth: barWidth,
  30352. valueAxisStart: getValueAxisStart(baseAxis, valueAxis),
  30353. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  30354. valueAxisHorizontal: valueAxisHorizontal
  30355. });
  30356. }
  30357. };
  30358. }
  30359. };
  30360. function isOnCartesian(seriesModel) {
  30361. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  30362. }
  30363. function isInLargeMode(seriesModel) {
  30364. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  30365. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  30366. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  30367. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  30368. }
  30369. var bisect = function (a, x, lo, hi) {
  30370. while (lo < hi) {
  30371. var mid = lo + hi >>> 1;
  30372. if (a[mid][1] < x) {
  30373. lo = mid + 1;
  30374. } else {
  30375. hi = mid;
  30376. }
  30377. }
  30378. return lo;
  30379. };
  30380. var TimeScale =
  30381. /** @class */
  30382. function (_super) {
  30383. __extends(TimeScale, _super);
  30384. function TimeScale(settings) {
  30385. var _this = _super.call(this, settings) || this;
  30386. _this.type = 'time';
  30387. return _this;
  30388. }
  30389. /**
  30390. * Get label is mainly for other components like dataZoom, tooltip.
  30391. */
  30392. TimeScale.prototype.getLabel = function (tick) {
  30393. var useUTC = this.getSetting('useUTC');
  30394. return format(tick.value, fullLeveledFormatter[getDefaultFormatPrecisionOfInterval(getPrimaryTimeUnit(this._minLevelUnit))] || fullLeveledFormatter.second, useUTC, this.getSetting('locale'));
  30395. };
  30396. TimeScale.prototype.getFormattedLabel = function (tick, idx, labelFormatter) {
  30397. var isUTC = this.getSetting('useUTC');
  30398. var lang = this.getSetting('locale');
  30399. return leveledFormat(tick, idx, labelFormatter, lang, isUTC);
  30400. };
  30401. /**
  30402. * @override
  30403. * @param expandToNicedExtent Whether expand the ticks to niced extent.
  30404. */
  30405. TimeScale.prototype.getTicks = function (expandToNicedExtent) {
  30406. var interval = this._interval;
  30407. var extent = this._extent;
  30408. var ticks = []; // If interval is 0, return [];
  30409. if (!interval) {
  30410. return ticks;
  30411. }
  30412. ticks.push({
  30413. value: extent[0],
  30414. level: 0
  30415. });
  30416. var useUTC = this.getSetting('useUTC');
  30417. var innerTicks = getIntervalTicks(this._minLevelUnit, this._approxInterval, useUTC, extent);
  30418. ticks = ticks.concat(innerTicks);
  30419. ticks.push({
  30420. value: extent[1],
  30421. level: 0
  30422. });
  30423. return ticks;
  30424. };
  30425. TimeScale.prototype.niceExtent = function (opt) {
  30426. var extent = this._extent; // If extent start and end are same, expand them
  30427. if (extent[0] === extent[1]) {
  30428. // Expand extent
  30429. extent[0] -= ONE_DAY;
  30430. extent[1] += ONE_DAY;
  30431. } // If there are no data and extent are [Infinity, -Infinity]
  30432. if (extent[1] === -Infinity && extent[0] === Infinity) {
  30433. var d = new Date();
  30434. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  30435. extent[0] = extent[1] - ONE_DAY;
  30436. }
  30437. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  30438. };
  30439. TimeScale.prototype.niceTicks = function (approxTickNum, minInterval, maxInterval) {
  30440. approxTickNum = approxTickNum || 10;
  30441. var extent = this._extent;
  30442. var span = extent[1] - extent[0];
  30443. this._approxInterval = span / approxTickNum;
  30444. if (minInterval != null && this._approxInterval < minInterval) {
  30445. this._approxInterval = minInterval;
  30446. }
  30447. if (maxInterval != null && this._approxInterval > maxInterval) {
  30448. this._approxInterval = maxInterval;
  30449. }
  30450. var scaleIntervalsLen = scaleIntervals.length;
  30451. var idx = Math.min(bisect(scaleIntervals, this._approxInterval, 0, scaleIntervalsLen), scaleIntervalsLen - 1); // Interval that can be used to calculate ticks
  30452. this._interval = scaleIntervals[idx][1]; // Min level used when picking ticks from top down.
  30453. // We check one more level to avoid the ticks are to sparse in some case.
  30454. this._minLevelUnit = scaleIntervals[Math.max(idx - 1, 0)][0];
  30455. };
  30456. TimeScale.prototype.parse = function (val) {
  30457. // val might be float.
  30458. return typeof val === 'number' ? val : +parseDate(val);
  30459. };
  30460. TimeScale.prototype.contain = function (val) {
  30461. return contain$1(this.parse(val), this._extent);
  30462. };
  30463. TimeScale.prototype.normalize = function (val) {
  30464. return normalize$1(this.parse(val), this._extent);
  30465. };
  30466. TimeScale.prototype.scale = function (val) {
  30467. return scale$2(val, this._extent);
  30468. };
  30469. TimeScale.type = 'time';
  30470. return TimeScale;
  30471. }(IntervalScale);
  30472. /**
  30473. * This implementation was originally copied from "d3.js"
  30474. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  30475. * with some modifications made for this program.
  30476. * See the license statement at the head of this file.
  30477. */
  30478. var scaleIntervals = [// Format interval
  30479. ['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
  30480. ];
  30481. function isUnitValueSame(unit, valueA, valueB, isUTC) {
  30482. var dateA = parseDate(valueA);
  30483. var dateB = parseDate(valueB);
  30484. var isSame = function (unit) {
  30485. return getUnitValue(dateA, unit, isUTC) === getUnitValue(dateB, unit, isUTC);
  30486. };
  30487. var isSameYear = function () {
  30488. return isSame('year');
  30489. }; // const isSameHalfYear = () => isSameYear() && isSame('half-year');
  30490. // const isSameQuater = () => isSameYear() && isSame('quarter');
  30491. var isSameMonth = function () {
  30492. return isSameYear() && isSame('month');
  30493. };
  30494. var isSameDay = function () {
  30495. return isSameMonth() && isSame('day');
  30496. }; // const isSameHalfDay = () => isSameDay() && isSame('half-day');
  30497. var isSameHour = function () {
  30498. return isSameDay() && isSame('hour');
  30499. };
  30500. var isSameMinute = function () {
  30501. return isSameHour() && isSame('minute');
  30502. };
  30503. var isSameSecond = function () {
  30504. return isSameMinute() && isSame('second');
  30505. };
  30506. var isSameMilliSecond = function () {
  30507. return isSameSecond() && isSame('millisecond');
  30508. };
  30509. switch (unit) {
  30510. case 'year':
  30511. return isSameYear();
  30512. case 'month':
  30513. return isSameMonth();
  30514. case 'day':
  30515. return isSameDay();
  30516. case 'hour':
  30517. return isSameHour();
  30518. case 'minute':
  30519. return isSameMinute();
  30520. case 'second':
  30521. return isSameSecond();
  30522. case 'millisecond':
  30523. return isSameMilliSecond();
  30524. }
  30525. } // const primaryUnitGetters = {
  30526. // year: fullYearGetterName(),
  30527. // month: monthGetterName(),
  30528. // day: dateGetterName(),
  30529. // hour: hoursGetterName(),
  30530. // minute: minutesGetterName(),
  30531. // second: secondsGetterName(),
  30532. // millisecond: millisecondsGetterName()
  30533. // };
  30534. // const primaryUnitUTCGetters = {
  30535. // year: fullYearGetterName(true),
  30536. // month: monthGetterName(true),
  30537. // day: dateGetterName(true),
  30538. // hour: hoursGetterName(true),
  30539. // minute: minutesGetterName(true),
  30540. // second: secondsGetterName(true),
  30541. // millisecond: millisecondsGetterName(true)
  30542. // };
  30543. // function moveTick(date: Date, unitName: TimeUnit, step: number, isUTC: boolean) {
  30544. // step = step || 1;
  30545. // switch (getPrimaryTimeUnit(unitName)) {
  30546. // case 'year':
  30547. // date[fullYearSetterName(isUTC)](date[fullYearGetterName(isUTC)]() + step);
  30548. // break;
  30549. // case 'month':
  30550. // date[monthSetterName(isUTC)](date[monthGetterName(isUTC)]() + step);
  30551. // break;
  30552. // case 'day':
  30553. // date[dateSetterName(isUTC)](date[dateGetterName(isUTC)]() + step);
  30554. // break;
  30555. // case 'hour':
  30556. // date[hoursSetterName(isUTC)](date[hoursGetterName(isUTC)]() + step);
  30557. // break;
  30558. // case 'minute':
  30559. // date[minutesSetterName(isUTC)](date[minutesGetterName(isUTC)]() + step);
  30560. // break;
  30561. // case 'second':
  30562. // date[secondsSetterName(isUTC)](date[secondsGetterName(isUTC)]() + step);
  30563. // break;
  30564. // case 'millisecond':
  30565. // date[millisecondsSetterName(isUTC)](date[millisecondsGetterName(isUTC)]() + step);
  30566. // break;
  30567. // }
  30568. // return date.getTime();
  30569. // }
  30570. // const DATE_INTERVALS = [[8, 7.5], [4, 3.5], [2, 1.5]];
  30571. // const MONTH_INTERVALS = [[6, 5.5], [3, 2.5], [2, 1.5]];
  30572. // const MINUTES_SECONDS_INTERVALS = [[30, 30], [20, 20], [15, 15], [10, 10], [5, 5], [2, 2]];
  30573. function getDateInterval(approxInterval, daysInMonth) {
  30574. approxInterval /= ONE_DAY;
  30575. return approxInterval > 16 ? 16 // Math.floor(daysInMonth / 2) + 1 // In this case we only want one tick betwen two month.
  30576. : approxInterval > 7.5 ? 7 // TODO week 7 or day 8?
  30577. : approxInterval > 3.5 ? 4 : approxInterval > 1.5 ? 2 : 1;
  30578. }
  30579. function getMonthInterval(approxInterval) {
  30580. var APPROX_ONE_MONTH = 30 * ONE_DAY;
  30581. approxInterval /= APPROX_ONE_MONTH;
  30582. return approxInterval > 6 ? 6 : approxInterval > 3 ? 3 : approxInterval > 2 ? 2 : 1;
  30583. }
  30584. function getHourInterval(approxInterval) {
  30585. approxInterval /= ONE_HOUR;
  30586. return approxInterval > 12 ? 12 : approxInterval > 6 ? 6 : approxInterval > 3.5 ? 4 : approxInterval > 2 ? 2 : 1;
  30587. }
  30588. function getMinutesAndSecondsInterval(approxInterval, isMinutes) {
  30589. approxInterval /= isMinutes ? ONE_MINUTE : ONE_SECOND;
  30590. return approxInterval > 30 ? 30 : approxInterval > 20 ? 20 : approxInterval > 15 ? 15 : approxInterval > 10 ? 10 : approxInterval > 5 ? 5 : approxInterval > 2 ? 2 : 1;
  30591. }
  30592. function getMillisecondsInterval(approxInterval) {
  30593. return nice(approxInterval, true);
  30594. }
  30595. function getFirstTimestampOfUnit(date, unitName, isUTC) {
  30596. var outDate = new Date(date);
  30597. switch (getPrimaryTimeUnit(unitName)) {
  30598. case 'year':
  30599. case 'month':
  30600. outDate[monthSetterName(isUTC)](0);
  30601. case 'day':
  30602. outDate[dateSetterName(isUTC)](1);
  30603. case 'hour':
  30604. outDate[hoursSetterName(isUTC)](0);
  30605. case 'minute':
  30606. outDate[minutesSetterName(isUTC)](0);
  30607. case 'second':
  30608. outDate[secondsSetterName(isUTC)](0);
  30609. outDate[millisecondsSetterName(isUTC)](0);
  30610. }
  30611. return outDate.getTime();
  30612. }
  30613. function getIntervalTicks(bottomUnitName, approxInterval, isUTC, extent) {
  30614. var safeLimit = 10000;
  30615. var unitNames = timeUnits;
  30616. var iter = 0;
  30617. function addTicksInSpan(interval, minTimestamp, maxTimestamp, getMethodName, setMethodName, isDate, out) {
  30618. var date = new Date(minTimestamp);
  30619. var dateTime = minTimestamp;
  30620. var d = date[getMethodName](); // if (isDate) {
  30621. // d -= 1; // Starts with 0; PENDING
  30622. // }
  30623. while (dateTime < maxTimestamp && dateTime <= extent[1]) {
  30624. out.push({
  30625. value: dateTime
  30626. });
  30627. d += interval;
  30628. date[setMethodName](d);
  30629. dateTime = date.getTime();
  30630. } // This extra tick is for calcuating ticks of next level. Will not been added to the final result
  30631. out.push({
  30632. value: dateTime,
  30633. notAdd: true
  30634. });
  30635. }
  30636. function addLevelTicks(unitName, lastLevelTicks, levelTicks) {
  30637. var newAddedTicks = [];
  30638. var isFirstLevel = !lastLevelTicks.length;
  30639. if (isUnitValueSame(getPrimaryTimeUnit(unitName), extent[0], extent[1], isUTC)) {
  30640. return;
  30641. }
  30642. if (isFirstLevel) {
  30643. lastLevelTicks = [{
  30644. // TODO Optimize. Not include so may ticks.
  30645. value: getFirstTimestampOfUnit(new Date(extent[0]), unitName, isUTC)
  30646. }, {
  30647. value: extent[1]
  30648. }];
  30649. }
  30650. for (var i = 0; i < lastLevelTicks.length - 1; i++) {
  30651. var startTick = lastLevelTicks[i].value;
  30652. var endTick = lastLevelTicks[i + 1].value;
  30653. if (startTick === endTick) {
  30654. continue;
  30655. }
  30656. var interval = void 0;
  30657. var getterName = void 0;
  30658. var setterName = void 0;
  30659. var isDate = false;
  30660. switch (unitName) {
  30661. case 'year':
  30662. interval = Math.max(1, Math.round(approxInterval / ONE_DAY / 365));
  30663. getterName = fullYearGetterName(isUTC);
  30664. setterName = fullYearSetterName(isUTC);
  30665. break;
  30666. case 'half-year':
  30667. case 'quarter':
  30668. case 'month':
  30669. interval = getMonthInterval(approxInterval);
  30670. getterName = monthGetterName(isUTC);
  30671. setterName = monthSetterName(isUTC);
  30672. break;
  30673. case 'week': // PENDING If week is added. Ignore day.
  30674. case 'half-week':
  30675. case 'day':
  30676. interval = getDateInterval(approxInterval); // Use 32 days and let interval been 16
  30677. getterName = dateGetterName(isUTC);
  30678. setterName = dateSetterName(isUTC);
  30679. isDate = true;
  30680. break;
  30681. case 'half-day':
  30682. case 'quarter-day':
  30683. case 'hour':
  30684. interval = getHourInterval(approxInterval);
  30685. getterName = hoursGetterName(isUTC);
  30686. setterName = hoursSetterName(isUTC);
  30687. break;
  30688. case 'minute':
  30689. interval = getMinutesAndSecondsInterval(approxInterval, true);
  30690. getterName = minutesGetterName(isUTC);
  30691. setterName = minutesSetterName(isUTC);
  30692. break;
  30693. case 'second':
  30694. interval = getMinutesAndSecondsInterval(approxInterval, false);
  30695. getterName = secondsGetterName(isUTC);
  30696. setterName = secondsSetterName(isUTC);
  30697. break;
  30698. case 'millisecond':
  30699. interval = getMillisecondsInterval(approxInterval);
  30700. getterName = millisecondsGetterName(isUTC);
  30701. setterName = millisecondsSetterName(isUTC);
  30702. break;
  30703. }
  30704. addTicksInSpan(interval, startTick, endTick, getterName, setterName, isDate, newAddedTicks);
  30705. if (unitName === 'year' && levelTicks.length > 1 && i === 0) {
  30706. // Add nearest years to the left extent.
  30707. levelTicks.unshift({
  30708. value: levelTicks[0].value - interval
  30709. });
  30710. }
  30711. }
  30712. for (var i = 0; i < newAddedTicks.length; i++) {
  30713. levelTicks.push(newAddedTicks[i]);
  30714. } // newAddedTicks.length && console.log(unitName, newAddedTicks);
  30715. return newAddedTicks;
  30716. }
  30717. var levelsTicks = [];
  30718. var currentLevelTicks = [];
  30719. var tickCount = 0;
  30720. var lastLevelTickCount = 0;
  30721. for (var i = 0; i < unitNames.length && iter++ < safeLimit; ++i) {
  30722. var primaryTimeUnit = getPrimaryTimeUnit(unitNames[i]);
  30723. if (!isPrimaryTimeUnit(unitNames[i])) {
  30724. // TODO
  30725. continue;
  30726. }
  30727. addLevelTicks(unitNames[i], levelsTicks[levelsTicks.length - 1] || [], currentLevelTicks);
  30728. var nextPrimaryTimeUnit = unitNames[i + 1] ? getPrimaryTimeUnit(unitNames[i + 1]) : null;
  30729. if (primaryTimeUnit !== nextPrimaryTimeUnit) {
  30730. if (currentLevelTicks.length) {
  30731. lastLevelTickCount = tickCount; // Remove the duplicate so the tick count can be precisely.
  30732. currentLevelTicks.sort(function (a, b) {
  30733. return a.value - b.value;
  30734. });
  30735. var levelTicksRemoveDuplicated = [];
  30736. for (var i_1 = 0; i_1 < currentLevelTicks.length; ++i_1) {
  30737. var tickValue = currentLevelTicks[i_1].value;
  30738. if (i_1 === 0 || currentLevelTicks[i_1 - 1].value !== tickValue) {
  30739. levelTicksRemoveDuplicated.push(currentLevelTicks[i_1]);
  30740. if (tickValue >= extent[0] && tickValue <= extent[1]) {
  30741. tickCount++;
  30742. }
  30743. }
  30744. }
  30745. var targetTickNum = (extent[1] - extent[0]) / approxInterval; // Added too much in this level and not too less in last level
  30746. if (tickCount > targetTickNum * 1.5 && lastLevelTickCount > targetTickNum / 1.5) {
  30747. break;
  30748. } // Only treat primary time unit as one level.
  30749. levelsTicks.push(levelTicksRemoveDuplicated);
  30750. if (tickCount > targetTickNum || bottomUnitName === unitNames[i]) {
  30751. break;
  30752. }
  30753. } // Reset if next unitName is primary
  30754. currentLevelTicks = [];
  30755. }
  30756. }
  30757. if ("development" !== 'production') {
  30758. if (iter >= safeLimit) {
  30759. warn('Exceed safe limit.');
  30760. }
  30761. }
  30762. var levelsTicksInExtent = filter(map(levelsTicks, function (levelTicks) {
  30763. return filter(levelTicks, function (tick) {
  30764. return tick.value >= extent[0] && tick.value <= extent[1] && !tick.notAdd;
  30765. });
  30766. }), function (levelTicks) {
  30767. return levelTicks.length > 0;
  30768. });
  30769. var ticks = [];
  30770. var maxLevel = levelsTicksInExtent.length - 1;
  30771. for (var i = 0; i < levelsTicksInExtent.length; ++i) {
  30772. var levelTicks = levelsTicksInExtent[i];
  30773. for (var k = 0; k < levelTicks.length; ++k) {
  30774. ticks.push({
  30775. value: levelTicks[k].value,
  30776. level: maxLevel - i
  30777. });
  30778. }
  30779. }
  30780. ticks.sort(function (a, b) {
  30781. return a.value - b.value;
  30782. }); // Remove duplicates
  30783. var result = [];
  30784. for (var i = 0; i < ticks.length; ++i) {
  30785. if (i === 0 || ticks[i].value !== ticks[i - 1].value) {
  30786. result.push(ticks[i]);
  30787. }
  30788. }
  30789. return result;
  30790. }
  30791. Scale.registerClass(TimeScale);
  30792. var scaleProto = Scale.prototype; // FIXME:TS refactor: not good to call it directly with `this`?
  30793. var intervalScaleProto = IntervalScale.prototype;
  30794. var getPrecisionSafe$1 = getPrecisionSafe;
  30795. var roundingErrorFix = round;
  30796. var mathFloor$1 = Math.floor;
  30797. var mathCeil = Math.ceil;
  30798. var mathPow$1 = Math.pow;
  30799. var mathLog = Math.log;
  30800. var LogScale =
  30801. /** @class */
  30802. function (_super) {
  30803. __extends(LogScale, _super);
  30804. function LogScale() {
  30805. var _this = _super !== null && _super.apply(this, arguments) || this;
  30806. _this.type = 'log';
  30807. _this.base = 10;
  30808. _this._originalScale = new IntervalScale(); // FIXME:TS actually used by `IntervalScale`
  30809. _this._interval = 0;
  30810. return _this;
  30811. }
  30812. /**
  30813. * @param Whether expand the ticks to niced extent.
  30814. */
  30815. LogScale.prototype.getTicks = function (expandToNicedExtent) {
  30816. var originalScale = this._originalScale;
  30817. var extent = this._extent;
  30818. var originalExtent = originalScale.getExtent();
  30819. var ticks = intervalScaleProto.getTicks.call(this, expandToNicedExtent);
  30820. return map(ticks, function (tick) {
  30821. var val = tick.value;
  30822. var powVal = round(mathPow$1(this.base, val)); // Fix #4158
  30823. powVal = val === extent[0] && this._fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  30824. powVal = val === extent[1] && this._fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  30825. return {
  30826. value: powVal
  30827. };
  30828. }, this);
  30829. };
  30830. LogScale.prototype.setExtent = function (start, end) {
  30831. var base = this.base;
  30832. start = mathLog(start) / mathLog(base);
  30833. end = mathLog(end) / mathLog(base);
  30834. intervalScaleProto.setExtent.call(this, start, end);
  30835. };
  30836. /**
  30837. * @return {number} end
  30838. */
  30839. LogScale.prototype.getExtent = function () {
  30840. var base = this.base;
  30841. var extent = scaleProto.getExtent.call(this);
  30842. extent[0] = mathPow$1(base, extent[0]);
  30843. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  30844. var originalScale = this._originalScale;
  30845. var originalExtent = originalScale.getExtent();
  30846. this._fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  30847. this._fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  30848. return extent;
  30849. };
  30850. LogScale.prototype.unionExtent = function (extent) {
  30851. this._originalScale.unionExtent(extent);
  30852. var base = this.base;
  30853. extent[0] = mathLog(extent[0]) / mathLog(base);
  30854. extent[1] = mathLog(extent[1]) / mathLog(base);
  30855. scaleProto.unionExtent.call(this, extent);
  30856. };
  30857. LogScale.prototype.unionExtentFromData = function (data, dim) {
  30858. // TODO
  30859. // filter value that <= 0
  30860. this.unionExtent(data.getApproximateExtent(dim));
  30861. };
  30862. /**
  30863. * Update interval and extent of intervals for nice ticks
  30864. * @param approxTickNum default 10 Given approx tick number
  30865. */
  30866. LogScale.prototype.niceTicks = function (approxTickNum) {
  30867. approxTickNum = approxTickNum || 10;
  30868. var extent = this._extent;
  30869. var span = extent[1] - extent[0];
  30870. if (span === Infinity || span <= 0) {
  30871. return;
  30872. }
  30873. var interval = quantity(span);
  30874. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  30875. if (err <= 0.5) {
  30876. interval *= 10;
  30877. } // Interval should be integer
  30878. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  30879. interval *= 10;
  30880. }
  30881. var niceExtent = [round(mathCeil(extent[0] / interval) * interval), round(mathFloor$1(extent[1] / interval) * interval)];
  30882. this._interval = interval;
  30883. this._niceExtent = niceExtent;
  30884. };
  30885. LogScale.prototype.niceExtent = function (opt) {
  30886. intervalScaleProto.niceExtent.call(this, opt);
  30887. this._fixMin = opt.fixMin;
  30888. this._fixMax = opt.fixMax;
  30889. };
  30890. LogScale.prototype.parse = function (val) {
  30891. return val;
  30892. };
  30893. LogScale.prototype.contain = function (val) {
  30894. val = mathLog(val) / mathLog(this.base);
  30895. return contain$1(val, this._extent);
  30896. };
  30897. LogScale.prototype.normalize = function (val) {
  30898. val = mathLog(val) / mathLog(this.base);
  30899. return normalize$1(val, this._extent);
  30900. };
  30901. LogScale.prototype.scale = function (val) {
  30902. val = scale$2(val, this._extent);
  30903. return mathPow$1(this.base, val);
  30904. };
  30905. LogScale.type = 'log';
  30906. return LogScale;
  30907. }(Scale);
  30908. var proto = LogScale.prototype;
  30909. proto.getMinorTicks = intervalScaleProto.getMinorTicks;
  30910. proto.getLabel = intervalScaleProto.getLabel;
  30911. function fixRoundingError(val, originalVal) {
  30912. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  30913. }
  30914. Scale.registerClass(LogScale);
  30915. var ScaleRawExtentInfo =
  30916. /** @class */
  30917. function () {
  30918. function ScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  30919. originalExtent) {
  30920. this._prepareParams(scale, model, originalExtent);
  30921. }
  30922. /**
  30923. * Parameters depending on ouside (like model, user callback)
  30924. * are prepared and fixed here.
  30925. */
  30926. ScaleRawExtentInfo.prototype._prepareParams = function (scale, model, // Usually: data extent from all series on this axis.
  30927. dataExtent) {
  30928. if (dataExtent[1] < dataExtent[0]) {
  30929. dataExtent = [NaN, NaN];
  30930. }
  30931. this._dataMin = dataExtent[0];
  30932. this._dataMax = dataExtent[1];
  30933. var isOrdinal = this._isOrdinal = scale.type === 'ordinal';
  30934. this._needCrossZero = model.getNeedCrossZero && model.getNeedCrossZero();
  30935. var modelMinRaw = this._modelMinRaw = model.get('min', true);
  30936. if (isFunction(modelMinRaw)) {
  30937. // This callback alway provide users the full data extent (before data filtered).
  30938. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw({
  30939. min: dataExtent[0],
  30940. max: dataExtent[1]
  30941. }));
  30942. } else if (modelMinRaw !== 'dataMin') {
  30943. this._modelMinNum = parseAxisModelMinMax(scale, modelMinRaw);
  30944. }
  30945. var modelMaxRaw = this._modelMaxRaw = model.get('max', true);
  30946. if (isFunction(modelMaxRaw)) {
  30947. // This callback alway provide users the full data extent (before data filtered).
  30948. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw({
  30949. min: dataExtent[0],
  30950. max: dataExtent[1]
  30951. }));
  30952. } else if (modelMaxRaw !== 'dataMax') {
  30953. this._modelMaxNum = parseAxisModelMinMax(scale, modelMaxRaw);
  30954. }
  30955. if (isOrdinal) {
  30956. // FIXME: there is a flaw here: if there is no "block" data processor like `dataZoom`,
  30957. // and progressive rendering is using, here the category result might just only contain
  30958. // the processed chunk rather than the entire result.
  30959. this._axisDataLen = model.getCategories().length;
  30960. } else {
  30961. var boundaryGap = model.get('boundaryGap');
  30962. var boundaryGapArr = isArray(boundaryGap) ? boundaryGap : [boundaryGap || 0, boundaryGap || 0];
  30963. if (typeof boundaryGapArr[0] === 'boolean' || typeof boundaryGapArr[1] === 'boolean') {
  30964. if ("development" !== 'production') {
  30965. 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.');
  30966. }
  30967. this._boundaryGapInner = [0, 0];
  30968. } else {
  30969. this._boundaryGapInner = [parsePercent(boundaryGapArr[0], 1), parsePercent(boundaryGapArr[1], 1)];
  30970. }
  30971. }
  30972. };
  30973. /**
  30974. * Calculate extent by prepared parameters.
  30975. * This method has no external dependency and can be called duplicatedly,
  30976. * getting the same result.
  30977. * If parameters changed, should call this method to recalcuate.
  30978. */
  30979. ScaleRawExtentInfo.prototype.calculate = function () {
  30980. // Notice: When min/max is not set (that is, when there are null/undefined,
  30981. // which is the most common case), these cases should be ensured:
  30982. // (1) For 'ordinal', show all axis.data.
  30983. // (2) For others:
  30984. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  30985. // disabled).
  30986. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  30987. // be the result that originalExtent enlarged by boundaryGap.
  30988. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  30989. var isOrdinal = this._isOrdinal;
  30990. var dataMin = this._dataMin;
  30991. var dataMax = this._dataMax;
  30992. var axisDataLen = this._axisDataLen;
  30993. var boundaryGapInner = this._boundaryGapInner;
  30994. var span = !isOrdinal ? dataMax - dataMin || Math.abs(dataMin) : null; // Currently if a `'value'` axis model min is specified as 'dataMin'/'dataMax',
  30995. // `boundaryGap` will not be used. It's the different from specifying as `null`/`undefined`.
  30996. var min = this._modelMinRaw === 'dataMin' ? dataMin : this._modelMinNum;
  30997. var max = this._modelMaxRaw === 'dataMax' ? dataMax : this._modelMaxNum; // If `_modelMinNum`/`_modelMaxNum` is `null`/`undefined`, should not be fixed.
  30998. var minFixed = min != null;
  30999. var maxFixed = max != null;
  31000. if (min == null) {
  31001. min = isOrdinal ? axisDataLen ? 0 : NaN : dataMin - boundaryGapInner[0] * span;
  31002. }
  31003. if (max == null) {
  31004. max = isOrdinal ? axisDataLen ? axisDataLen - 1 : NaN : dataMax + boundaryGapInner[1] * span;
  31005. }
  31006. (min == null || !isFinite(min)) && (min = NaN);
  31007. (max == null || !isFinite(max)) && (max = NaN);
  31008. if (min > max) {
  31009. min = NaN;
  31010. max = NaN;
  31011. }
  31012. var isBlank = eqNaN(min) || eqNaN(max) || isOrdinal && !axisDataLen; // If data extent modified, need to recalculated to ensure cross zero.
  31013. if (this._needCrossZero) {
  31014. // Axis is over zero and min is not set
  31015. if (min > 0 && max > 0 && !minFixed) {
  31016. min = 0; // minFixed = true;
  31017. } // Axis is under zero and max is not set
  31018. if (min < 0 && max < 0 && !maxFixed) {
  31019. max = 0; // maxFixed = true;
  31020. } // PENDING:
  31021. // When `needCrossZero` and all data is positive/negative, should it be ensured
  31022. // that the results processed by boundaryGap are positive/negative?
  31023. // If so, here `minFixed`/`maxFixed` need to be set.
  31024. }
  31025. var determinedMin = this._determinedMin;
  31026. var determinedMax = this._determinedMax;
  31027. if (determinedMin != null) {
  31028. min = determinedMin;
  31029. minFixed = true;
  31030. }
  31031. if (determinedMax != null) {
  31032. max = determinedMax;
  31033. maxFixed = true;
  31034. } // Ensure min/max be finite number or NaN here. (not to be null/undefined)
  31035. // `NaN` means min/max axis is blank.
  31036. return {
  31037. min: min,
  31038. max: max,
  31039. minFixed: minFixed,
  31040. maxFixed: maxFixed,
  31041. isBlank: isBlank
  31042. };
  31043. };
  31044. ScaleRawExtentInfo.prototype.modifyDataMinMax = function (minMaxName, val) {
  31045. if ("development" !== 'production') {
  31046. assert(!this.frozen);
  31047. }
  31048. this[DATA_MIN_MAX_ATTR[minMaxName]] = val;
  31049. };
  31050. ScaleRawExtentInfo.prototype.setDeterminedMinMax = function (minMaxName, val) {
  31051. var attr = DETERMINED_MIN_MAX_ATTR[minMaxName];
  31052. if ("development" !== 'production') {
  31053. assert(!this.frozen // Earse them usually means logic flaw.
  31054. && this[attr] == null);
  31055. }
  31056. this[attr] = val;
  31057. };
  31058. ScaleRawExtentInfo.prototype.freeze = function () {
  31059. // @ts-ignore
  31060. this.frozen = true;
  31061. };
  31062. return ScaleRawExtentInfo;
  31063. }();
  31064. var DETERMINED_MIN_MAX_ATTR = {
  31065. min: '_determinedMin',
  31066. max: '_determinedMax'
  31067. };
  31068. var DATA_MIN_MAX_ATTR = {
  31069. min: '_dataMin',
  31070. max: '_dataMax'
  31071. };
  31072. /**
  31073. * Get scale min max and related info only depends on model settings.
  31074. * This method can be called after coordinate system created.
  31075. * For example, in data processing stage.
  31076. *
  31077. * Scale extent info probably be required multiple times during a workflow.
  31078. * For example:
  31079. * (1) `dataZoom` depends it to get the axis extent in "100%" state.
  31080. * (2) `processor/extentCalculator` depends it to make sure whether axis extent is specified.
  31081. * (3) `coordSys.update` use it to finally decide the scale extent.
  31082. * But the callback of `min`/`max` should not be called multiple times.
  31083. * The code below should not be implemented repeatedly either.
  31084. * So we cache the result in the scale instance, which will be recreated at the begining
  31085. * of the workflow (because `scale` instance will be recreated each round of the workflow).
  31086. */
  31087. function ensureScaleRawExtentInfo(scale, model, // Usually: data extent from all series on this axis.
  31088. originalExtent) {
  31089. // Do not permit to recreate.
  31090. var rawExtentInfo = scale.rawExtentInfo;
  31091. if (rawExtentInfo) {
  31092. return rawExtentInfo;
  31093. }
  31094. rawExtentInfo = new ScaleRawExtentInfo(scale, model, originalExtent); // @ts-ignore
  31095. scale.rawExtentInfo = rawExtentInfo;
  31096. return rawExtentInfo;
  31097. }
  31098. function parseAxisModelMinMax(scale, minMax) {
  31099. return minMax == null ? null : eqNaN(minMax) ? NaN : scale.parse(minMax);
  31100. }
  31101. /**
  31102. * Get axis scale extent before niced.
  31103. * Item of returned array can only be number (including Infinity and NaN).
  31104. *
  31105. * Caution:
  31106. * Precondition of calling this method:
  31107. * The scale extent has been initialized using series data extent via
  31108. * `scale.setExtent` or `scale.unionExtentFromData`;
  31109. */
  31110. function getScaleExtent(scale, model) {
  31111. var scaleType = scale.type;
  31112. var rawExtentResult = ensureScaleRawExtentInfo(scale, model, scale.getExtent()).calculate();
  31113. scale.setBlank(rawExtentResult.isBlank);
  31114. var min = rawExtentResult.min;
  31115. 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
  31116. // is base axis
  31117. // FIXME
  31118. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  31119. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  31120. // Should not depend on series type `bar`?
  31121. // (3) Fix that might overlap when using dataZoom.
  31122. // (4) Consider other chart types using `barGrid`?
  31123. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  31124. var ecModel = model.ecModel;
  31125. if (ecModel && scaleType === 'time'
  31126. /*|| scaleType === 'interval' */
  31127. ) {
  31128. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  31129. var isBaseAxisAndHasBarSeries_1 = false;
  31130. each(barSeriesModels, function (seriesModel) {
  31131. isBaseAxisAndHasBarSeries_1 = isBaseAxisAndHasBarSeries_1 || seriesModel.getBaseAxis() === model.axis;
  31132. });
  31133. if (isBaseAxisAndHasBarSeries_1) {
  31134. // Calculate placement of bars on axis. TODO should be decoupled
  31135. // with barLayout
  31136. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  31137. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  31138. min = adjustedScale.min;
  31139. max = adjustedScale.max;
  31140. }
  31141. }
  31142. return {
  31143. extent: [min, max],
  31144. // "fix" means "fixed", the value should not be
  31145. // changed in the subsequent steps.
  31146. fixMin: rawExtentResult.minFixed,
  31147. fixMax: rawExtentResult.maxFixed
  31148. };
  31149. }
  31150. function adjustScaleForOverflow(min, max, model, // Only support cartesian coord yet.
  31151. barWidthAndOffset) {
  31152. // Get Axis Length
  31153. var axisExtent = model.axis.getExtent();
  31154. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  31155. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  31156. if (barsOnCurrentAxis === undefined) {
  31157. return {
  31158. min: min,
  31159. max: max
  31160. };
  31161. }
  31162. var minOverflow = Infinity;
  31163. each(barsOnCurrentAxis, function (item) {
  31164. minOverflow = Math.min(item.offset, minOverflow);
  31165. });
  31166. var maxOverflow = -Infinity;
  31167. each(barsOnCurrentAxis, function (item) {
  31168. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  31169. });
  31170. minOverflow = Math.abs(minOverflow);
  31171. maxOverflow = Math.abs(maxOverflow);
  31172. var totalOverFlow = minOverflow + maxOverflow; // Calculate required buffer based on old range and overflow
  31173. var oldRange = max - min;
  31174. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  31175. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  31176. max += overflowBuffer * (maxOverflow / totalOverFlow);
  31177. min -= overflowBuffer * (minOverflow / totalOverFlow);
  31178. return {
  31179. min: min,
  31180. max: max
  31181. };
  31182. } // Precondition of calling this method:
  31183. // The scale extent has been initailized using series data extent via
  31184. // `scale.setExtent` or `scale.unionExtentFromData`;
  31185. function niceScaleExtent(scale, model) {
  31186. var extentInfo = getScaleExtent(scale, model);
  31187. var extent = extentInfo.extent;
  31188. var splitNumber = model.get('splitNumber');
  31189. if (scale instanceof LogScale) {
  31190. scale.base = model.get('logBase');
  31191. }
  31192. var scaleType = scale.type;
  31193. scale.setExtent(extent[0], extent[1]);
  31194. scale.niceExtent({
  31195. splitNumber: splitNumber,
  31196. fixMin: extentInfo.fixMin,
  31197. fixMax: extentInfo.fixMax,
  31198. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  31199. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  31200. }); // If some one specified the min, max. And the default calculated interval
  31201. // is not good enough. He can specify the interval. It is often appeared
  31202. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  31203. // to be 60.
  31204. // FIXME
  31205. var interval = model.get('interval');
  31206. if (interval != null) {
  31207. scale.setInterval && scale.setInterval(interval);
  31208. }
  31209. }
  31210. /**
  31211. * @param axisType Default retrieve from model.type
  31212. */
  31213. function createScaleByModel(model, axisType) {
  31214. axisType = axisType || model.get('type');
  31215. if (axisType) {
  31216. switch (axisType) {
  31217. // Buildin scale
  31218. case 'category':
  31219. return new OrdinalScale({
  31220. ordinalMeta: model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(),
  31221. extent: [Infinity, -Infinity]
  31222. });
  31223. case 'time':
  31224. return new TimeScale({
  31225. locale: model.ecModel.getLocaleModel(),
  31226. useUTC: model.ecModel.get('useUTC')
  31227. });
  31228. default:
  31229. // case 'value'/'interval', 'log', or others.
  31230. return new (Scale.getClass(axisType) || IntervalScale)();
  31231. }
  31232. }
  31233. }
  31234. /**
  31235. * Check if the axis cross 0
  31236. */
  31237. function ifAxisCrossZero(axis) {
  31238. var dataExtent = axis.scale.getExtent();
  31239. var min = dataExtent[0];
  31240. var max = dataExtent[1];
  31241. return !(min > 0 && max > 0 || min < 0 && max < 0);
  31242. }
  31243. /**
  31244. * @param axis
  31245. * @return Label formatter function.
  31246. * param: {number} tickValue,
  31247. * param: {number} idx, the index in all ticks.
  31248. * If category axis, this param is not required.
  31249. * return: {string} label string.
  31250. */
  31251. function makeLabelFormatter(axis) {
  31252. var labelFormatter = axis.getLabelModel().get('formatter');
  31253. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  31254. if (axis.scale.type === 'time') {
  31255. return function (tpl) {
  31256. return function (tick, idx) {
  31257. return axis.scale.getFormattedLabel(tick, idx, tpl);
  31258. };
  31259. }(labelFormatter);
  31260. } else if (typeof labelFormatter === 'string') {
  31261. return function (tpl) {
  31262. return function (tick) {
  31263. // For category axis, get raw value; for numeric axis,
  31264. // get formatted label like '1,333,444'.
  31265. var label = axis.scale.getLabel(tick);
  31266. var text = tpl.replace('{value}', label != null ? label : '');
  31267. return text;
  31268. };
  31269. }(labelFormatter);
  31270. } else if (typeof labelFormatter === 'function') {
  31271. return function (cb) {
  31272. return function (tick, idx) {
  31273. // The original intention of `idx` is "the index of the tick in all ticks".
  31274. // But the previous implementation of category axis do not consider the
  31275. // `axisLabel.interval`, which cause that, for example, the `interval` is
  31276. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  31277. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  31278. // the definition here for back compatibility.
  31279. if (categoryTickStart != null) {
  31280. idx = tick.value - categoryTickStart;
  31281. }
  31282. return cb(getAxisRawValue(axis, tick), idx, tick.level != null ? {
  31283. level: tick.level
  31284. } : null);
  31285. };
  31286. }(labelFormatter);
  31287. } else {
  31288. return function (tick) {
  31289. return axis.scale.getLabel(tick);
  31290. };
  31291. }
  31292. }
  31293. function getAxisRawValue(axis, tick) {
  31294. // In category axis with data zoom, tick is not the original
  31295. // index of axis.data. So tick should not be exposed to user
  31296. // in category axis.
  31297. return axis.type === 'category' ? axis.scale.getLabel(tick) : tick.value;
  31298. }
  31299. /**
  31300. * @param axis
  31301. * @return Be null/undefined if no labels.
  31302. */
  31303. function estimateLabelUnionRect(axis) {
  31304. var axisModel = axis.model;
  31305. var scale = axis.scale;
  31306. if (!axisModel.get(['axisLabel', 'show']) || scale.isBlank()) {
  31307. return;
  31308. }
  31309. var realNumberScaleTicks;
  31310. var tickCount;
  31311. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  31312. if (scale instanceof OrdinalScale) {
  31313. tickCount = scale.count();
  31314. } else {
  31315. realNumberScaleTicks = scale.getTicks();
  31316. tickCount = realNumberScaleTicks.length;
  31317. }
  31318. var axisLabelModel = axis.getLabelModel();
  31319. var labelFormatter = makeLabelFormatter(axis);
  31320. var rect;
  31321. var step = 1; // Simple optimization for large amount of labels
  31322. if (tickCount > 40) {
  31323. step = Math.ceil(tickCount / 40);
  31324. }
  31325. for (var i = 0; i < tickCount; i += step) {
  31326. var tick = realNumberScaleTicks ? realNumberScaleTicks[i] : {
  31327. value: categoryScaleExtent[0] + i
  31328. };
  31329. var label = labelFormatter(tick, i);
  31330. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  31331. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  31332. rect ? rect.union(singleRect) : rect = singleRect;
  31333. }
  31334. return rect;
  31335. }
  31336. function rotateTextRect(textRect, rotate) {
  31337. var rotateRadians = rotate * Math.PI / 180;
  31338. var beforeWidth = textRect.width;
  31339. var beforeHeight = textRect.height;
  31340. var afterWidth = beforeWidth * Math.abs(Math.cos(rotateRadians)) + Math.abs(beforeHeight * Math.sin(rotateRadians));
  31341. var afterHeight = beforeWidth * Math.abs(Math.sin(rotateRadians)) + Math.abs(beforeHeight * Math.cos(rotateRadians));
  31342. var rotatedRect = new BoundingRect(textRect.x, textRect.y, afterWidth, afterHeight);
  31343. return rotatedRect;
  31344. }
  31345. /**
  31346. * @param model axisLabelModel or axisTickModel
  31347. * @return {number|String} Can be null|'auto'|number|function
  31348. */
  31349. function getOptionCategoryInterval(model) {
  31350. var interval = model.get('interval');
  31351. return interval == null ? 'auto' : interval;
  31352. }
  31353. /**
  31354. * Set `categoryInterval` as 0 implicitly indicates that
  31355. * show all labels reguardless of overlap.
  31356. * @param {Object} axis axisModel.axis
  31357. */
  31358. function shouldShowAllLabels(axis) {
  31359. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  31360. }
  31361. function getDataDimensionsOnAxis(data, axisDim) {
  31362. // Remove duplicated dat dimensions caused by `getStackedDimension`.
  31363. var dataDimMap = {}; // Currently `mapDimensionsAll` will contain stack result dimension ('__\0ecstackresult').
  31364. // PENDING: is it reasonable? Do we need to remove the original dim from "coord dim" since
  31365. // there has been stacked result dim?
  31366. each(data.mapDimensionsAll(axisDim), function (dataDim) {
  31367. // For example, the extent of the original dimension
  31368. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31369. // is [7, 9], the final extent should NOT include [0.1, 0.5],
  31370. // because there is no graphic corresponding to [0.1, 0.5].
  31371. // See the case in `test/area-stack.html` `main1`, where area line
  31372. // stack needs `yAxis` not start from 0.
  31373. dataDimMap[getStackedDimension(data, dataDim)] = true;
  31374. });
  31375. return keys(dataDimMap);
  31376. }
  31377. function unionAxisExtentFromData(dataExtent, data, axisDim) {
  31378. if (data) {
  31379. each(getDataDimensionsOnAxis(data, axisDim), function (dim) {
  31380. var seriesExtent = data.getApproximateExtent(dim);
  31381. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  31382. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  31383. });
  31384. }
  31385. }
  31386. /*
  31387. * Licensed to the Apache Software Foundation (ASF) under one
  31388. * or more contributor license agreements. See the NOTICE file
  31389. * distributed with this work for additional information
  31390. * regarding copyright ownership. The ASF licenses this file
  31391. * to you under the Apache License, Version 2.0 (the
  31392. * "License"); you may not use this file except in compliance
  31393. * with the License. You may obtain a copy of the License at
  31394. *
  31395. * http://www.apache.org/licenses/LICENSE-2.0
  31396. *
  31397. * Unless required by applicable law or agreed to in writing,
  31398. * software distributed under the License is distributed on an
  31399. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31400. * KIND, either express or implied. See the License for the
  31401. * specific language governing permissions and limitations
  31402. * under the License.
  31403. */
  31404. /**
  31405. * AUTO-GENERATED FILE. DO NOT MODIFY.
  31406. */
  31407. /*
  31408. * Licensed to the Apache Software Foundation (ASF) under one
  31409. * or more contributor license agreements. See the NOTICE file
  31410. * distributed with this work for additional information
  31411. * regarding copyright ownership. The ASF licenses this file
  31412. * to you under the Apache License, Version 2.0 (the
  31413. * "License"); you may not use this file except in compliance
  31414. * with the License. You may obtain a copy of the License at
  31415. *
  31416. * http://www.apache.org/licenses/LICENSE-2.0
  31417. *
  31418. * Unless required by applicable law or agreed to in writing,
  31419. * software distributed under the License is distributed on an
  31420. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31421. * KIND, either express or implied. See the License for the
  31422. * specific language governing permissions and limitations
  31423. * under the License.
  31424. */
  31425. var AxisModelCommonMixin =
  31426. /** @class */
  31427. function () {
  31428. function AxisModelCommonMixin() {}
  31429. AxisModelCommonMixin.prototype.getNeedCrossZero = function () {
  31430. var option = this.option;
  31431. return !option.scale;
  31432. };
  31433. /**
  31434. * Should be implemented by each axis model if necessary.
  31435. * @return coordinate system model
  31436. */
  31437. AxisModelCommonMixin.prototype.getCoordSysModel = function () {
  31438. return;
  31439. };
  31440. return AxisModelCommonMixin;
  31441. }();
  31442. /**
  31443. * Create a muti dimension List structure from seriesModel.
  31444. */
  31445. function createList(seriesModel) {
  31446. return createListFromArray(seriesModel.getSource(), seriesModel);
  31447. } // export function createGraph(seriesModel) {
  31448. var dataStack$1 = {
  31449. isDimensionStacked: isDimensionStacked,
  31450. enableDataStack: enableDataStack,
  31451. getStackedDimension: getStackedDimension
  31452. };
  31453. /**
  31454. * Create scale
  31455. * @param {Array.<number>} dataExtent
  31456. * @param {Object|module:echarts/Model} option If `optoin.type`
  31457. * is secified, it can only be `'value'` currently.
  31458. */
  31459. function createScale(dataExtent, option) {
  31460. var axisModel = option;
  31461. if (!(option instanceof Model)) {
  31462. axisModel = new Model(option); // FIXME
  31463. // Currently AxisModelCommonMixin has nothing to do with the
  31464. // the requirements of `axisHelper.createScaleByModel`. For
  31465. // example the method `getCategories` and `getOrdinalMeta`
  31466. // are required for `'category'` axis, and ecModel are required
  31467. // for `'time'` axis. But occationally echarts-gl happened
  31468. // to only use `'value'` axis.
  31469. // zrUtil.mixin(axisModel, AxisModelCommonMixin);
  31470. }
  31471. var scale = createScaleByModel(axisModel);
  31472. scale.setExtent(dataExtent[0], dataExtent[1]);
  31473. niceScaleExtent(scale, axisModel);
  31474. return scale;
  31475. }
  31476. /**
  31477. * Mixin common methods to axis model,
  31478. *
  31479. * Inlcude methods
  31480. * `getFormattedLabels() => Array.<string>`
  31481. * `getCategories() => Array.<string>`
  31482. * `getMin(origin: boolean) => number`
  31483. * `getMax(origin: boolean) => number`
  31484. * `getNeedCrossZero() => boolean`
  31485. */
  31486. function mixinAxisModelCommonMethods(Model) {
  31487. mixin(Model, AxisModelCommonMixin);
  31488. }
  31489. function createTextStyle$1(textStyleModel, opts) {
  31490. opts = opts || {};
  31491. return createTextStyle(textStyleModel, null, null, opts.state !== 'normal');
  31492. }
  31493. var helper = /*#__PURE__*/Object.freeze({
  31494. __proto__: null,
  31495. createList: createList,
  31496. getLayoutRect: getLayoutRect,
  31497. dataStack: dataStack$1,
  31498. createScale: createScale,
  31499. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  31500. getECData: getECData,
  31501. createTextStyle: createTextStyle$1,
  31502. createDimensions: createDimensions,
  31503. createSymbol: createSymbol,
  31504. enableHoverEmphasis: enableHoverEmphasis
  31505. });
  31506. var EPSILON$3 = 1e-8;
  31507. function isAroundEqual$1(a, b) {
  31508. return Math.abs(a - b) < EPSILON$3;
  31509. }
  31510. function contain$2(points, x, y) {
  31511. var w = 0;
  31512. var p = points[0];
  31513. if (!p) {
  31514. return false;
  31515. }
  31516. for (var i = 1; i < points.length; i++) {
  31517. var p2 = points[i];
  31518. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  31519. p = p2;
  31520. }
  31521. var p0 = points[0];
  31522. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  31523. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  31524. }
  31525. return w !== 0;
  31526. }
  31527. var Region =
  31528. /** @class */
  31529. function () {
  31530. function Region(name, geometries, cp) {
  31531. this.name = name;
  31532. this.geometries = geometries;
  31533. if (!cp) {
  31534. var rect = this.getBoundingRect();
  31535. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31536. } else {
  31537. cp = [cp[0], cp[1]];
  31538. }
  31539. this.center = cp;
  31540. }
  31541. Region.prototype.getBoundingRect = function () {
  31542. var rect = this._rect;
  31543. if (rect) {
  31544. return rect;
  31545. }
  31546. var MAX_NUMBER = Number.MAX_VALUE;
  31547. var min$1 = [MAX_NUMBER, MAX_NUMBER];
  31548. var max$1 = [-MAX_NUMBER, -MAX_NUMBER];
  31549. var min2 = [];
  31550. var max2 = [];
  31551. var geometries = this.geometries;
  31552. var i = 0;
  31553. for (; i < geometries.length; i++) {
  31554. // Only support polygon
  31555. if (geometries[i].type !== 'polygon') {
  31556. continue;
  31557. } // Doesn't consider hole
  31558. var exterior = geometries[i].exterior;
  31559. fromPoints(exterior, min2, max2);
  31560. min(min$1, min$1, min2);
  31561. max(max$1, max$1, max2);
  31562. } // No data
  31563. if (i === 0) {
  31564. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  31565. }
  31566. return this._rect = new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  31567. };
  31568. Region.prototype.contain = function (coord) {
  31569. var rect = this.getBoundingRect();
  31570. var geometries = this.geometries;
  31571. if (!rect.contain(coord[0], coord[1])) {
  31572. return false;
  31573. }
  31574. loopGeo: for (var i = 0, len = geometries.length; i < len; i++) {
  31575. // Only support polygon.
  31576. if (geometries[i].type !== 'polygon') {
  31577. continue;
  31578. }
  31579. var exterior = geometries[i].exterior;
  31580. var interiors = geometries[i].interiors;
  31581. if (contain$2(exterior, coord[0], coord[1])) {
  31582. // Not in the region if point is in the hole.
  31583. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  31584. if (contain$2(interiors[k], coord[0], coord[1])) {
  31585. continue loopGeo;
  31586. }
  31587. }
  31588. return true;
  31589. }
  31590. }
  31591. return false;
  31592. };
  31593. Region.prototype.transformTo = function (x, y, width, height) {
  31594. var rect = this.getBoundingRect();
  31595. var aspect = rect.width / rect.height;
  31596. if (!width) {
  31597. width = aspect * height;
  31598. } else if (!height) {
  31599. height = width / aspect;
  31600. }
  31601. var target = new BoundingRect(x, y, width, height);
  31602. var transform = rect.calculateTransform(target);
  31603. var geometries = this.geometries;
  31604. for (var i = 0; i < geometries.length; i++) {
  31605. // Only support polygon.
  31606. if (geometries[i].type !== 'polygon') {
  31607. continue;
  31608. }
  31609. var exterior = geometries[i].exterior;
  31610. var interiors = geometries[i].interiors;
  31611. for (var p = 0; p < exterior.length; p++) {
  31612. applyTransform(exterior[p], exterior[p], transform);
  31613. }
  31614. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  31615. for (var p = 0; p < interiors[h].length; p++) {
  31616. applyTransform(interiors[h][p], interiors[h][p], transform);
  31617. }
  31618. }
  31619. }
  31620. rect = this._rect;
  31621. rect.copy(target); // Update center
  31622. this.center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  31623. };
  31624. Region.prototype.cloneShallow = function (name) {
  31625. name == null && (name = this.name);
  31626. var newRegion = new Region(name, this.geometries, this.center);
  31627. newRegion._rect = this._rect;
  31628. newRegion.transformTo = null; // Simply avoid to be called.
  31629. return newRegion;
  31630. };
  31631. return Region;
  31632. }();
  31633. function decode(json) {
  31634. if (!json.UTF8Encoding) {
  31635. return json;
  31636. }
  31637. var jsonCompressed = json;
  31638. var encodeScale = jsonCompressed.UTF8Scale;
  31639. if (encodeScale == null) {
  31640. encodeScale = 1024;
  31641. }
  31642. var features = jsonCompressed.features;
  31643. for (var f = 0; f < features.length; f++) {
  31644. var feature = features[f];
  31645. var geometry = feature.geometry;
  31646. if (geometry.type === 'Polygon') {
  31647. var coordinates = geometry.coordinates;
  31648. for (var c = 0; c < coordinates.length; c++) {
  31649. coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale);
  31650. }
  31651. } else if (geometry.type === 'MultiPolygon') {
  31652. var coordinates = geometry.coordinates;
  31653. for (var c = 0; c < coordinates.length; c++) {
  31654. var coordinate = coordinates[c];
  31655. for (var c2 = 0; c2 < coordinate.length; c2++) {
  31656. coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale);
  31657. }
  31658. }
  31659. }
  31660. } // Has been decoded
  31661. jsonCompressed.UTF8Encoding = false;
  31662. return jsonCompressed;
  31663. }
  31664. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  31665. var result = [];
  31666. var prevX = encodeOffsets[0];
  31667. var prevY = encodeOffsets[1];
  31668. for (var i = 0; i < coordinate.length; i += 2) {
  31669. var x = coordinate.charCodeAt(i) - 64;
  31670. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  31671. x = x >> 1 ^ -(x & 1);
  31672. y = y >> 1 ^ -(y & 1); // Delta deocding
  31673. x += prevX;
  31674. y += prevY;
  31675. prevX = x;
  31676. prevY = y; // Dequantize
  31677. result.push([x / encodeScale, y / encodeScale]);
  31678. }
  31679. return result;
  31680. }
  31681. function parseGeoJSON(geoJson, nameProperty) {
  31682. geoJson = decode(geoJson);
  31683. return map(filter(geoJson.features, function (featureObj) {
  31684. // Output of mapshaper may have geometry null
  31685. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  31686. }), function (featureObj) {
  31687. var properties = featureObj.properties;
  31688. var geo = featureObj.geometry;
  31689. var geometries = [];
  31690. if (geo.type === 'Polygon') {
  31691. var coordinates = geo.coordinates;
  31692. geometries.push({
  31693. type: 'polygon',
  31694. // According to the GeoJSON specification.
  31695. // First must be exterior, and the rest are all interior(holes).
  31696. exterior: coordinates[0],
  31697. interiors: coordinates.slice(1)
  31698. });
  31699. }
  31700. if (geo.type === 'MultiPolygon') {
  31701. var coordinates = geo.coordinates;
  31702. each(coordinates, function (item) {
  31703. if (item[0]) {
  31704. geometries.push({
  31705. type: 'polygon',
  31706. exterior: item[0],
  31707. interiors: item.slice(1)
  31708. });
  31709. }
  31710. });
  31711. }
  31712. var region = new Region(properties[nameProperty || 'name'], geometries, properties.cp);
  31713. region.properties = properties;
  31714. return region;
  31715. });
  31716. }
  31717. var number = /*#__PURE__*/Object.freeze({
  31718. __proto__: null,
  31719. linearMap: linearMap,
  31720. round: round,
  31721. asc: asc,
  31722. getPrecision: getPrecision,
  31723. getPrecisionSafe: getPrecisionSafe,
  31724. getPixelPrecision: getPixelPrecision,
  31725. getPercentWithPrecision: getPercentWithPrecision,
  31726. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  31727. remRadian: remRadian,
  31728. isRadianAroundZero: isRadianAroundZero,
  31729. parseDate: parseDate,
  31730. quantity: quantity,
  31731. quantityExponent: quantityExponent,
  31732. nice: nice,
  31733. quantile: quantile,
  31734. reformIntervals: reformIntervals,
  31735. isNumeric: isNumeric,
  31736. numericToNumber: numericToNumber
  31737. });
  31738. var time = /*#__PURE__*/Object.freeze({
  31739. __proto__: null,
  31740. parse: parseDate,
  31741. format: format
  31742. });
  31743. var graphic$1 = /*#__PURE__*/Object.freeze({
  31744. __proto__: null,
  31745. extendShape: extendShape,
  31746. extendPath: extendPath,
  31747. makePath: makePath,
  31748. makeImage: makeImage,
  31749. mergePath: mergePath$1,
  31750. resizePath: resizePath,
  31751. createIcon: createIcon,
  31752. updateProps: updateProps,
  31753. initProps: initProps,
  31754. getTransform: getTransform,
  31755. clipPointsByRect: clipPointsByRect,
  31756. clipRectByRect: clipRectByRect,
  31757. registerShape: registerShape,
  31758. getShapeClass: getShapeClass,
  31759. Group: Group,
  31760. Image: ZRImage,
  31761. Text: ZRText,
  31762. Circle: Circle,
  31763. Ellipse: Ellipse,
  31764. Sector: Sector,
  31765. Ring: Ring,
  31766. Polygon: Polygon,
  31767. Polyline: Polyline,
  31768. Rect: Rect,
  31769. Line: Line,
  31770. BezierCurve: BezierCurve,
  31771. Arc: Arc,
  31772. IncrementalDisplayable: IncrementalDisplayable,
  31773. CompoundPath: CompoundPath,
  31774. LinearGradient: LinearGradient,
  31775. RadialGradient: RadialGradient,
  31776. BoundingRect: BoundingRect
  31777. });
  31778. var format$1 = /*#__PURE__*/Object.freeze({
  31779. __proto__: null,
  31780. addCommas: addCommas,
  31781. toCamelCase: toCamelCase,
  31782. normalizeCssArray: normalizeCssArray$1,
  31783. encodeHTML: encodeHTML,
  31784. formatTpl: formatTpl,
  31785. getTooltipMarker: getTooltipMarker,
  31786. formatTime: formatTime,
  31787. capitalFirst: capitalFirst,
  31788. truncateText: truncateText,
  31789. getTextRect: getTextRect
  31790. });
  31791. var util$1 = /*#__PURE__*/Object.freeze({
  31792. __proto__: null,
  31793. map: map,
  31794. each: each,
  31795. indexOf: indexOf,
  31796. inherits: inherits,
  31797. reduce: reduce,
  31798. filter: filter,
  31799. bind: bind,
  31800. curry: curry,
  31801. isArray: isArray,
  31802. isString: isString,
  31803. isObject: isObject,
  31804. isFunction: isFunction,
  31805. extend: extend,
  31806. defaults: defaults,
  31807. clone: clone,
  31808. merge: merge
  31809. });
  31810. var inner$4 = makeInner();
  31811. function createAxisLabels(axis) {
  31812. // Only ordinal scale support tick interval
  31813. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  31814. }
  31815. /**
  31816. * @param {module:echats/coord/Axis} axis
  31817. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  31818. * @return {Object} {
  31819. * ticks: Array.<number>
  31820. * tickCategoryInterval: number
  31821. * }
  31822. */
  31823. function createAxisTicks(axis, tickModel) {
  31824. // Only ordinal scale support tick interval
  31825. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  31826. ticks: map(axis.scale.getTicks(), function (tick) {
  31827. return tick.value;
  31828. })
  31829. };
  31830. }
  31831. function makeCategoryLabels(axis) {
  31832. var labelModel = axis.getLabelModel();
  31833. var result = makeCategoryLabelsActually(axis, labelModel);
  31834. return !labelModel.get('show') || axis.scale.isBlank() ? {
  31835. labels: [],
  31836. labelCategoryInterval: result.labelCategoryInterval
  31837. } : result;
  31838. }
  31839. function makeCategoryLabelsActually(axis, labelModel) {
  31840. var labelsCache = getListCache(axis, 'labels');
  31841. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  31842. var result = listCacheGet(labelsCache, optionLabelInterval);
  31843. if (result) {
  31844. return result;
  31845. }
  31846. var labels;
  31847. var numericLabelInterval;
  31848. if (isFunction(optionLabelInterval)) {
  31849. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  31850. } else {
  31851. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  31852. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  31853. } // Cache to avoid calling interval function repeatly.
  31854. return listCacheSet(labelsCache, optionLabelInterval, {
  31855. labels: labels,
  31856. labelCategoryInterval: numericLabelInterval
  31857. });
  31858. }
  31859. function makeCategoryTicks(axis, tickModel) {
  31860. var ticksCache = getListCache(axis, 'ticks');
  31861. var optionTickInterval = getOptionCategoryInterval(tickModel);
  31862. var result = listCacheGet(ticksCache, optionTickInterval);
  31863. if (result) {
  31864. return result;
  31865. }
  31866. var ticks;
  31867. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  31868. // we should not return all ticks.
  31869. if (!tickModel.get('show') || axis.scale.isBlank()) {
  31870. ticks = [];
  31871. }
  31872. if (isFunction(optionTickInterval)) {
  31873. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  31874. } // Always use label interval by default despite label show. Consider this
  31875. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  31876. // labels. `splitLine` and `axisTick` should be consistent in this case.
  31877. else if (optionTickInterval === 'auto') {
  31878. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  31879. tickCategoryInterval = labelsResult.labelCategoryInterval;
  31880. ticks = map(labelsResult.labels, function (labelItem) {
  31881. return labelItem.tickValue;
  31882. });
  31883. } else {
  31884. tickCategoryInterval = optionTickInterval;
  31885. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  31886. } // Cache to avoid calling interval function repeatly.
  31887. return listCacheSet(ticksCache, optionTickInterval, {
  31888. ticks: ticks,
  31889. tickCategoryInterval: tickCategoryInterval
  31890. });
  31891. }
  31892. function makeRealNumberLabels(axis) {
  31893. var ticks = axis.scale.getTicks();
  31894. var labelFormatter = makeLabelFormatter(axis);
  31895. return {
  31896. labels: map(ticks, function (tick, idx) {
  31897. return {
  31898. formattedLabel: labelFormatter(tick, idx),
  31899. rawLabel: axis.scale.getLabel(tick),
  31900. tickValue: tick.value
  31901. };
  31902. })
  31903. };
  31904. }
  31905. function getListCache(axis, prop) {
  31906. // Because key can be funciton, and cache size always be small, we use array cache.
  31907. return inner$4(axis)[prop] || (inner$4(axis)[prop] = []);
  31908. }
  31909. function listCacheGet(cache, key) {
  31910. for (var i = 0; i < cache.length; i++) {
  31911. if (cache[i].key === key) {
  31912. return cache[i].value;
  31913. }
  31914. }
  31915. }
  31916. function listCacheSet(cache, key, value) {
  31917. cache.push({
  31918. key: key,
  31919. value: value
  31920. });
  31921. return value;
  31922. }
  31923. function makeAutoCategoryInterval(axis) {
  31924. var result = inner$4(axis).autoInterval;
  31925. return result != null ? result : inner$4(axis).autoInterval = axis.calculateCategoryInterval();
  31926. }
  31927. /**
  31928. * Calculate interval for category axis ticks and labels.
  31929. * To get precise result, at least one of `getRotate` and `isHorizontal`
  31930. * should be implemented in axis.
  31931. */
  31932. function calculateCategoryInterval(axis) {
  31933. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  31934. var labelFormatter = makeLabelFormatter(axis);
  31935. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  31936. var ordinalScale = axis.scale;
  31937. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  31938. // avoid generating a long array by `getTicks`
  31939. // in large category data case.
  31940. var tickCount = ordinalScale.count();
  31941. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  31942. return 0;
  31943. }
  31944. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  31945. if (tickCount > 40) {
  31946. step = Math.max(1, Math.floor(tickCount / 40));
  31947. }
  31948. var tickValue = ordinalExtent[0];
  31949. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  31950. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  31951. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  31952. var maxW = 0;
  31953. var maxH = 0; // Caution: Performance sensitive for large category data.
  31954. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  31955. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  31956. var width = 0;
  31957. var height = 0; // Not precise, do not consider align and vertical align
  31958. // and each distance from axis line yet.
  31959. var rect = getBoundingRect(labelFormatter({
  31960. value: tickValue
  31961. }), params.font, 'center', 'top'); // Magic number
  31962. width = rect.width * 1.3;
  31963. height = rect.height * 1.3; // Min size, void long loop.
  31964. maxW = Math.max(maxW, width, 7);
  31965. maxH = Math.max(maxH, height, 7);
  31966. }
  31967. var dw = maxW / unitW;
  31968. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  31969. isNaN(dw) && (dw = Infinity);
  31970. isNaN(dh) && (dh = Infinity);
  31971. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  31972. var cache = inner$4(axis.model);
  31973. var axisExtent = axis.getExtent();
  31974. var lastAutoInterval = cache.lastAutoInterval;
  31975. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  31976. // otherwise the calculated interval might jitter when the zoom
  31977. // window size is close to the interval-changing size.
  31978. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  31979. // The jitter will cause that sometimes the displayed labels are
  31980. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  31981. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  31982. // point is not the same when zooming in or zooming out.
  31983. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  31984. // be used. Otherwise some hiden labels might not be shown again.
  31985. && cache.axisExtent0 === axisExtent[0] && cache.axisExtent1 === axisExtent[1]) {
  31986. interval = lastAutoInterval;
  31987. } // Only update cache if cache not used, otherwise the
  31988. // changing of interval is too insensitive.
  31989. else {
  31990. cache.lastTickCount = tickCount;
  31991. cache.lastAutoInterval = interval;
  31992. cache.axisExtent0 = axisExtent[0];
  31993. cache.axisExtent1 = axisExtent[1];
  31994. }
  31995. return interval;
  31996. }
  31997. function fetchAutoCategoryIntervalCalculationParams(axis) {
  31998. var labelModel = axis.getLabelModel();
  31999. return {
  32000. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  32001. labelRotate: labelModel.get('rotate') || 0,
  32002. font: labelModel.getFont()
  32003. };
  32004. }
  32005. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  32006. var labelFormatter = makeLabelFormatter(axis);
  32007. var ordinalScale = axis.scale;
  32008. var ordinalExtent = ordinalScale.getExtent();
  32009. var labelModel = axis.getLabelModel();
  32010. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  32011. var step = Math.max((categoryInterval || 0) + 1, 1);
  32012. var startTick = ordinalExtent[0];
  32013. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  32014. // while zooming and moving while interval > 0. Otherwise the selection
  32015. // of displayable ticks and symbols probably keep changing.
  32016. // 3 is empirical value.
  32017. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  32018. startTick = Math.round(Math.ceil(startTick / step) * step);
  32019. } // (1) Only add min max label here but leave overlap checking
  32020. // to render stage, which also ensure the returned list
  32021. // suitable for splitLine and splitArea rendering.
  32022. // (2) Scales except category always contain min max label so
  32023. // do not need to perform this process.
  32024. var showAllLabel = shouldShowAllLabels(axis);
  32025. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  32026. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  32027. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  32028. addItem(ordinalExtent[0]);
  32029. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  32030. var tickValue = startTick;
  32031. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  32032. addItem(tickValue);
  32033. }
  32034. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  32035. addItem(ordinalExtent[1]);
  32036. }
  32037. function addItem(tickValue) {
  32038. var tickObj = {
  32039. value: tickValue
  32040. };
  32041. result.push(onlyTick ? tickValue : {
  32042. formattedLabel: labelFormatter(tickObj),
  32043. rawLabel: ordinalScale.getLabel(tickObj),
  32044. tickValue: tickValue
  32045. });
  32046. }
  32047. return result;
  32048. }
  32049. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  32050. var ordinalScale = axis.scale;
  32051. var labelFormatter = makeLabelFormatter(axis);
  32052. var result = [];
  32053. each(ordinalScale.getTicks(), function (tick) {
  32054. var rawLabel = ordinalScale.getLabel(tick);
  32055. var tickValue = tick.value;
  32056. if (categoryInterval(tick.value, rawLabel)) {
  32057. result.push(onlyTick ? tickValue : {
  32058. formattedLabel: labelFormatter(tick),
  32059. rawLabel: rawLabel,
  32060. tickValue: tickValue
  32061. });
  32062. }
  32063. });
  32064. return result;
  32065. }
  32066. var NORMALIZED_EXTENT = [0, 1];
  32067. /**
  32068. * Base class of Axis.
  32069. */
  32070. var Axis =
  32071. /** @class */
  32072. function () {
  32073. function Axis(dim, scale, extent) {
  32074. this.onBand = false;
  32075. this.inverse = false;
  32076. this.dim = dim;
  32077. this.scale = scale;
  32078. this._extent = extent || [0, 0];
  32079. }
  32080. /**
  32081. * If axis extent contain given coord
  32082. */
  32083. Axis.prototype.contain = function (coord) {
  32084. var extent = this._extent;
  32085. var min = Math.min(extent[0], extent[1]);
  32086. var max = Math.max(extent[0], extent[1]);
  32087. return coord >= min && coord <= max;
  32088. };
  32089. /**
  32090. * If axis extent contain given data
  32091. */
  32092. Axis.prototype.containData = function (data) {
  32093. return this.scale.contain(data);
  32094. };
  32095. /**
  32096. * Get coord extent.
  32097. */
  32098. Axis.prototype.getExtent = function () {
  32099. return this._extent.slice();
  32100. };
  32101. /**
  32102. * Get precision used for formatting
  32103. */
  32104. Axis.prototype.getPixelPrecision = function (dataExtent) {
  32105. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  32106. };
  32107. /**
  32108. * Set coord extent
  32109. */
  32110. Axis.prototype.setExtent = function (start, end) {
  32111. var extent = this._extent;
  32112. extent[0] = start;
  32113. extent[1] = end;
  32114. };
  32115. /**
  32116. * Convert data to coord. Data is the rank if it has an ordinal scale
  32117. */
  32118. Axis.prototype.dataToCoord = function (data, clamp) {
  32119. var extent = this._extent;
  32120. var scale = this.scale;
  32121. data = scale.normalize(data);
  32122. if (this.onBand && scale.type === 'ordinal') {
  32123. extent = extent.slice();
  32124. fixExtentWithBands(extent, scale.count());
  32125. }
  32126. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  32127. };
  32128. /**
  32129. * Convert coord to data. Data is the rank if it has an ordinal scale
  32130. */
  32131. Axis.prototype.coordToData = function (coord, clamp) {
  32132. var extent = this._extent;
  32133. var scale = this.scale;
  32134. if (this.onBand && scale.type === 'ordinal') {
  32135. extent = extent.slice();
  32136. fixExtentWithBands(extent, scale.count());
  32137. }
  32138. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  32139. return this.scale.scale(t);
  32140. };
  32141. /**
  32142. * Convert pixel point to data in axis
  32143. */
  32144. Axis.prototype.pointToData = function (point, clamp) {
  32145. // Should be implemented in derived class if necessary.
  32146. return;
  32147. };
  32148. /**
  32149. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  32150. * `axis.getTicksCoords` considers `onBand`, which is used by
  32151. * `boundaryGap:true` of category axis and splitLine and splitArea.
  32152. * @param opt.tickModel default: axis.model.getModel('axisTick')
  32153. * @param opt.clamp If `true`, the first and the last
  32154. * tick must be at the axis end points. Otherwise, clip ticks
  32155. * that outside the axis extent.
  32156. */
  32157. Axis.prototype.getTicksCoords = function (opt) {
  32158. opt = opt || {};
  32159. var tickModel = opt.tickModel || this.getTickModel();
  32160. var result = createAxisTicks(this, tickModel);
  32161. var ticks = result.ticks;
  32162. var ticksCoords = map(ticks, function (tickVal) {
  32163. return {
  32164. coord: this.dataToCoord(this.scale.type === 'ordinal' ? this.scale.getRawOrdinalNumber(tickVal) : tickVal),
  32165. tickValue: tickVal
  32166. };
  32167. }, this);
  32168. var alignWithLabel = tickModel.get('alignWithLabel');
  32169. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  32170. return ticksCoords;
  32171. };
  32172. Axis.prototype.getMinorTicksCoords = function () {
  32173. if (this.scale.type === 'ordinal') {
  32174. // Category axis doesn't support minor ticks
  32175. return [];
  32176. }
  32177. var minorTickModel = this.model.getModel('minorTick');
  32178. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  32179. if (!(splitNumber > 0 && splitNumber < 100)) {
  32180. splitNumber = 5;
  32181. }
  32182. var minorTicks = this.scale.getMinorTicks(splitNumber);
  32183. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  32184. return map(minorTicksGroup, function (minorTick) {
  32185. return {
  32186. coord: this.dataToCoord(minorTick),
  32187. tickValue: minorTick
  32188. };
  32189. }, this);
  32190. }, this);
  32191. return minorTicksCoords;
  32192. };
  32193. Axis.prototype.getViewLabels = function () {
  32194. return createAxisLabels(this).labels;
  32195. };
  32196. Axis.prototype.getLabelModel = function () {
  32197. return this.model.getModel('axisLabel');
  32198. };
  32199. /**
  32200. * Notice here we only get the default tick model. For splitLine
  32201. * or splitArea, we should pass the splitLineModel or splitAreaModel
  32202. * manually when calling `getTicksCoords`.
  32203. * In GL, this method may be overrided to:
  32204. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  32205. */
  32206. Axis.prototype.getTickModel = function () {
  32207. return this.model.getModel('axisTick');
  32208. };
  32209. /**
  32210. * Get width of band
  32211. */
  32212. Axis.prototype.getBandWidth = function () {
  32213. var axisExtent = this._extent;
  32214. var dataExtent = this.scale.getExtent();
  32215. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  32216. len === 0 && (len = 1);
  32217. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  32218. return Math.abs(size) / len;
  32219. };
  32220. /**
  32221. * Only be called in category axis.
  32222. * Can be overrided, consider other axes like in 3D.
  32223. * @return Auto interval for cateogry axis tick and label
  32224. */
  32225. Axis.prototype.calculateCategoryInterval = function () {
  32226. return calculateCategoryInterval(this);
  32227. };
  32228. return Axis;
  32229. }();
  32230. function fixExtentWithBands(extent, nTick) {
  32231. var size = extent[1] - extent[0];
  32232. var len = nTick;
  32233. var margin = size / len / 2;
  32234. extent[0] += margin;
  32235. extent[1] -= margin;
  32236. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  32237. // |---1---|---2---|---3---|---4---|.
  32238. // So the displayed ticks and splitLine/splitArea should between
  32239. // each data item, otherwise cause misleading (e.g., split tow bars
  32240. // of a single data item when there are two bar series).
  32241. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  32242. // splitLine/spliteArea should layout appropriately corresponding
  32243. // to displayed labels. (So we should not use `getBandWidth` in this
  32244. // case).
  32245. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  32246. var ticksLen = ticksCoords.length;
  32247. if (!axis.onBand || alignWithLabel || !ticksLen) {
  32248. return;
  32249. }
  32250. var axisExtent = axis.getExtent();
  32251. var last;
  32252. var diffSize;
  32253. if (ticksLen === 1) {
  32254. ticksCoords[0].coord = axisExtent[0];
  32255. last = ticksCoords[1] = {
  32256. coord: axisExtent[0]
  32257. };
  32258. } else {
  32259. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  32260. var shift_1 = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  32261. each(ticksCoords, function (ticksItem) {
  32262. ticksItem.coord -= shift_1 / 2;
  32263. });
  32264. var dataExtent = axis.scale.getExtent();
  32265. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  32266. last = {
  32267. coord: ticksCoords[ticksLen - 1].coord + shift_1 * diffSize
  32268. };
  32269. ticksCoords.push(last);
  32270. }
  32271. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  32272. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  32273. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  32274. }
  32275. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  32276. ticksCoords.unshift({
  32277. coord: axisExtent[0]
  32278. });
  32279. }
  32280. if (littleThan(axisExtent[1], last.coord)) {
  32281. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  32282. }
  32283. if (clamp && littleThan(last.coord, axisExtent[1])) {
  32284. ticksCoords.push({
  32285. coord: axisExtent[1]
  32286. });
  32287. }
  32288. function littleThan(a, b) {
  32289. // Avoid rounding error cause calculated tick coord different with extent.
  32290. // It may cause an extra unecessary tick added.
  32291. a = round(a);
  32292. b = round(b);
  32293. return inverse ? a > b : a < b;
  32294. }
  32295. }
  32296. // Should use `ComponentModel.extend` or `class XXXX extend ComponentModel` to create class.
  32297. // Then use `registerComponentModel` in `install` parameter when `use` this extension. For example:
  32298. // class Bar3DModel extends ComponentModel {}
  32299. // export function install(registers) { regsiters.registerComponentModel(Bar3DModel); }
  32300. // echarts.use(install);
  32301. function extendComponentModel(proto) {
  32302. var Model = ComponentModel.extend(proto);
  32303. ComponentModel.registerClass(Model);
  32304. return Model;
  32305. }
  32306. function extendComponentView(proto) {
  32307. var View = ComponentView.extend(proto);
  32308. ComponentView.registerClass(View);
  32309. return View;
  32310. }
  32311. function extendSeriesModel(proto) {
  32312. var Model = SeriesModel.extend(proto);
  32313. SeriesModel.registerClass(Model);
  32314. return Model;
  32315. }
  32316. function extendChartView(proto) {
  32317. var View = ChartView.extend(proto);
  32318. ChartView.registerClass(View);
  32319. return View;
  32320. }
  32321. function createElement(name) {
  32322. return document.createElementNS('http://www.w3.org/2000/svg', name);
  32323. }
  32324. function diff(oldArr, newArr, equals) {
  32325. if (!equals) {
  32326. equals = function (a, b) {
  32327. return a === b;
  32328. };
  32329. }
  32330. oldArr = oldArr.slice();
  32331. newArr = newArr.slice();
  32332. var newLen = newArr.length;
  32333. var oldLen = oldArr.length;
  32334. var editLength = 1;
  32335. var maxEditLength = newLen + oldLen;
  32336. var bestPath = [{ newPos: -1, components: [] }];
  32337. var oldPos = extractCommon(bestPath[0], newArr, oldArr, 0, equals);
  32338. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  32339. var indices = [];
  32340. for (var i = 0; i < newArr.length; i++) {
  32341. indices.push(i);
  32342. }
  32343. return [{
  32344. indices: indices,
  32345. count: newArr.length,
  32346. added: false,
  32347. removed: false
  32348. }];
  32349. }
  32350. function execEditLength() {
  32351. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  32352. var basePath;
  32353. var addPath = bestPath[diagonalPath - 1];
  32354. var removePath = bestPath[diagonalPath + 1];
  32355. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  32356. if (addPath) {
  32357. bestPath[diagonalPath - 1] = undefined;
  32358. }
  32359. var canAdd = addPath && addPath.newPos + 1 < newLen;
  32360. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  32361. if (!canAdd && !canRemove) {
  32362. bestPath[diagonalPath] = undefined;
  32363. continue;
  32364. }
  32365. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  32366. basePath = clonePath(removePath);
  32367. pushComponent(basePath.components, false, true);
  32368. }
  32369. else {
  32370. basePath = addPath;
  32371. basePath.newPos++;
  32372. pushComponent(basePath.components, true, false);
  32373. }
  32374. oldPos = extractCommon(basePath, newArr, oldArr, diagonalPath, equals);
  32375. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  32376. return buildValues(basePath.components);
  32377. }
  32378. else {
  32379. bestPath[diagonalPath] = basePath;
  32380. }
  32381. }
  32382. editLength++;
  32383. }
  32384. while (editLength <= maxEditLength) {
  32385. var ret = execEditLength();
  32386. if (ret) {
  32387. return ret;
  32388. }
  32389. }
  32390. }
  32391. function extractCommon(basePath, newArr, oldArr, diagonalPath, equals) {
  32392. var newLen = newArr.length;
  32393. var oldLen = oldArr.length;
  32394. var newPos = basePath.newPos;
  32395. var oldPos = newPos - diagonalPath;
  32396. var commonCount = 0;
  32397. while (newPos + 1 < newLen && oldPos + 1 < oldLen && equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  32398. newPos++;
  32399. oldPos++;
  32400. commonCount++;
  32401. }
  32402. if (commonCount) {
  32403. basePath.components.push({
  32404. count: commonCount,
  32405. added: false,
  32406. removed: false,
  32407. indices: []
  32408. });
  32409. }
  32410. basePath.newPos = newPos;
  32411. return oldPos;
  32412. }
  32413. function pushComponent(components, added, removed) {
  32414. var last = components[components.length - 1];
  32415. if (last && last.added === added && last.removed === removed) {
  32416. components[components.length - 1] = {
  32417. count: last.count + 1,
  32418. added: added,
  32419. removed: removed,
  32420. indices: []
  32421. };
  32422. }
  32423. else {
  32424. components.push({
  32425. count: 1,
  32426. added: added,
  32427. removed: removed,
  32428. indices: []
  32429. });
  32430. }
  32431. }
  32432. function buildValues(components) {
  32433. var componentPos = 0;
  32434. var componentLen = components.length;
  32435. var newPos = 0;
  32436. var oldPos = 0;
  32437. for (; componentPos < componentLen; componentPos++) {
  32438. var component = components[componentPos];
  32439. if (!component.removed) {
  32440. var indices = [];
  32441. for (var i = newPos; i < newPos + component.count; i++) {
  32442. indices.push(i);
  32443. }
  32444. component.indices = indices;
  32445. newPos += component.count;
  32446. if (!component.added) {
  32447. oldPos += component.count;
  32448. }
  32449. }
  32450. else {
  32451. for (var i = oldPos; i < oldPos + component.count; i++) {
  32452. component.indices.push(i);
  32453. }
  32454. oldPos += component.count;
  32455. }
  32456. }
  32457. return components;
  32458. }
  32459. function clonePath(path) {
  32460. return { newPos: path.newPos, components: path.components.slice(0) };
  32461. }
  32462. function arrayDiff(oldArr, newArr, equal) {
  32463. return diff(oldArr, newArr, equal);
  32464. }
  32465. var NONE = 'none';
  32466. var mathRound = Math.round;
  32467. var mathSin$4 = Math.sin;
  32468. var mathCos$4 = Math.cos;
  32469. var PI$4 = Math.PI;
  32470. var PI2$7 = Math.PI * 2;
  32471. var degree = 180 / PI$4;
  32472. var EPSILON$4 = 1e-4;
  32473. function round3(val) {
  32474. return mathRound(val * 1e3) / 1e3;
  32475. }
  32476. function round4(val) {
  32477. return mathRound(val * 1e4) / 1e4;
  32478. }
  32479. function isAroundZero$1(val) {
  32480. return val < EPSILON$4 && val > -EPSILON$4;
  32481. }
  32482. function pathHasFill(style) {
  32483. var fill = style.fill;
  32484. return fill != null && fill !== NONE;
  32485. }
  32486. function pathHasStroke(style) {
  32487. var stroke = style.stroke;
  32488. return stroke != null && stroke !== NONE;
  32489. }
  32490. function setTransform(svgEl, m) {
  32491. if (m) {
  32492. attr(svgEl, 'transform', 'matrix('
  32493. + round3(m[0]) + ','
  32494. + round3(m[1]) + ','
  32495. + round3(m[2]) + ','
  32496. + round3(m[3]) + ','
  32497. + round4(m[4]) + ','
  32498. + round4(m[5])
  32499. + ')');
  32500. }
  32501. }
  32502. function attr(el, key, val) {
  32503. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  32504. el.setAttribute(key, val);
  32505. }
  32506. }
  32507. function attrXLink(el, key, val) {
  32508. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  32509. }
  32510. function attrXML(el, key, val) {
  32511. el.setAttributeNS('http://www.w3.org/XML/1998/namespace', key, val);
  32512. }
  32513. function bindStyle(svgEl, style, el) {
  32514. var opacity = style.opacity == null ? 1 : style.opacity;
  32515. if (el instanceof ZRImage) {
  32516. svgEl.style.opacity = opacity + '';
  32517. return;
  32518. }
  32519. if (pathHasFill(style)) {
  32520. var fill = style.fill;
  32521. fill = fill === 'transparent' ? NONE : fill;
  32522. attr(svgEl, 'fill', fill);
  32523. attr(svgEl, 'fill-opacity', (style.fillOpacity != null ? style.fillOpacity * opacity : opacity) + '');
  32524. }
  32525. else {
  32526. attr(svgEl, 'fill', NONE);
  32527. }
  32528. if (pathHasStroke(style)) {
  32529. var stroke = style.stroke;
  32530. stroke = stroke === 'transparent' ? NONE : stroke;
  32531. attr(svgEl, 'stroke', stroke);
  32532. var strokeWidth = style.lineWidth;
  32533. var strokeScale_1 = style.strokeNoScale
  32534. ? el.getLineScale()
  32535. : 1;
  32536. attr(svgEl, 'stroke-width', (strokeScale_1 ? strokeWidth / strokeScale_1 : 0) + '');
  32537. attr(svgEl, 'paint-order', style.strokeFirst ? 'stroke' : 'fill');
  32538. attr(svgEl, 'stroke-opacity', (style.strokeOpacity != null ? style.strokeOpacity * opacity : opacity) + '');
  32539. var lineDash = style.lineDash && strokeWidth > 0 && normalizeLineDash(style.lineDash, strokeWidth);
  32540. if (lineDash) {
  32541. var lineDashOffset = style.lineDashOffset;
  32542. if (strokeScale_1 && strokeScale_1 !== 1) {
  32543. lineDash = map(lineDash, function (rawVal) {
  32544. return rawVal / strokeScale_1;
  32545. });
  32546. if (lineDashOffset) {
  32547. lineDashOffset /= strokeScale_1;
  32548. lineDashOffset = mathRound(lineDashOffset);
  32549. }
  32550. }
  32551. attr(svgEl, 'stroke-dasharray', lineDash.join(','));
  32552. attr(svgEl, 'stroke-dashoffset', (lineDashOffset || 0) + '');
  32553. }
  32554. else {
  32555. attr(svgEl, 'stroke-dasharray', '');
  32556. }
  32557. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  32558. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  32559. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit + '');
  32560. }
  32561. else {
  32562. attr(svgEl, 'stroke', NONE);
  32563. }
  32564. }
  32565. var SVGPathRebuilder = (function () {
  32566. function SVGPathRebuilder() {
  32567. }
  32568. SVGPathRebuilder.prototype.reset = function () {
  32569. this._d = [];
  32570. this._str = '';
  32571. };
  32572. SVGPathRebuilder.prototype.moveTo = function (x, y) {
  32573. this._add('M', x, y);
  32574. };
  32575. SVGPathRebuilder.prototype.lineTo = function (x, y) {
  32576. this._add('L', x, y);
  32577. };
  32578. SVGPathRebuilder.prototype.bezierCurveTo = function (x, y, x2, y2, x3, y3) {
  32579. this._add('C', x, y, x2, y2, x3, y3);
  32580. };
  32581. SVGPathRebuilder.prototype.quadraticCurveTo = function (x, y, x2, y2) {
  32582. this._add('Q', x, y, x2, y2);
  32583. };
  32584. SVGPathRebuilder.prototype.arc = function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  32585. this.ellipse(cx, cy, r, r, 0, startAngle, endAngle, anticlockwise);
  32586. };
  32587. SVGPathRebuilder.prototype.ellipse = function (cx, cy, rx, ry, psi, startAngle, endAngle, anticlockwise) {
  32588. var firstCmd = this._d.length === 0;
  32589. var dTheta = endAngle - startAngle;
  32590. var clockwise = !anticlockwise;
  32591. var dThetaPositive = Math.abs(dTheta);
  32592. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  32593. || (clockwise ? dTheta >= PI2$7 : -dTheta >= PI2$7);
  32594. var unifiedTheta = dTheta > 0 ? dTheta % PI2$7 : (dTheta % PI2$7 + PI2$7);
  32595. var large = false;
  32596. if (isCircle) {
  32597. large = true;
  32598. }
  32599. else if (isAroundZero$1(dThetaPositive)) {
  32600. large = false;
  32601. }
  32602. else {
  32603. large = (unifiedTheta >= PI$4) === !!clockwise;
  32604. }
  32605. var x0 = round4(cx + rx * mathCos$4(startAngle));
  32606. var y0 = round4(cy + ry * mathSin$4(startAngle));
  32607. if (isCircle) {
  32608. if (clockwise) {
  32609. dTheta = PI2$7 - 1e-4;
  32610. }
  32611. else {
  32612. dTheta = -PI2$7 + 1e-4;
  32613. }
  32614. large = true;
  32615. if (firstCmd) {
  32616. this._d.push('M', x0, y0);
  32617. }
  32618. }
  32619. var x = round4(cx + rx * mathCos$4(startAngle + dTheta));
  32620. var y = round4(cy + ry * mathSin$4(startAngle + dTheta));
  32621. if (isNaN(x0) || isNaN(y0) || isNaN(rx) || isNaN(ry) || isNaN(psi) || isNaN(degree) || isNaN(x) || isNaN(y)) {
  32622. return '';
  32623. }
  32624. this._d.push('A', round4(rx), round4(ry), mathRound(psi * degree), +large, +clockwise, x, y);
  32625. };
  32626. SVGPathRebuilder.prototype.rect = function (x, y, w, h) {
  32627. this._add('M', x, y);
  32628. this._add('L', x + w, y);
  32629. this._add('L', x + w, y + h);
  32630. this._add('L', x, y + h);
  32631. this._add('L', x, y);
  32632. };
  32633. SVGPathRebuilder.prototype.closePath = function () {
  32634. if (this._d.length > 0) {
  32635. this._add('Z');
  32636. }
  32637. };
  32638. SVGPathRebuilder.prototype._add = function (cmd, a, b, c, d, e, f, g, h) {
  32639. this._d.push(cmd);
  32640. for (var i = 1; i < arguments.length; i++) {
  32641. var val = arguments[i];
  32642. if (isNaN(val)) {
  32643. this._invalid = true;
  32644. return;
  32645. }
  32646. this._d.push(round4(val));
  32647. }
  32648. };
  32649. SVGPathRebuilder.prototype.generateStr = function () {
  32650. this._str = this._invalid ? '' : this._d.join(' ');
  32651. this._d = [];
  32652. };
  32653. SVGPathRebuilder.prototype.getStr = function () {
  32654. return this._str;
  32655. };
  32656. return SVGPathRebuilder;
  32657. }());
  32658. var svgPath = {
  32659. brush: function (el) {
  32660. var style = el.style;
  32661. var svgEl = el.__svgEl;
  32662. if (!svgEl) {
  32663. svgEl = createElement('path');
  32664. el.__svgEl = svgEl;
  32665. }
  32666. if (!el.path) {
  32667. el.createPathProxy();
  32668. }
  32669. var path = el.path;
  32670. if (el.shapeChanged()) {
  32671. path.beginPath();
  32672. el.buildPath(path, el.shape);
  32673. el.pathUpdated();
  32674. }
  32675. var pathVersion = path.getVersion();
  32676. var elExt = el;
  32677. var svgPathBuilder = elExt.__svgPathBuilder;
  32678. if (elExt.__svgPathVersion !== pathVersion || !svgPathBuilder || el.style.strokePercent < 1) {
  32679. if (!svgPathBuilder) {
  32680. svgPathBuilder = elExt.__svgPathBuilder = new SVGPathRebuilder();
  32681. }
  32682. svgPathBuilder.reset();
  32683. path.rebuildPath(svgPathBuilder, el.style.strokePercent);
  32684. svgPathBuilder.generateStr();
  32685. elExt.__svgPathVersion = pathVersion;
  32686. }
  32687. attr(svgEl, 'd', svgPathBuilder.getStr());
  32688. bindStyle(svgEl, style, el);
  32689. setTransform(svgEl, el.transform);
  32690. }
  32691. };
  32692. var svgImage = {
  32693. brush: function (el) {
  32694. var style = el.style;
  32695. var image = style.image;
  32696. if (image instanceof HTMLImageElement) {
  32697. image = image.src;
  32698. }
  32699. else if (image instanceof HTMLCanvasElement) {
  32700. image = image.toDataURL();
  32701. }
  32702. if (!image) {
  32703. return;
  32704. }
  32705. var x = style.x || 0;
  32706. var y = style.y || 0;
  32707. var dw = style.width;
  32708. var dh = style.height;
  32709. var svgEl = el.__svgEl;
  32710. if (!svgEl) {
  32711. svgEl = createElement('image');
  32712. el.__svgEl = svgEl;
  32713. }
  32714. if (image !== el.__imageSrc) {
  32715. attrXLink(svgEl, 'href', image);
  32716. el.__imageSrc = image;
  32717. }
  32718. attr(svgEl, 'width', dw + '');
  32719. attr(svgEl, 'height', dh + '');
  32720. attr(svgEl, 'x', x + '');
  32721. attr(svgEl, 'y', y + '');
  32722. bindStyle(svgEl, style, el);
  32723. setTransform(svgEl, el.transform);
  32724. }
  32725. };
  32726. var TEXT_ALIGN_TO_ANCHOR = {
  32727. left: 'start',
  32728. right: 'end',
  32729. center: 'middle',
  32730. middle: 'middle'
  32731. };
  32732. function adjustTextY$1(y, lineHeight, textBaseline) {
  32733. if (textBaseline === 'top') {
  32734. y += lineHeight / 2;
  32735. }
  32736. else if (textBaseline === 'bottom') {
  32737. y -= lineHeight / 2;
  32738. }
  32739. return y;
  32740. }
  32741. var svgText = {
  32742. brush: function (el) {
  32743. var style = el.style;
  32744. var text = style.text;
  32745. text != null && (text += '');
  32746. if (!text || isNaN(style.x) || isNaN(style.y)) {
  32747. return;
  32748. }
  32749. var textSvgEl = el.__svgEl;
  32750. if (!textSvgEl) {
  32751. textSvgEl = createElement('text');
  32752. attrXML(textSvgEl, 'xml:space', 'preserve');
  32753. el.__svgEl = textSvgEl;
  32754. }
  32755. var font = style.font || DEFAULT_FONT;
  32756. var textSvgElStyle = textSvgEl.style;
  32757. textSvgElStyle.font = font;
  32758. textSvgEl.textContent = text;
  32759. bindStyle(textSvgEl, style, el);
  32760. setTransform(textSvgEl, el.transform);
  32761. var x = style.x || 0;
  32762. var y = adjustTextY$1(style.y || 0, getLineHeight(font), style.textBaseline);
  32763. var textAlign = TEXT_ALIGN_TO_ANCHOR[style.textAlign]
  32764. || style.textAlign;
  32765. attr(textSvgEl, 'dominant-baseline', 'central');
  32766. attr(textSvgEl, 'text-anchor', textAlign);
  32767. attr(textSvgEl, 'x', x + '');
  32768. attr(textSvgEl, 'y', y + '');
  32769. }
  32770. };
  32771. var MARK_UNUSED = '0';
  32772. var MARK_USED = '1';
  32773. var Definable = (function () {
  32774. function Definable(zrId, svgRoot, tagNames, markLabel, domName) {
  32775. this.nextId = 0;
  32776. this._domName = '_dom';
  32777. this.createElement = createElement;
  32778. this._zrId = zrId;
  32779. this._svgRoot = svgRoot;
  32780. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  32781. this._markLabel = markLabel;
  32782. if (domName) {
  32783. this._domName = domName;
  32784. }
  32785. }
  32786. Definable.prototype.getDefs = function (isForceCreating) {
  32787. var svgRoot = this._svgRoot;
  32788. var defs = this._svgRoot.getElementsByTagName('defs');
  32789. if (defs.length === 0) {
  32790. if (isForceCreating) {
  32791. var defs_1 = svgRoot.insertBefore(this.createElement('defs'), svgRoot.firstChild);
  32792. if (!defs_1.contains) {
  32793. defs_1.contains = function (el) {
  32794. var children = defs_1.children;
  32795. if (!children) {
  32796. return false;
  32797. }
  32798. for (var i = children.length - 1; i >= 0; --i) {
  32799. if (children[i] === el) {
  32800. return true;
  32801. }
  32802. }
  32803. return false;
  32804. };
  32805. }
  32806. return defs_1;
  32807. }
  32808. else {
  32809. return null;
  32810. }
  32811. }
  32812. else {
  32813. return defs[0];
  32814. }
  32815. };
  32816. Definable.prototype.doUpdate = function (target, onUpdate) {
  32817. if (!target) {
  32818. return;
  32819. }
  32820. var defs = this.getDefs(false);
  32821. if (target[this._domName] && defs.contains(target[this._domName])) {
  32822. if (typeof onUpdate === 'function') {
  32823. onUpdate(target);
  32824. }
  32825. }
  32826. else {
  32827. var dom = this.add(target);
  32828. if (dom) {
  32829. target[this._domName] = dom;
  32830. }
  32831. }
  32832. };
  32833. Definable.prototype.add = function (target) {
  32834. return null;
  32835. };
  32836. Definable.prototype.addDom = function (dom) {
  32837. var defs = this.getDefs(true);
  32838. if (dom.parentNode !== defs) {
  32839. defs.appendChild(dom);
  32840. }
  32841. };
  32842. Definable.prototype.removeDom = function (target) {
  32843. var defs = this.getDefs(false);
  32844. if (defs && target[this._domName]) {
  32845. defs.removeChild(target[this._domName]);
  32846. target[this._domName] = null;
  32847. }
  32848. };
  32849. Definable.prototype.getDoms = function () {
  32850. var defs = this.getDefs(false);
  32851. if (!defs) {
  32852. return [];
  32853. }
  32854. var doms = [];
  32855. each(this._tagNames, function (tagName) {
  32856. var tags = defs.getElementsByTagName(tagName);
  32857. for (var i = 0; i < tags.length; i++) {
  32858. doms.push(tags[i]);
  32859. }
  32860. });
  32861. return doms;
  32862. };
  32863. Definable.prototype.markAllUnused = function () {
  32864. var doms = this.getDoms();
  32865. var that = this;
  32866. each(doms, function (dom) {
  32867. dom[that._markLabel] = MARK_UNUSED;
  32868. });
  32869. };
  32870. Definable.prototype.markDomUsed = function (dom) {
  32871. dom && (dom[this._markLabel] = MARK_USED);
  32872. };
  32873. Definable.prototype.markDomUnused = function (dom) {
  32874. dom && (dom[this._markLabel] = MARK_UNUSED);
  32875. };
  32876. Definable.prototype.isDomUnused = function (dom) {
  32877. return dom && dom[this._markLabel] !== MARK_USED;
  32878. };
  32879. Definable.prototype.removeUnused = function () {
  32880. var _this = this;
  32881. var defs = this.getDefs(false);
  32882. if (!defs) {
  32883. return;
  32884. }
  32885. var doms = this.getDoms();
  32886. each(doms, function (dom) {
  32887. if (_this.isDomUnused(dom)) {
  32888. defs.removeChild(dom);
  32889. }
  32890. });
  32891. };
  32892. Definable.prototype.getSvgProxy = function (displayable) {
  32893. if (displayable instanceof Path) {
  32894. return svgPath;
  32895. }
  32896. else if (displayable instanceof ZRImage) {
  32897. return svgImage;
  32898. }
  32899. else if (displayable instanceof TSpan) {
  32900. return svgText;
  32901. }
  32902. else {
  32903. return svgPath;
  32904. }
  32905. };
  32906. Definable.prototype.getSvgElement = function (displayable) {
  32907. return displayable.__svgEl;
  32908. };
  32909. return Definable;
  32910. }());
  32911. function isLinearGradient(value) {
  32912. return value.type === 'linear';
  32913. }
  32914. function isRadialGradient(value) {
  32915. return value.type === 'radial';
  32916. }
  32917. function isGradient(value) {
  32918. return value && (value.type === 'linear'
  32919. || value.type === 'radial');
  32920. }
  32921. var GradientManager = (function (_super) {
  32922. __extends(GradientManager, _super);
  32923. function GradientManager(zrId, svgRoot) {
  32924. return _super.call(this, zrId, svgRoot, ['linearGradient', 'radialGradient'], '__gradient_in_use__') || this;
  32925. }
  32926. GradientManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  32927. if (displayable && displayable.style) {
  32928. var that_1 = this;
  32929. each(['fill', 'stroke'], function (fillOrStroke) {
  32930. var value = displayable.style[fillOrStroke];
  32931. if (isGradient(value)) {
  32932. var gradient = value;
  32933. var defs = that_1.getDefs(true);
  32934. var dom = void 0;
  32935. if (gradient.__dom) {
  32936. dom = gradient.__dom;
  32937. if (!defs.contains(gradient.__dom)) {
  32938. that_1.addDom(dom);
  32939. }
  32940. }
  32941. else {
  32942. dom = that_1.add(gradient);
  32943. }
  32944. that_1.markUsed(displayable);
  32945. var id = dom.getAttribute('id');
  32946. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  32947. }
  32948. });
  32949. }
  32950. };
  32951. GradientManager.prototype.add = function (gradient) {
  32952. var dom;
  32953. if (isLinearGradient(gradient)) {
  32954. dom = this.createElement('linearGradient');
  32955. }
  32956. else if (isRadialGradient(gradient)) {
  32957. dom = this.createElement('radialGradient');
  32958. }
  32959. else {
  32960. logError('Illegal gradient type.');
  32961. return null;
  32962. }
  32963. gradient.id = gradient.id || this.nextId++;
  32964. dom.setAttribute('id', 'zr' + this._zrId
  32965. + '-gradient-' + gradient.id);
  32966. this.updateDom(gradient, dom);
  32967. this.addDom(dom);
  32968. return dom;
  32969. };
  32970. GradientManager.prototype.update = function (gradient) {
  32971. if (!isGradient(gradient)) {
  32972. return;
  32973. }
  32974. var that = this;
  32975. this.doUpdate(gradient, function () {
  32976. var dom = gradient.__dom;
  32977. if (!dom) {
  32978. return;
  32979. }
  32980. var tagName = dom.tagName;
  32981. var type = gradient.type;
  32982. if (type === 'linear' && tagName === 'linearGradient'
  32983. || type === 'radial' && tagName === 'radialGradient') {
  32984. that.updateDom(gradient, gradient.__dom);
  32985. }
  32986. else {
  32987. that.removeDom(gradient);
  32988. that.add(gradient);
  32989. }
  32990. });
  32991. };
  32992. GradientManager.prototype.updateDom = function (gradient, dom) {
  32993. if (isLinearGradient(gradient)) {
  32994. dom.setAttribute('x1', gradient.x + '');
  32995. dom.setAttribute('y1', gradient.y + '');
  32996. dom.setAttribute('x2', gradient.x2 + '');
  32997. dom.setAttribute('y2', gradient.y2 + '');
  32998. }
  32999. else if (isRadialGradient(gradient)) {
  33000. dom.setAttribute('cx', gradient.x + '');
  33001. dom.setAttribute('cy', gradient.y + '');
  33002. dom.setAttribute('r', gradient.r + '');
  33003. }
  33004. else {
  33005. logError('Illegal gradient type.');
  33006. return;
  33007. }
  33008. if (gradient.global) {
  33009. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  33010. }
  33011. else {
  33012. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  33013. }
  33014. dom.innerHTML = '';
  33015. var colors = gradient.colorStops;
  33016. for (var i = 0, len = colors.length; i < len; ++i) {
  33017. var stop_1 = this.createElement('stop');
  33018. stop_1.setAttribute('offset', colors[i].offset * 100 + '%');
  33019. var color$1 = colors[i].color;
  33020. if (color$1.indexOf('rgba') > -1) {
  33021. var opacity = parse(color$1)[3];
  33022. var hex = toHex(color$1);
  33023. stop_1.setAttribute('stop-color', '#' + hex);
  33024. stop_1.setAttribute('stop-opacity', opacity + '');
  33025. }
  33026. else {
  33027. stop_1.setAttribute('stop-color', colors[i].color);
  33028. }
  33029. dom.appendChild(stop_1);
  33030. }
  33031. gradient.__dom = dom;
  33032. };
  33033. GradientManager.prototype.markUsed = function (displayable) {
  33034. if (displayable.style) {
  33035. var gradient = displayable.style.fill;
  33036. if (gradient && gradient.__dom) {
  33037. _super.prototype.markDomUsed.call(this, gradient.__dom);
  33038. }
  33039. gradient = displayable.style.stroke;
  33040. if (gradient && gradient.__dom) {
  33041. _super.prototype.markDomUsed.call(this, gradient.__dom);
  33042. }
  33043. }
  33044. };
  33045. return GradientManager;
  33046. }(Definable));
  33047. function isPattern(value) {
  33048. return value && (!!value.image || !!value.svgElement);
  33049. }
  33050. var patternDomMap = new WeakMap();
  33051. var PatternManager = (function (_super) {
  33052. __extends(PatternManager, _super);
  33053. function PatternManager(zrId, svgRoot) {
  33054. return _super.call(this, zrId, svgRoot, ['pattern'], '__pattern_in_use__') || this;
  33055. }
  33056. PatternManager.prototype.addWithoutUpdate = function (svgElement, displayable) {
  33057. if (displayable && displayable.style) {
  33058. var that_1 = this;
  33059. each(['fill', 'stroke'], function (fillOrStroke) {
  33060. var pattern = displayable.style[fillOrStroke];
  33061. if (isPattern(pattern)) {
  33062. var defs = that_1.getDefs(true);
  33063. var dom = patternDomMap.get(pattern);
  33064. if (dom) {
  33065. if (!defs.contains(dom)) {
  33066. that_1.addDom(dom);
  33067. }
  33068. }
  33069. else {
  33070. dom = that_1.add(pattern);
  33071. }
  33072. that_1.markUsed(displayable);
  33073. var id = dom.getAttribute('id');
  33074. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  33075. }
  33076. });
  33077. }
  33078. };
  33079. PatternManager.prototype.add = function (pattern) {
  33080. if (!isPattern(pattern)) {
  33081. return;
  33082. }
  33083. var dom = this.createElement('pattern');
  33084. pattern.id = pattern.id == null ? this.nextId++ : pattern.id;
  33085. dom.setAttribute('id', 'zr' + this._zrId
  33086. + '-pattern-' + pattern.id);
  33087. dom.setAttribute('x', '0');
  33088. dom.setAttribute('y', '0');
  33089. dom.setAttribute('patternUnits', 'userSpaceOnUse');
  33090. this.updateDom(pattern, dom);
  33091. this.addDom(dom);
  33092. return dom;
  33093. };
  33094. PatternManager.prototype.update = function (pattern) {
  33095. if (!isPattern(pattern)) {
  33096. return;
  33097. }
  33098. var that = this;
  33099. this.doUpdate(pattern, function () {
  33100. var dom = patternDomMap.get(pattern);
  33101. that.updateDom(pattern, dom);
  33102. });
  33103. };
  33104. PatternManager.prototype.updateDom = function (pattern, patternDom) {
  33105. var svgElement = pattern.svgElement;
  33106. if (svgElement instanceof SVGElement) {
  33107. if (svgElement.parentNode !== patternDom) {
  33108. patternDom.innerHTML = '';
  33109. patternDom.appendChild(svgElement);
  33110. patternDom.setAttribute('width', pattern.svgWidth + '');
  33111. patternDom.setAttribute('height', pattern.svgHeight + '');
  33112. }
  33113. }
  33114. else {
  33115. var img = void 0;
  33116. var prevImage = patternDom.getElementsByTagName('image');
  33117. if (prevImage.length) {
  33118. if (pattern.image) {
  33119. img = prevImage[0];
  33120. }
  33121. else {
  33122. patternDom.removeChild(prevImage[0]);
  33123. return;
  33124. }
  33125. }
  33126. else if (pattern.image) {
  33127. img = this.createElement('image');
  33128. }
  33129. if (img) {
  33130. var imageSrc = void 0;
  33131. if (typeof pattern.image === 'string') {
  33132. imageSrc = pattern.image;
  33133. }
  33134. else if (pattern.image instanceof HTMLImageElement) {
  33135. imageSrc = pattern.image.src;
  33136. }
  33137. else if (pattern.image instanceof HTMLCanvasElement) {
  33138. imageSrc = pattern.image.toDataURL();
  33139. }
  33140. if (imageSrc) {
  33141. img.setAttribute('href', imageSrc);
  33142. img.setAttribute('x', '0');
  33143. img.setAttribute('y', '0');
  33144. var hostEl = {
  33145. dirty: function () { }
  33146. };
  33147. var createdImage = createOrUpdateImage(imageSrc, img, hostEl, function (img) {
  33148. patternDom.setAttribute('width', img.width + '');
  33149. patternDom.setAttribute('height', img.height + '');
  33150. });
  33151. if (createdImage && createdImage.width && createdImage.height) {
  33152. patternDom.setAttribute('width', createdImage.width + '');
  33153. patternDom.setAttribute('height', createdImage.height + '');
  33154. }
  33155. patternDom.appendChild(img);
  33156. }
  33157. }
  33158. }
  33159. var x = pattern.x || 0;
  33160. var y = pattern.y || 0;
  33161. var rotation = (pattern.rotation || 0) / Math.PI * 180;
  33162. var scaleX = pattern.scaleX || 1;
  33163. var scaleY = pattern.scaleY || 1;
  33164. var transform = "translate(" + x + ", " + y + ") rotate(" + rotation + ") scale(" + scaleX + ", " + scaleY + ")";
  33165. patternDom.setAttribute('patternTransform', transform);
  33166. patternDomMap.set(pattern, patternDom);
  33167. };
  33168. PatternManager.prototype.markUsed = function (displayable) {
  33169. if (displayable.style) {
  33170. if (isPattern(displayable.style.fill)) {
  33171. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.fill));
  33172. }
  33173. if (isPattern(displayable.style.stroke)) {
  33174. _super.prototype.markDomUsed.call(this, patternDomMap.get(displayable.style.stroke));
  33175. }
  33176. }
  33177. };
  33178. return PatternManager;
  33179. }(Definable));
  33180. function generateClipPathsKey(clipPaths) {
  33181. var key = [];
  33182. if (clipPaths) {
  33183. for (var i = 0; i < clipPaths.length; i++) {
  33184. var clipPath = clipPaths[i];
  33185. key.push(clipPath.id);
  33186. }
  33187. }
  33188. return key.join(',');
  33189. }
  33190. function hasClipPath(displayable) {
  33191. var clipPaths = displayable.__clipPaths;
  33192. return clipPaths && clipPaths.length > 0;
  33193. }
  33194. var ClippathManager = (function (_super) {
  33195. __extends(ClippathManager, _super);
  33196. function ClippathManager(zrId, svgRoot) {
  33197. var _this = _super.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__') || this;
  33198. _this._refGroups = {};
  33199. _this._keyDuplicateCount = {};
  33200. return _this;
  33201. }
  33202. ClippathManager.prototype.markAllUnused = function () {
  33203. _super.prototype.markAllUnused.call(this);
  33204. for (var key in this._refGroups) {
  33205. this.markDomUnused(this._refGroups[key]);
  33206. }
  33207. this._keyDuplicateCount = {};
  33208. };
  33209. ClippathManager.prototype._getClipPathGroup = function (displayable, prevDisplayable) {
  33210. if (!hasClipPath(displayable)) {
  33211. return;
  33212. }
  33213. var clipPaths = displayable.__clipPaths;
  33214. var keyDuplicateCount = this._keyDuplicateCount;
  33215. var clipPathKey = generateClipPathsKey(clipPaths);
  33216. if (isClipPathChanged(clipPaths, prevDisplayable && prevDisplayable.__clipPaths)) {
  33217. keyDuplicateCount[clipPathKey] = keyDuplicateCount[clipPathKey] || 0;
  33218. keyDuplicateCount[clipPathKey] && (clipPathKey += '-' + keyDuplicateCount[clipPathKey]);
  33219. keyDuplicateCount[clipPathKey]++;
  33220. }
  33221. return this._refGroups[clipPathKey]
  33222. || (this._refGroups[clipPathKey] = this.createElement('g'));
  33223. };
  33224. ClippathManager.prototype.update = function (displayable, prevDisplayable) {
  33225. var clipGroup = this._getClipPathGroup(displayable, prevDisplayable);
  33226. if (clipGroup) {
  33227. this.markDomUsed(clipGroup);
  33228. this.updateDom(clipGroup, displayable.__clipPaths);
  33229. }
  33230. return clipGroup;
  33231. };
  33232. ClippathManager.prototype.updateDom = function (parentEl, clipPaths) {
  33233. if (clipPaths && clipPaths.length > 0) {
  33234. var defs = this.getDefs(true);
  33235. var clipPath = clipPaths[0];
  33236. var clipPathEl = void 0;
  33237. var id = void 0;
  33238. if (clipPath._dom) {
  33239. id = clipPath._dom.getAttribute('id');
  33240. clipPathEl = clipPath._dom;
  33241. if (!defs.contains(clipPathEl)) {
  33242. defs.appendChild(clipPathEl);
  33243. }
  33244. }
  33245. else {
  33246. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  33247. ++this.nextId;
  33248. clipPathEl = this.createElement('clipPath');
  33249. clipPathEl.setAttribute('id', id);
  33250. defs.appendChild(clipPathEl);
  33251. clipPath._dom = clipPathEl;
  33252. }
  33253. var svgProxy = this.getSvgProxy(clipPath);
  33254. svgProxy.brush(clipPath);
  33255. var pathEl = this.getSvgElement(clipPath);
  33256. clipPathEl.innerHTML = '';
  33257. clipPathEl.appendChild(pathEl);
  33258. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  33259. if (clipPaths.length > 1) {
  33260. this.updateDom(clipPathEl, clipPaths.slice(1));
  33261. }
  33262. }
  33263. else {
  33264. if (parentEl) {
  33265. parentEl.setAttribute('clip-path', 'none');
  33266. }
  33267. }
  33268. };
  33269. ClippathManager.prototype.markUsed = function (displayable) {
  33270. var _this = this;
  33271. if (displayable.__clipPaths) {
  33272. each(displayable.__clipPaths, function (clipPath) {
  33273. if (clipPath._dom) {
  33274. _super.prototype.markDomUsed.call(_this, clipPath._dom);
  33275. }
  33276. });
  33277. }
  33278. };
  33279. ClippathManager.prototype.removeUnused = function () {
  33280. _super.prototype.removeUnused.call(this);
  33281. var newRefGroupsMap = {};
  33282. for (var key in this._refGroups) {
  33283. var group = this._refGroups[key];
  33284. if (!this.isDomUnused(group)) {
  33285. newRefGroupsMap[key] = group;
  33286. }
  33287. else if (group.parentNode) {
  33288. group.parentNode.removeChild(group);
  33289. }
  33290. }
  33291. this._refGroups = newRefGroupsMap;
  33292. };
  33293. return ClippathManager;
  33294. }(Definable));
  33295. var ShadowManager = (function (_super) {
  33296. __extends(ShadowManager, _super);
  33297. function ShadowManager(zrId, svgRoot) {
  33298. var _this = _super.call(this, zrId, svgRoot, ['filter'], '__filter_in_use__', '_shadowDom') || this;
  33299. _this._shadowDomMap = {};
  33300. _this._shadowDomPool = [];
  33301. return _this;
  33302. }
  33303. ShadowManager.prototype._getFromPool = function () {
  33304. var shadowDom = this._shadowDomPool.pop();
  33305. if (!shadowDom) {
  33306. shadowDom = this.createElement('filter');
  33307. shadowDom.setAttribute('id', 'zr' + this._zrId + '-shadow-' + this.nextId++);
  33308. var domChild = this.createElement('feDropShadow');
  33309. shadowDom.appendChild(domChild);
  33310. this.addDom(shadowDom);
  33311. }
  33312. return shadowDom;
  33313. };
  33314. ShadowManager.prototype.update = function (svgElement, displayable) {
  33315. var style = displayable.style;
  33316. if (hasShadow(style)) {
  33317. var shadowKey = getShadowKey(displayable);
  33318. var shadowDom = displayable._shadowDom = this._shadowDomMap[shadowKey];
  33319. if (!shadowDom) {
  33320. shadowDom = this._getFromPool();
  33321. this._shadowDomMap[shadowKey] = shadowDom;
  33322. }
  33323. this.updateDom(svgElement, displayable, shadowDom);
  33324. }
  33325. else {
  33326. this.remove(svgElement, displayable);
  33327. }
  33328. };
  33329. ShadowManager.prototype.remove = function (svgElement, displayable) {
  33330. if (displayable._shadowDom != null) {
  33331. displayable._shadowDom = null;
  33332. svgElement.style.filter = '';
  33333. }
  33334. };
  33335. ShadowManager.prototype.updateDom = function (svgElement, displayable, shadowDom) {
  33336. var domChild = shadowDom.children[0];
  33337. var style = displayable.style;
  33338. var globalScale = displayable.getGlobalScale();
  33339. var scaleX = globalScale[0];
  33340. var scaleY = globalScale[1];
  33341. if (!scaleX || !scaleY) {
  33342. return;
  33343. }
  33344. var offsetX = style.shadowOffsetX || 0;
  33345. var offsetY = style.shadowOffsetY || 0;
  33346. var blur = style.shadowBlur;
  33347. var color = style.shadowColor;
  33348. domChild.setAttribute('dx', offsetX / scaleX + '');
  33349. domChild.setAttribute('dy', offsetY / scaleY + '');
  33350. domChild.setAttribute('flood-color', color);
  33351. var stdDx = blur / 2 / scaleX;
  33352. var stdDy = blur / 2 / scaleY;
  33353. var stdDeviation = stdDx + ' ' + stdDy;
  33354. domChild.setAttribute('stdDeviation', stdDeviation);
  33355. shadowDom.setAttribute('x', '-100%');
  33356. shadowDom.setAttribute('y', '-100%');
  33357. shadowDom.setAttribute('width', '300%');
  33358. shadowDom.setAttribute('height', '300%');
  33359. displayable._shadowDom = shadowDom;
  33360. var id = shadowDom.getAttribute('id');
  33361. svgElement.style.filter = 'url(#' + id + ')';
  33362. };
  33363. ShadowManager.prototype.removeUnused = function () {
  33364. var defs = this.getDefs(false);
  33365. if (!defs) {
  33366. return;
  33367. }
  33368. var shadowDomsPool = this._shadowDomPool;
  33369. for (var key in this._shadowDomMap) {
  33370. var dom = this._shadowDomMap[key];
  33371. shadowDomsPool.push(dom);
  33372. }
  33373. this._shadowDomMap = {};
  33374. };
  33375. return ShadowManager;
  33376. }(Definable));
  33377. function hasShadow(style) {
  33378. return style
  33379. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY);
  33380. }
  33381. function getShadowKey(displayable) {
  33382. var style = displayable.style;
  33383. var globalScale = displayable.getGlobalScale();
  33384. return [
  33385. style.shadowColor,
  33386. (style.shadowBlur || 0).toFixed(2),
  33387. (style.shadowOffsetX || 0).toFixed(2),
  33388. (style.shadowOffsetY || 0).toFixed(2),
  33389. globalScale[0],
  33390. globalScale[1]
  33391. ].join(',');
  33392. }
  33393. function parseInt10(val) {
  33394. return parseInt(val, 10);
  33395. }
  33396. function getSvgProxy(el) {
  33397. if (el instanceof Path) {
  33398. return svgPath;
  33399. }
  33400. else if (el instanceof ZRImage) {
  33401. return svgImage;
  33402. }
  33403. else if (el instanceof TSpan) {
  33404. return svgText;
  33405. }
  33406. else {
  33407. return svgPath;
  33408. }
  33409. }
  33410. function checkParentAvailable(parent, child) {
  33411. return child && parent && child.parentNode !== parent;
  33412. }
  33413. function insertAfter(parent, child, prevSibling) {
  33414. if (checkParentAvailable(parent, child) && prevSibling) {
  33415. var nextSibling = prevSibling.nextSibling;
  33416. nextSibling ? parent.insertBefore(child, nextSibling)
  33417. : parent.appendChild(child);
  33418. }
  33419. }
  33420. function prepend(parent, child) {
  33421. if (checkParentAvailable(parent, child)) {
  33422. var firstChild = parent.firstChild;
  33423. firstChild ? parent.insertBefore(child, firstChild)
  33424. : parent.appendChild(child);
  33425. }
  33426. }
  33427. function remove(parent, child) {
  33428. if (child && parent && child.parentNode === parent) {
  33429. parent.removeChild(child);
  33430. }
  33431. }
  33432. function removeFromMyParent(child) {
  33433. if (child && child.parentNode) {
  33434. child.parentNode.removeChild(child);
  33435. }
  33436. }
  33437. function getSvgElement(displayable) {
  33438. return displayable.__svgEl;
  33439. }
  33440. var SVGPainter = (function () {
  33441. function SVGPainter(root, storage, opts, zrId) {
  33442. this.type = 'svg';
  33443. this.refreshHover = createMethodNotSupport('refreshHover');
  33444. this.pathToImage = createMethodNotSupport('pathToImage');
  33445. this.configLayer = createMethodNotSupport('configLayer');
  33446. this.root = root;
  33447. this.storage = storage;
  33448. this._opts = opts = extend({}, opts || {});
  33449. var svgDom = createElement('svg');
  33450. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg');
  33451. svgDom.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
  33452. svgDom.setAttribute('version', '1.1');
  33453. svgDom.setAttribute('baseProfile', 'full');
  33454. svgDom.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  33455. var bgRoot = createElement('g');
  33456. svgDom.appendChild(bgRoot);
  33457. var svgRoot = createElement('g');
  33458. svgDom.appendChild(svgRoot);
  33459. this._gradientManager = new GradientManager(zrId, svgRoot);
  33460. this._patternManager = new PatternManager(zrId, svgRoot);
  33461. this._clipPathManager = new ClippathManager(zrId, svgRoot);
  33462. this._shadowManager = new ShadowManager(zrId, svgRoot);
  33463. var viewport = document.createElement('div');
  33464. viewport.style.cssText = 'overflow:hidden;position:relative';
  33465. this._svgDom = svgDom;
  33466. this._svgRoot = svgRoot;
  33467. this._backgroundRoot = bgRoot;
  33468. this._viewport = viewport;
  33469. root.appendChild(viewport);
  33470. viewport.appendChild(svgDom);
  33471. this.resize(opts.width, opts.height);
  33472. this._visibleList = [];
  33473. }
  33474. SVGPainter.prototype.getType = function () {
  33475. return 'svg';
  33476. };
  33477. SVGPainter.prototype.getViewportRoot = function () {
  33478. return this._viewport;
  33479. };
  33480. SVGPainter.prototype.getSvgDom = function () {
  33481. return this._svgDom;
  33482. };
  33483. SVGPainter.prototype.getSvgRoot = function () {
  33484. return this._svgRoot;
  33485. };
  33486. SVGPainter.prototype.getViewportRootOffset = function () {
  33487. var viewportRoot = this.getViewportRoot();
  33488. if (viewportRoot) {
  33489. return {
  33490. offsetLeft: viewportRoot.offsetLeft || 0,
  33491. offsetTop: viewportRoot.offsetTop || 0
  33492. };
  33493. }
  33494. };
  33495. SVGPainter.prototype.refresh = function () {
  33496. var list = this.storage.getDisplayList(true);
  33497. this._paintList(list);
  33498. };
  33499. SVGPainter.prototype.setBackgroundColor = function (backgroundColor) {
  33500. if (this._backgroundRoot && this._backgroundNode) {
  33501. this._backgroundRoot.removeChild(this._backgroundNode);
  33502. }
  33503. var bgNode = createElement('rect');
  33504. bgNode.setAttribute('width', this.getWidth());
  33505. bgNode.setAttribute('height', this.getHeight());
  33506. bgNode.setAttribute('x', 0);
  33507. bgNode.setAttribute('y', 0);
  33508. bgNode.setAttribute('id', 0);
  33509. bgNode.style.fill = backgroundColor;
  33510. this._backgroundRoot.appendChild(bgNode);
  33511. this._backgroundNode = bgNode;
  33512. };
  33513. SVGPainter.prototype.createSVGElement = function (tag) {
  33514. return createElement(tag);
  33515. };
  33516. SVGPainter.prototype.paintOne = function (el) {
  33517. var svgProxy = getSvgProxy(el);
  33518. svgProxy && svgProxy.brush(el);
  33519. return getSvgElement(el);
  33520. };
  33521. SVGPainter.prototype._paintList = function (list) {
  33522. var gradientManager = this._gradientManager;
  33523. var patternManager = this._patternManager;
  33524. var clipPathManager = this._clipPathManager;
  33525. var shadowManager = this._shadowManager;
  33526. gradientManager.markAllUnused();
  33527. patternManager.markAllUnused();
  33528. clipPathManager.markAllUnused();
  33529. shadowManager.markAllUnused();
  33530. var svgRoot = this._svgRoot;
  33531. var visibleList = this._visibleList;
  33532. var listLen = list.length;
  33533. var newVisibleList = [];
  33534. for (var i = 0; i < listLen; i++) {
  33535. var displayable = list[i];
  33536. var svgProxy = getSvgProxy(displayable);
  33537. var svgElement = getSvgElement(displayable);
  33538. if (!displayable.invisible) {
  33539. if (displayable.__dirty || !svgElement) {
  33540. svgProxy && svgProxy.brush(displayable);
  33541. svgElement = getSvgElement(displayable);
  33542. if (svgElement && displayable.style) {
  33543. gradientManager.update(displayable.style.fill);
  33544. gradientManager.update(displayable.style.stroke);
  33545. patternManager.update(displayable.style.fill);
  33546. patternManager.update(displayable.style.stroke);
  33547. shadowManager.update(svgElement, displayable);
  33548. }
  33549. displayable.__dirty = 0;
  33550. }
  33551. if (svgElement) {
  33552. newVisibleList.push(displayable);
  33553. }
  33554. }
  33555. }
  33556. var diff = arrayDiff(visibleList, newVisibleList);
  33557. var prevSvgElement;
  33558. var topPrevSvgElement;
  33559. for (var i = 0; i < diff.length; i++) {
  33560. var item = diff[i];
  33561. if (item.removed) {
  33562. for (var k = 0; k < item.count; k++) {
  33563. var displayable = visibleList[item.indices[k]];
  33564. var svgElement = getSvgElement(displayable);
  33565. hasClipPath(displayable) ? removeFromMyParent(svgElement)
  33566. : remove(svgRoot, svgElement);
  33567. }
  33568. }
  33569. }
  33570. var prevDisplayable;
  33571. var currentClipGroup;
  33572. for (var i = 0; i < diff.length; i++) {
  33573. var item = diff[i];
  33574. if (item.removed) {
  33575. continue;
  33576. }
  33577. for (var k = 0; k < item.count; k++) {
  33578. var displayable = newVisibleList[item.indices[k]];
  33579. var clipGroup = clipPathManager.update(displayable, prevDisplayable);
  33580. if (clipGroup !== currentClipGroup) {
  33581. prevSvgElement = topPrevSvgElement;
  33582. if (clipGroup) {
  33583. prevSvgElement ? insertAfter(svgRoot, clipGroup, prevSvgElement)
  33584. : prepend(svgRoot, clipGroup);
  33585. topPrevSvgElement = clipGroup;
  33586. prevSvgElement = null;
  33587. }
  33588. currentClipGroup = clipGroup;
  33589. }
  33590. var svgElement = getSvgElement(displayable);
  33591. prevSvgElement
  33592. ? insertAfter(currentClipGroup || svgRoot, svgElement, prevSvgElement)
  33593. : prepend(currentClipGroup || svgRoot, svgElement);
  33594. prevSvgElement = svgElement || prevSvgElement;
  33595. if (!currentClipGroup) {
  33596. topPrevSvgElement = prevSvgElement;
  33597. }
  33598. gradientManager.markUsed(displayable);
  33599. gradientManager.addWithoutUpdate(svgElement, displayable);
  33600. patternManager.markUsed(displayable);
  33601. patternManager.addWithoutUpdate(svgElement, displayable);
  33602. clipPathManager.markUsed(displayable);
  33603. prevDisplayable = displayable;
  33604. }
  33605. }
  33606. gradientManager.removeUnused();
  33607. patternManager.removeUnused();
  33608. clipPathManager.removeUnused();
  33609. shadowManager.removeUnused();
  33610. this._visibleList = newVisibleList;
  33611. };
  33612. SVGPainter.prototype._getDefs = function (isForceCreating) {
  33613. var svgRoot = this._svgDom;
  33614. var defs = svgRoot.getElementsByTagName('defs');
  33615. if (defs.length === 0) {
  33616. if (isForceCreating) {
  33617. var defs_1 = svgRoot.insertBefore(createElement('defs'), svgRoot.firstChild);
  33618. if (!defs_1.contains) {
  33619. defs_1.contains = function (el) {
  33620. var children = defs_1.children;
  33621. if (!children) {
  33622. return false;
  33623. }
  33624. for (var i = children.length - 1; i >= 0; --i) {
  33625. if (children[i] === el) {
  33626. return true;
  33627. }
  33628. }
  33629. return false;
  33630. };
  33631. }
  33632. return defs_1;
  33633. }
  33634. else {
  33635. return null;
  33636. }
  33637. }
  33638. else {
  33639. return defs[0];
  33640. }
  33641. };
  33642. SVGPainter.prototype.resize = function (width, height) {
  33643. var viewport = this._viewport;
  33644. viewport.style.display = 'none';
  33645. var opts = this._opts;
  33646. width != null && (opts.width = width);
  33647. height != null && (opts.height = height);
  33648. width = this._getSize(0);
  33649. height = this._getSize(1);
  33650. viewport.style.display = '';
  33651. if (this._width !== width || this._height !== height) {
  33652. this._width = width;
  33653. this._height = height;
  33654. var viewportStyle = viewport.style;
  33655. viewportStyle.width = width + 'px';
  33656. viewportStyle.height = height + 'px';
  33657. var svgRoot = this._svgDom;
  33658. svgRoot.setAttribute('width', width + '');
  33659. svgRoot.setAttribute('height', height + '');
  33660. }
  33661. if (this._backgroundNode) {
  33662. this._backgroundNode.setAttribute('width', width);
  33663. this._backgroundNode.setAttribute('height', height);
  33664. }
  33665. };
  33666. SVGPainter.prototype.getWidth = function () {
  33667. return this._width;
  33668. };
  33669. SVGPainter.prototype.getHeight = function () {
  33670. return this._height;
  33671. };
  33672. SVGPainter.prototype._getSize = function (whIdx) {
  33673. var opts = this._opts;
  33674. var wh = ['width', 'height'][whIdx];
  33675. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  33676. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  33677. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  33678. if (opts[wh] != null && opts[wh] !== 'auto') {
  33679. return parseFloat(opts[wh]);
  33680. }
  33681. var root = this.root;
  33682. var stl = document.defaultView.getComputedStyle(root);
  33683. return ((root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  33684. - (parseInt10(stl[plt]) || 0)
  33685. - (parseInt10(stl[prb]) || 0)) | 0;
  33686. };
  33687. SVGPainter.prototype.dispose = function () {
  33688. this.root.innerHTML = '';
  33689. this._svgRoot
  33690. = this._backgroundRoot
  33691. = this._svgDom
  33692. = this._backgroundNode
  33693. = this._viewport
  33694. = this.storage
  33695. = null;
  33696. };
  33697. SVGPainter.prototype.clear = function () {
  33698. var viewportNode = this._viewport;
  33699. if (viewportNode && viewportNode.parentNode) {
  33700. viewportNode.parentNode.removeChild(viewportNode);
  33701. }
  33702. };
  33703. SVGPainter.prototype.toDataURL = function () {
  33704. this.refresh();
  33705. var svgDom = this._svgDom;
  33706. var outerHTML = svgDom.outerHTML
  33707. || (svgDom.parentNode && svgDom.parentNode).innerHTML;
  33708. var html = encodeURIComponent(outerHTML.replace(/></g, '>\n\r<'));
  33709. return 'data:image/svg+xml;charset=UTF-8,' + html;
  33710. };
  33711. return SVGPainter;
  33712. }());
  33713. function createMethodNotSupport(method) {
  33714. return function () {
  33715. logError('In SVG mode painter not support method "' + method + '"');
  33716. };
  33717. }
  33718. function install(registers) {
  33719. registers.registerPainter('svg', SVGPainter);
  33720. }
  33721. function returnFalse() {
  33722. return false;
  33723. }
  33724. function createDom(id, painter, dpr) {
  33725. var newDom = createCanvas();
  33726. var width = painter.getWidth();
  33727. var height = painter.getHeight();
  33728. var newDomStyle = newDom.style;
  33729. if (newDomStyle) {
  33730. newDomStyle.position = 'absolute';
  33731. newDomStyle.left = '0';
  33732. newDomStyle.top = '0';
  33733. newDomStyle.width = width + 'px';
  33734. newDomStyle.height = height + 'px';
  33735. newDom.setAttribute('data-zr-dom-id', id);
  33736. }
  33737. newDom.width = width * dpr;
  33738. newDom.height = height * dpr;
  33739. return newDom;
  33740. }
  33741. var Layer = (function (_super) {
  33742. __extends(Layer, _super);
  33743. function Layer(id, painter, dpr) {
  33744. var _this = _super.call(this) || this;
  33745. _this.motionBlur = false;
  33746. _this.lastFrameAlpha = 0.7;
  33747. _this.dpr = 1;
  33748. _this.virtual = false;
  33749. _this.config = {};
  33750. _this.incremental = false;
  33751. _this.zlevel = 0;
  33752. _this.maxRepaintRectCount = 5;
  33753. _this.__dirty = true;
  33754. _this.__firstTimePaint = true;
  33755. _this.__used = false;
  33756. _this.__drawIndex = 0;
  33757. _this.__startIndex = 0;
  33758. _this.__endIndex = 0;
  33759. _this.__prevStartIndex = null;
  33760. _this.__prevEndIndex = null;
  33761. var dom;
  33762. dpr = dpr || devicePixelRatio;
  33763. if (typeof id === 'string') {
  33764. dom = createDom(id, painter, dpr);
  33765. }
  33766. else if (isObject(id)) {
  33767. dom = id;
  33768. id = dom.id;
  33769. }
  33770. _this.id = id;
  33771. _this.dom = dom;
  33772. var domStyle = dom.style;
  33773. if (domStyle) {
  33774. dom.onselectstart = returnFalse;
  33775. domStyle.webkitUserSelect = 'none';
  33776. domStyle.userSelect = 'none';
  33777. domStyle.webkitTapHighlightColor = 'rgba(0,0,0,0)';
  33778. domStyle['-webkit-touch-callout'] = 'none';
  33779. domStyle.padding = '0';
  33780. domStyle.margin = '0';
  33781. domStyle.borderWidth = '0';
  33782. }
  33783. _this.domBack = null;
  33784. _this.ctxBack = null;
  33785. _this.painter = painter;
  33786. _this.config = null;
  33787. _this.dpr = dpr;
  33788. return _this;
  33789. }
  33790. Layer.prototype.getElementCount = function () {
  33791. return this.__endIndex - this.__startIndex;
  33792. };
  33793. Layer.prototype.afterBrush = function () {
  33794. this.__prevStartIndex = this.__startIndex;
  33795. this.__prevEndIndex = this.__endIndex;
  33796. };
  33797. Layer.prototype.initContext = function () {
  33798. this.ctx = this.dom.getContext('2d');
  33799. this.ctx.dpr = this.dpr;
  33800. };
  33801. Layer.prototype.setUnpainted = function () {
  33802. this.__firstTimePaint = true;
  33803. };
  33804. Layer.prototype.createBackBuffer = function () {
  33805. var dpr = this.dpr;
  33806. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  33807. this.ctxBack = this.domBack.getContext('2d');
  33808. if (dpr !== 1) {
  33809. this.ctxBack.scale(dpr, dpr);
  33810. }
  33811. };
  33812. Layer.prototype.createRepaintRects = function (displayList, prevList, viewWidth, viewHeight) {
  33813. if (this.__firstTimePaint) {
  33814. this.__firstTimePaint = false;
  33815. return null;
  33816. }
  33817. var mergedRepaintRects = [];
  33818. var maxRepaintRectCount = this.maxRepaintRectCount;
  33819. var full = false;
  33820. var pendingRect = new BoundingRect(0, 0, 0, 0);
  33821. function addRectToMergePool(rect) {
  33822. if (!rect.isFinite() || rect.isZero()) {
  33823. return;
  33824. }
  33825. if (mergedRepaintRects.length === 0) {
  33826. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33827. boundingRect.copy(rect);
  33828. mergedRepaintRects.push(boundingRect);
  33829. }
  33830. else {
  33831. var isMerged = false;
  33832. var minDeltaArea = Infinity;
  33833. var bestRectToMergeIdx = 0;
  33834. for (var i = 0; i < mergedRepaintRects.length; ++i) {
  33835. var mergedRect = mergedRepaintRects[i];
  33836. if (mergedRect.intersect(rect)) {
  33837. var pendingRect_1 = new BoundingRect(0, 0, 0, 0);
  33838. pendingRect_1.copy(mergedRect);
  33839. pendingRect_1.union(rect);
  33840. mergedRepaintRects[i] = pendingRect_1;
  33841. isMerged = true;
  33842. break;
  33843. }
  33844. else if (full) {
  33845. pendingRect.copy(rect);
  33846. pendingRect.union(mergedRect);
  33847. var aArea = rect.width * rect.height;
  33848. var bArea = mergedRect.width * mergedRect.height;
  33849. var pendingArea = pendingRect.width * pendingRect.height;
  33850. var deltaArea = pendingArea - aArea - bArea;
  33851. if (deltaArea < minDeltaArea) {
  33852. minDeltaArea = deltaArea;
  33853. bestRectToMergeIdx = i;
  33854. }
  33855. }
  33856. }
  33857. if (full) {
  33858. mergedRepaintRects[bestRectToMergeIdx].union(rect);
  33859. isMerged = true;
  33860. }
  33861. if (!isMerged) {
  33862. var boundingRect = new BoundingRect(0, 0, 0, 0);
  33863. boundingRect.copy(rect);
  33864. mergedRepaintRects.push(boundingRect);
  33865. }
  33866. if (!full) {
  33867. full = mergedRepaintRects.length >= maxRepaintRectCount;
  33868. }
  33869. }
  33870. }
  33871. for (var i = this.__startIndex; i < this.__endIndex; ++i) {
  33872. var el = displayList[i];
  33873. if (el) {
  33874. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  33875. var prevRect = el.__isRendered && ((el.__dirty & Element.REDARAW_BIT) || !shouldPaint)
  33876. ? el.getPrevPaintRect()
  33877. : null;
  33878. if (prevRect) {
  33879. addRectToMergePool(prevRect);
  33880. }
  33881. var curRect = shouldPaint && ((el.__dirty & Element.REDARAW_BIT) || !el.__isRendered)
  33882. ? el.getPaintRect()
  33883. : null;
  33884. if (curRect) {
  33885. addRectToMergePool(curRect);
  33886. }
  33887. }
  33888. }
  33889. for (var i = this.__prevStartIndex; i < this.__prevEndIndex; ++i) {
  33890. var el = prevList[i];
  33891. var shouldPaint = el.shouldBePainted(viewWidth, viewHeight, true, true);
  33892. if (el && (!shouldPaint || !el.__zr) && el.__isRendered) {
  33893. var prevRect = el.getPrevPaintRect();
  33894. if (prevRect) {
  33895. addRectToMergePool(prevRect);
  33896. }
  33897. }
  33898. }
  33899. var hasIntersections;
  33900. do {
  33901. hasIntersections = false;
  33902. for (var i = 0; i < mergedRepaintRects.length;) {
  33903. if (mergedRepaintRects[i].isZero()) {
  33904. mergedRepaintRects.splice(i, 1);
  33905. continue;
  33906. }
  33907. for (var j = i + 1; j < mergedRepaintRects.length;) {
  33908. if (mergedRepaintRects[i].intersect(mergedRepaintRects[j])) {
  33909. hasIntersections = true;
  33910. mergedRepaintRects[i].union(mergedRepaintRects[j]);
  33911. mergedRepaintRects.splice(j, 1);
  33912. }
  33913. else {
  33914. j++;
  33915. }
  33916. }
  33917. i++;
  33918. }
  33919. } while (hasIntersections);
  33920. this._paintRects = mergedRepaintRects;
  33921. return mergedRepaintRects;
  33922. };
  33923. Layer.prototype.debugGetPaintRects = function () {
  33924. return (this._paintRects || []).slice();
  33925. };
  33926. Layer.prototype.resize = function (width, height) {
  33927. var dpr = this.dpr;
  33928. var dom = this.dom;
  33929. var domStyle = dom.style;
  33930. var domBack = this.domBack;
  33931. if (domStyle) {
  33932. domStyle.width = width + 'px';
  33933. domStyle.height = height + 'px';
  33934. }
  33935. dom.width = width * dpr;
  33936. dom.height = height * dpr;
  33937. if (domBack) {
  33938. domBack.width = width * dpr;
  33939. domBack.height = height * dpr;
  33940. if (dpr !== 1) {
  33941. this.ctxBack.scale(dpr, dpr);
  33942. }
  33943. }
  33944. };
  33945. Layer.prototype.clear = function (clearAll, clearColor, repaintRects) {
  33946. var dom = this.dom;
  33947. var ctx = this.ctx;
  33948. var width = dom.width;
  33949. var height = dom.height;
  33950. clearColor = clearColor || this.clearColor;
  33951. var haveMotionBLur = this.motionBlur && !clearAll;
  33952. var lastFrameAlpha = this.lastFrameAlpha;
  33953. var dpr = this.dpr;
  33954. var self = this;
  33955. if (haveMotionBLur) {
  33956. if (!this.domBack) {
  33957. this.createBackBuffer();
  33958. }
  33959. this.ctxBack.globalCompositeOperation = 'copy';
  33960. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  33961. }
  33962. var domBack = this.domBack;
  33963. function doClear(x, y, width, height) {
  33964. ctx.clearRect(x, y, width, height);
  33965. if (clearColor && clearColor !== 'transparent') {
  33966. var clearColorGradientOrPattern = void 0;
  33967. if (isGradientObject(clearColor)) {
  33968. clearColorGradientOrPattern = clearColor.__canvasGradient
  33969. || getCanvasGradient(ctx, clearColor, {
  33970. x: 0,
  33971. y: 0,
  33972. width: width,
  33973. height: height
  33974. });
  33975. clearColor.__canvasGradient = clearColorGradientOrPattern;
  33976. }
  33977. else if (isPatternObject(clearColor)) {
  33978. clearColorGradientOrPattern = createCanvasPattern(ctx, clearColor, {
  33979. dirty: function () {
  33980. self.setUnpainted();
  33981. self.__painter.refresh();
  33982. }
  33983. });
  33984. }
  33985. ctx.save();
  33986. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  33987. ctx.fillRect(x, y, width, height);
  33988. ctx.restore();
  33989. }
  33990. if (haveMotionBLur) {
  33991. ctx.save();
  33992. ctx.globalAlpha = lastFrameAlpha;
  33993. ctx.drawImage(domBack, x, y, width, height);
  33994. ctx.restore();
  33995. }
  33996. }
  33997. if (!repaintRects || haveMotionBLur) {
  33998. doClear(0, 0, width, height);
  33999. }
  34000. else if (repaintRects.length) {
  34001. each(repaintRects, function (rect) {
  34002. doClear(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34003. });
  34004. }
  34005. };
  34006. return Layer;
  34007. }(Eventful));
  34008. var HOVER_LAYER_ZLEVEL = 1e5;
  34009. var CANVAS_ZLEVEL = 314159;
  34010. var EL_AFTER_INCREMENTAL_INC = 0.01;
  34011. var INCREMENTAL_INC = 0.001;
  34012. function parseInt10$1(val) {
  34013. return parseInt(val, 10);
  34014. }
  34015. function isLayerValid(layer) {
  34016. if (!layer) {
  34017. return false;
  34018. }
  34019. if (layer.__builtin__) {
  34020. return true;
  34021. }
  34022. if (typeof (layer.resize) !== 'function'
  34023. || typeof (layer.refresh) !== 'function') {
  34024. return false;
  34025. }
  34026. return true;
  34027. }
  34028. function createRoot(width, height) {
  34029. var domRoot = document.createElement('div');
  34030. domRoot.style.cssText = [
  34031. 'position:relative',
  34032. 'width:' + width + 'px',
  34033. 'height:' + height + 'px',
  34034. 'padding:0',
  34035. 'margin:0',
  34036. 'border-width:0'
  34037. ].join(';') + ';';
  34038. return domRoot;
  34039. }
  34040. var CanvasPainter = (function () {
  34041. function CanvasPainter(root, storage, opts, id) {
  34042. this.type = 'canvas';
  34043. this._zlevelList = [];
  34044. this._prevDisplayList = [];
  34045. this._layers = {};
  34046. this._layerConfig = {};
  34047. this._needsManuallyCompositing = false;
  34048. this.type = 'canvas';
  34049. var singleCanvas = !root.nodeName
  34050. || root.nodeName.toUpperCase() === 'CANVAS';
  34051. this._opts = opts = extend({}, opts || {});
  34052. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  34053. this._singleCanvas = singleCanvas;
  34054. this.root = root;
  34055. var rootStyle = root.style;
  34056. if (rootStyle) {
  34057. rootStyle.webkitTapHighlightColor = 'transparent';
  34058. rootStyle.webkitUserSelect = 'none';
  34059. rootStyle.userSelect = 'none';
  34060. rootStyle['-webkit-touch-callout'] = 'none';
  34061. root.innerHTML = '';
  34062. }
  34063. this.storage = storage;
  34064. var zlevelList = this._zlevelList;
  34065. this._prevDisplayList = [];
  34066. var layers = this._layers;
  34067. if (!singleCanvas) {
  34068. this._width = this._getSize(0);
  34069. this._height = this._getSize(1);
  34070. var domRoot = this._domRoot = createRoot(this._width, this._height);
  34071. root.appendChild(domRoot);
  34072. }
  34073. else {
  34074. var rootCanvas = root;
  34075. var width = rootCanvas.width;
  34076. var height = rootCanvas.height;
  34077. if (opts.width != null) {
  34078. width = opts.width;
  34079. }
  34080. if (opts.height != null) {
  34081. height = opts.height;
  34082. }
  34083. this.dpr = opts.devicePixelRatio || 1;
  34084. rootCanvas.width = width * this.dpr;
  34085. rootCanvas.height = height * this.dpr;
  34086. this._width = width;
  34087. this._height = height;
  34088. var mainLayer = new Layer(rootCanvas, this, this.dpr);
  34089. mainLayer.__builtin__ = true;
  34090. mainLayer.initContext();
  34091. layers[CANVAS_ZLEVEL] = mainLayer;
  34092. mainLayer.zlevel = CANVAS_ZLEVEL;
  34093. zlevelList.push(CANVAS_ZLEVEL);
  34094. this._domRoot = root;
  34095. }
  34096. }
  34097. CanvasPainter.prototype.getType = function () {
  34098. return 'canvas';
  34099. };
  34100. CanvasPainter.prototype.isSingleCanvas = function () {
  34101. return this._singleCanvas;
  34102. };
  34103. CanvasPainter.prototype.getViewportRoot = function () {
  34104. return this._domRoot;
  34105. };
  34106. CanvasPainter.prototype.getViewportRootOffset = function () {
  34107. var viewportRoot = this.getViewportRoot();
  34108. if (viewportRoot) {
  34109. return {
  34110. offsetLeft: viewportRoot.offsetLeft || 0,
  34111. offsetTop: viewportRoot.offsetTop || 0
  34112. };
  34113. }
  34114. };
  34115. CanvasPainter.prototype.refresh = function (paintAll) {
  34116. var list = this.storage.getDisplayList(true);
  34117. var prevList = this._prevDisplayList;
  34118. var zlevelList = this._zlevelList;
  34119. this._redrawId = Math.random();
  34120. this._paintList(list, prevList, paintAll, this._redrawId);
  34121. for (var i = 0; i < zlevelList.length; i++) {
  34122. var z = zlevelList[i];
  34123. var layer = this._layers[z];
  34124. if (!layer.__builtin__ && layer.refresh) {
  34125. var clearColor = i === 0 ? this._backgroundColor : null;
  34126. layer.refresh(clearColor);
  34127. }
  34128. }
  34129. if (this._opts.useDirtyRect) {
  34130. this._prevDisplayList = list.slice();
  34131. }
  34132. return this;
  34133. };
  34134. CanvasPainter.prototype.refreshHover = function () {
  34135. this._paintHoverList(this.storage.getDisplayList(false));
  34136. };
  34137. CanvasPainter.prototype._paintHoverList = function (list) {
  34138. var len = list.length;
  34139. var hoverLayer = this._hoverlayer;
  34140. hoverLayer && hoverLayer.clear();
  34141. if (!len) {
  34142. return;
  34143. }
  34144. var scope = {
  34145. inHover: true,
  34146. viewWidth: this._width,
  34147. viewHeight: this._height
  34148. };
  34149. var ctx;
  34150. for (var i = 0; i < len; i++) {
  34151. var el = list[i];
  34152. if (el.__inHover) {
  34153. if (!hoverLayer) {
  34154. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  34155. }
  34156. if (!ctx) {
  34157. ctx = hoverLayer.ctx;
  34158. ctx.save();
  34159. }
  34160. brush(ctx, el, scope, i === len - 1);
  34161. }
  34162. }
  34163. if (ctx) {
  34164. ctx.restore();
  34165. }
  34166. };
  34167. CanvasPainter.prototype.getHoverLayer = function () {
  34168. return this.getLayer(HOVER_LAYER_ZLEVEL);
  34169. };
  34170. CanvasPainter.prototype.paintOne = function (ctx, el) {
  34171. brushSingle(ctx, el);
  34172. };
  34173. CanvasPainter.prototype._paintList = function (list, prevList, paintAll, redrawId) {
  34174. if (this._redrawId !== redrawId) {
  34175. return;
  34176. }
  34177. paintAll = paintAll || false;
  34178. this._updateLayerStatus(list);
  34179. var _a = this._doPaintList(list, prevList, paintAll), finished = _a.finished, needsRefreshHover = _a.needsRefreshHover;
  34180. if (this._needsManuallyCompositing) {
  34181. this._compositeManually();
  34182. }
  34183. if (needsRefreshHover) {
  34184. this._paintHoverList(list);
  34185. }
  34186. if (!finished) {
  34187. var self_1 = this;
  34188. requestAnimationFrame$1(function () {
  34189. self_1._paintList(list, prevList, paintAll, redrawId);
  34190. });
  34191. }
  34192. else {
  34193. this.eachLayer(function (layer) {
  34194. layer.afterBrush && layer.afterBrush();
  34195. });
  34196. }
  34197. };
  34198. CanvasPainter.prototype._compositeManually = function () {
  34199. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  34200. var width = this._domRoot.width;
  34201. var height = this._domRoot.height;
  34202. ctx.clearRect(0, 0, width, height);
  34203. this.eachBuiltinLayer(function (layer) {
  34204. if (layer.virtual) {
  34205. ctx.drawImage(layer.dom, 0, 0, width, height);
  34206. }
  34207. });
  34208. };
  34209. CanvasPainter.prototype._doPaintList = function (list, prevList, paintAll) {
  34210. var _this = this;
  34211. var layerList = [];
  34212. var useDirtyRect = this._opts.useDirtyRect;
  34213. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  34214. var zlevel = this._zlevelList[zi];
  34215. var layer = this._layers[zlevel];
  34216. if (layer.__builtin__
  34217. && layer !== this._hoverlayer
  34218. && (layer.__dirty || paintAll)) {
  34219. layerList.push(layer);
  34220. }
  34221. }
  34222. var finished = true;
  34223. var needsRefreshHover = false;
  34224. var _loop_1 = function (k) {
  34225. var layer = layerList[k];
  34226. var ctx = layer.ctx;
  34227. var repaintRects = useDirtyRect
  34228. && layer.createRepaintRects(list, prevList, this_1._width, this_1._height);
  34229. ctx.save();
  34230. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  34231. var useTimer = !paintAll && layer.incremental && Date.now;
  34232. var startTime = useTimer && Date.now();
  34233. var clearColor = layer.zlevel === this_1._zlevelList[0]
  34234. ? this_1._backgroundColor : null;
  34235. if (layer.__startIndex === layer.__endIndex) {
  34236. layer.clear(false, clearColor, repaintRects);
  34237. }
  34238. else if (start === layer.__startIndex) {
  34239. var firstEl = list[start];
  34240. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  34241. layer.clear(false, clearColor, repaintRects);
  34242. }
  34243. }
  34244. if (start === -1) {
  34245. console.error('For some unknown reason. drawIndex is -1');
  34246. start = layer.__startIndex;
  34247. }
  34248. var i;
  34249. var repaint = function (repaintRect) {
  34250. var scope = {
  34251. inHover: false,
  34252. allClipped: false,
  34253. prevEl: null,
  34254. viewWidth: _this._width,
  34255. viewHeight: _this._height
  34256. };
  34257. for (i = start; i < layer.__endIndex; i++) {
  34258. var el = list[i];
  34259. if (el.__inHover) {
  34260. needsRefreshHover = true;
  34261. }
  34262. _this._doPaintEl(el, layer, useDirtyRect, repaintRect, scope, i === layer.__endIndex - 1);
  34263. if (useTimer) {
  34264. var dTime = Date.now() - startTime;
  34265. if (dTime > 15) {
  34266. break;
  34267. }
  34268. }
  34269. }
  34270. if (scope.prevElClipPaths) {
  34271. ctx.restore();
  34272. }
  34273. };
  34274. if (repaintRects) {
  34275. if (repaintRects.length === 0) {
  34276. i = layer.__endIndex;
  34277. }
  34278. else {
  34279. var dpr = this_1.dpr;
  34280. for (var r = 0; r < repaintRects.length; ++r) {
  34281. var rect = repaintRects[r];
  34282. ctx.save();
  34283. ctx.beginPath();
  34284. ctx.rect(rect.x * dpr, rect.y * dpr, rect.width * dpr, rect.height * dpr);
  34285. ctx.clip();
  34286. repaint(rect);
  34287. ctx.restore();
  34288. }
  34289. }
  34290. }
  34291. else {
  34292. ctx.save();
  34293. repaint();
  34294. ctx.restore();
  34295. }
  34296. layer.__drawIndex = i;
  34297. if (layer.__drawIndex < layer.__endIndex) {
  34298. finished = false;
  34299. }
  34300. };
  34301. var this_1 = this;
  34302. for (var k = 0; k < layerList.length; k++) {
  34303. _loop_1(k);
  34304. }
  34305. if (env.wxa) {
  34306. each(this._layers, function (layer) {
  34307. if (layer && layer.ctx && layer.ctx.draw) {
  34308. layer.ctx.draw();
  34309. }
  34310. });
  34311. }
  34312. return {
  34313. finished: finished,
  34314. needsRefreshHover: needsRefreshHover
  34315. };
  34316. };
  34317. CanvasPainter.prototype._doPaintEl = function (el, currentLayer, useDirtyRect, repaintRect, scope, isLast) {
  34318. var ctx = currentLayer.ctx;
  34319. if (useDirtyRect) {
  34320. var paintRect = el.getPaintRect();
  34321. if (!repaintRect || paintRect && paintRect.intersect(repaintRect)) {
  34322. brush(ctx, el, scope, isLast);
  34323. el.setPrevPaintRect(paintRect);
  34324. }
  34325. }
  34326. else {
  34327. brush(ctx, el, scope, isLast);
  34328. }
  34329. };
  34330. CanvasPainter.prototype.getLayer = function (zlevel, virtual) {
  34331. if (this._singleCanvas && !this._needsManuallyCompositing) {
  34332. zlevel = CANVAS_ZLEVEL;
  34333. }
  34334. var layer = this._layers[zlevel];
  34335. if (!layer) {
  34336. layer = new Layer('zr_' + zlevel, this, this.dpr);
  34337. layer.zlevel = zlevel;
  34338. layer.__builtin__ = true;
  34339. if (this._layerConfig[zlevel]) {
  34340. merge(layer, this._layerConfig[zlevel], true);
  34341. }
  34342. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  34343. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  34344. }
  34345. if (virtual) {
  34346. layer.virtual = virtual;
  34347. }
  34348. this.insertLayer(zlevel, layer);
  34349. layer.initContext();
  34350. }
  34351. return layer;
  34352. };
  34353. CanvasPainter.prototype.insertLayer = function (zlevel, layer) {
  34354. var layersMap = this._layers;
  34355. var zlevelList = this._zlevelList;
  34356. var len = zlevelList.length;
  34357. var domRoot = this._domRoot;
  34358. var prevLayer = null;
  34359. var i = -1;
  34360. if (layersMap[zlevel]) {
  34361. logError('ZLevel ' + zlevel + ' has been used already');
  34362. return;
  34363. }
  34364. if (!isLayerValid(layer)) {
  34365. logError('Layer of zlevel ' + zlevel + ' is not valid');
  34366. return;
  34367. }
  34368. if (len > 0 && zlevel > zlevelList[0]) {
  34369. for (i = 0; i < len - 1; i++) {
  34370. if (zlevelList[i] < zlevel
  34371. && zlevelList[i + 1] > zlevel) {
  34372. break;
  34373. }
  34374. }
  34375. prevLayer = layersMap[zlevelList[i]];
  34376. }
  34377. zlevelList.splice(i + 1, 0, zlevel);
  34378. layersMap[zlevel] = layer;
  34379. if (!layer.virtual) {
  34380. if (prevLayer) {
  34381. var prevDom = prevLayer.dom;
  34382. if (prevDom.nextSibling) {
  34383. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  34384. }
  34385. else {
  34386. domRoot.appendChild(layer.dom);
  34387. }
  34388. }
  34389. else {
  34390. if (domRoot.firstChild) {
  34391. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  34392. }
  34393. else {
  34394. domRoot.appendChild(layer.dom);
  34395. }
  34396. }
  34397. }
  34398. layer.__painter = this;
  34399. };
  34400. CanvasPainter.prototype.eachLayer = function (cb, context) {
  34401. var zlevelList = this._zlevelList;
  34402. for (var i = 0; i < zlevelList.length; i++) {
  34403. var z = zlevelList[i];
  34404. cb.call(context, this._layers[z], z);
  34405. }
  34406. };
  34407. CanvasPainter.prototype.eachBuiltinLayer = function (cb, context) {
  34408. var zlevelList = this._zlevelList;
  34409. for (var i = 0; i < zlevelList.length; i++) {
  34410. var z = zlevelList[i];
  34411. var layer = this._layers[z];
  34412. if (layer.__builtin__) {
  34413. cb.call(context, layer, z);
  34414. }
  34415. }
  34416. };
  34417. CanvasPainter.prototype.eachOtherLayer = function (cb, context) {
  34418. var zlevelList = this._zlevelList;
  34419. for (var i = 0; i < zlevelList.length; i++) {
  34420. var z = zlevelList[i];
  34421. var layer = this._layers[z];
  34422. if (!layer.__builtin__) {
  34423. cb.call(context, layer, z);
  34424. }
  34425. }
  34426. };
  34427. CanvasPainter.prototype.getLayers = function () {
  34428. return this._layers;
  34429. };
  34430. CanvasPainter.prototype._updateLayerStatus = function (list) {
  34431. this.eachBuiltinLayer(function (layer, z) {
  34432. layer.__dirty = layer.__used = false;
  34433. });
  34434. function updatePrevLayer(idx) {
  34435. if (prevLayer) {
  34436. if (prevLayer.__endIndex !== idx) {
  34437. prevLayer.__dirty = true;
  34438. }
  34439. prevLayer.__endIndex = idx;
  34440. }
  34441. }
  34442. if (this._singleCanvas) {
  34443. for (var i_1 = 1; i_1 < list.length; i_1++) {
  34444. var el = list[i_1];
  34445. if (el.zlevel !== list[i_1 - 1].zlevel || el.incremental) {
  34446. this._needsManuallyCompositing = true;
  34447. break;
  34448. }
  34449. }
  34450. }
  34451. var prevLayer = null;
  34452. var incrementalLayerCount = 0;
  34453. var prevZlevel;
  34454. var i;
  34455. for (i = 0; i < list.length; i++) {
  34456. var el = list[i];
  34457. var zlevel = el.zlevel;
  34458. var layer = void 0;
  34459. if (prevZlevel !== zlevel) {
  34460. prevZlevel = zlevel;
  34461. incrementalLayerCount = 0;
  34462. }
  34463. if (el.incremental) {
  34464. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  34465. layer.incremental = true;
  34466. incrementalLayerCount = 1;
  34467. }
  34468. else {
  34469. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  34470. }
  34471. if (!layer.__builtin__) {
  34472. logError('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  34473. }
  34474. if (layer !== prevLayer) {
  34475. layer.__used = true;
  34476. if (layer.__startIndex !== i) {
  34477. layer.__dirty = true;
  34478. }
  34479. layer.__startIndex = i;
  34480. if (!layer.incremental) {
  34481. layer.__drawIndex = i;
  34482. }
  34483. else {
  34484. layer.__drawIndex = -1;
  34485. }
  34486. updatePrevLayer(i);
  34487. prevLayer = layer;
  34488. }
  34489. if ((el.__dirty & Element.REDARAW_BIT) && !el.__inHover) {
  34490. layer.__dirty = true;
  34491. if (layer.incremental && layer.__drawIndex < 0) {
  34492. layer.__drawIndex = i;
  34493. }
  34494. }
  34495. }
  34496. updatePrevLayer(i);
  34497. this.eachBuiltinLayer(function (layer, z) {
  34498. if (!layer.__used && layer.getElementCount() > 0) {
  34499. layer.__dirty = true;
  34500. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  34501. }
  34502. if (layer.__dirty && layer.__drawIndex < 0) {
  34503. layer.__drawIndex = layer.__startIndex;
  34504. }
  34505. });
  34506. };
  34507. CanvasPainter.prototype.clear = function () {
  34508. this.eachBuiltinLayer(this._clearLayer);
  34509. return this;
  34510. };
  34511. CanvasPainter.prototype._clearLayer = function (layer) {
  34512. layer.clear();
  34513. };
  34514. CanvasPainter.prototype.setBackgroundColor = function (backgroundColor) {
  34515. this._backgroundColor = backgroundColor;
  34516. each(this._layers, function (layer) {
  34517. layer.setUnpainted();
  34518. });
  34519. };
  34520. CanvasPainter.prototype.configLayer = function (zlevel, config) {
  34521. if (config) {
  34522. var layerConfig = this._layerConfig;
  34523. if (!layerConfig[zlevel]) {
  34524. layerConfig[zlevel] = config;
  34525. }
  34526. else {
  34527. merge(layerConfig[zlevel], config, true);
  34528. }
  34529. for (var i = 0; i < this._zlevelList.length; i++) {
  34530. var _zlevel = this._zlevelList[i];
  34531. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  34532. var layer = this._layers[_zlevel];
  34533. merge(layer, layerConfig[zlevel], true);
  34534. }
  34535. }
  34536. }
  34537. };
  34538. CanvasPainter.prototype.delLayer = function (zlevel) {
  34539. var layers = this._layers;
  34540. var zlevelList = this._zlevelList;
  34541. var layer = layers[zlevel];
  34542. if (!layer) {
  34543. return;
  34544. }
  34545. layer.dom.parentNode.removeChild(layer.dom);
  34546. delete layers[zlevel];
  34547. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  34548. };
  34549. CanvasPainter.prototype.resize = function (width, height) {
  34550. if (!this._domRoot.style) {
  34551. if (width == null || height == null) {
  34552. return;
  34553. }
  34554. this._width = width;
  34555. this._height = height;
  34556. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  34557. }
  34558. else {
  34559. var domRoot = this._domRoot;
  34560. domRoot.style.display = 'none';
  34561. var opts = this._opts;
  34562. width != null && (opts.width = width);
  34563. height != null && (opts.height = height);
  34564. width = this._getSize(0);
  34565. height = this._getSize(1);
  34566. domRoot.style.display = '';
  34567. if (this._width !== width || height !== this._height) {
  34568. domRoot.style.width = width + 'px';
  34569. domRoot.style.height = height + 'px';
  34570. for (var id in this._layers) {
  34571. if (this._layers.hasOwnProperty(id)) {
  34572. this._layers[id].resize(width, height);
  34573. }
  34574. }
  34575. this.refresh(true);
  34576. }
  34577. this._width = width;
  34578. this._height = height;
  34579. }
  34580. return this;
  34581. };
  34582. CanvasPainter.prototype.clearLayer = function (zlevel) {
  34583. var layer = this._layers[zlevel];
  34584. if (layer) {
  34585. layer.clear();
  34586. }
  34587. };
  34588. CanvasPainter.prototype.dispose = function () {
  34589. this.root.innerHTML = '';
  34590. this.root =
  34591. this.storage =
  34592. this._domRoot =
  34593. this._layers = null;
  34594. };
  34595. CanvasPainter.prototype.getRenderedCanvas = function (opts) {
  34596. opts = opts || {};
  34597. if (this._singleCanvas && !this._compositeManually) {
  34598. return this._layers[CANVAS_ZLEVEL].dom;
  34599. }
  34600. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  34601. imageLayer.initContext();
  34602. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  34603. var ctx = imageLayer.ctx;
  34604. if (opts.pixelRatio <= this.dpr) {
  34605. this.refresh();
  34606. var width_1 = imageLayer.dom.width;
  34607. var height_1 = imageLayer.dom.height;
  34608. this.eachLayer(function (layer) {
  34609. if (layer.__builtin__) {
  34610. ctx.drawImage(layer.dom, 0, 0, width_1, height_1);
  34611. }
  34612. else if (layer.renderToCanvas) {
  34613. ctx.save();
  34614. layer.renderToCanvas(ctx);
  34615. ctx.restore();
  34616. }
  34617. });
  34618. }
  34619. else {
  34620. var scope = {
  34621. inHover: false,
  34622. viewWidth: this._width,
  34623. viewHeight: this._height
  34624. };
  34625. var displayList = this.storage.getDisplayList(true);
  34626. for (var i = 0, len = displayList.length; i < len; i++) {
  34627. var el = displayList[i];
  34628. brush(ctx, el, scope, i === len - 1);
  34629. }
  34630. }
  34631. return imageLayer.dom;
  34632. };
  34633. CanvasPainter.prototype.getWidth = function () {
  34634. return this._width;
  34635. };
  34636. CanvasPainter.prototype.getHeight = function () {
  34637. return this._height;
  34638. };
  34639. CanvasPainter.prototype._getSize = function (whIdx) {
  34640. var opts = this._opts;
  34641. var wh = ['width', 'height'][whIdx];
  34642. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  34643. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  34644. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  34645. if (opts[wh] != null && opts[wh] !== 'auto') {
  34646. return parseFloat(opts[wh]);
  34647. }
  34648. var root = this.root;
  34649. var stl = document.defaultView.getComputedStyle(root);
  34650. return ((root[cwh] || parseInt10$1(stl[wh]) || parseInt10$1(root.style[wh]))
  34651. - (parseInt10$1(stl[plt]) || 0)
  34652. - (parseInt10$1(stl[prb]) || 0)) | 0;
  34653. };
  34654. CanvasPainter.prototype.pathToImage = function (path, dpr) {
  34655. dpr = dpr || this.dpr;
  34656. var canvas = document.createElement('canvas');
  34657. var ctx = canvas.getContext('2d');
  34658. var rect = path.getBoundingRect();
  34659. var style = path.style;
  34660. var shadowBlurSize = style.shadowBlur * dpr;
  34661. var shadowOffsetX = style.shadowOffsetX * dpr;
  34662. var shadowOffsetY = style.shadowOffsetY * dpr;
  34663. var lineWidth = path.hasStroke() ? style.lineWidth : 0;
  34664. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  34665. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  34666. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  34667. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  34668. var width = rect.width + leftMargin + rightMargin;
  34669. var height = rect.height + topMargin + bottomMargin;
  34670. canvas.width = width * dpr;
  34671. canvas.height = height * dpr;
  34672. ctx.scale(dpr, dpr);
  34673. ctx.clearRect(0, 0, width, height);
  34674. ctx.dpr = dpr;
  34675. var pathTransform = {
  34676. x: path.x,
  34677. y: path.y,
  34678. scaleX: path.scaleX,
  34679. scaleY: path.scaleY,
  34680. rotation: path.rotation,
  34681. originX: path.originX,
  34682. originY: path.originY
  34683. };
  34684. path.x = leftMargin - rect.x;
  34685. path.y = topMargin - rect.y;
  34686. path.rotation = 0;
  34687. path.scaleX = 1;
  34688. path.scaleY = 1;
  34689. path.updateTransform();
  34690. if (path) {
  34691. brush(ctx, path, {
  34692. inHover: false,
  34693. viewWidth: this._width,
  34694. viewHeight: this._height
  34695. }, true);
  34696. }
  34697. var imgShape = new ZRImage({
  34698. style: {
  34699. x: 0,
  34700. y: 0,
  34701. image: canvas
  34702. }
  34703. });
  34704. extend(path, pathTransform);
  34705. return imgShape;
  34706. };
  34707. return CanvasPainter;
  34708. }());
  34709. function install$1(registers) {
  34710. registers.registerPainter('canvas', CanvasPainter);
  34711. }
  34712. var LineSeriesModel =
  34713. /** @class */
  34714. function (_super) {
  34715. __extends(LineSeriesModel, _super);
  34716. function LineSeriesModel() {
  34717. var _this = _super !== null && _super.apply(this, arguments) || this;
  34718. _this.type = LineSeriesModel.type;
  34719. _this.hasSymbolVisual = true;
  34720. _this.legendSymbol = 'line';
  34721. return _this;
  34722. }
  34723. LineSeriesModel.prototype.getInitialData = function (option) {
  34724. if ("development" !== 'production') {
  34725. var coordSys = option.coordinateSystem;
  34726. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  34727. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  34728. }
  34729. }
  34730. return createListFromArray(this.getSource(), this, {
  34731. useEncodeDefaulter: true
  34732. });
  34733. };
  34734. LineSeriesModel.type = 'series.line';
  34735. LineSeriesModel.dependencies = ['grid', 'polar'];
  34736. LineSeriesModel.defaultOption = {
  34737. zlevel: 0,
  34738. z: 3,
  34739. coordinateSystem: 'cartesian2d',
  34740. legendHoverLink: true,
  34741. clip: true,
  34742. label: {
  34743. position: 'top'
  34744. },
  34745. endLabel: {
  34746. show: false,
  34747. valueAnimation: true,
  34748. distance: 8
  34749. },
  34750. lineStyle: {
  34751. width: 2,
  34752. type: 'solid'
  34753. },
  34754. emphasis: {
  34755. scale: true,
  34756. lineStyle: {
  34757. width: 'bolder'
  34758. }
  34759. },
  34760. // areaStyle: {
  34761. // origin of areaStyle. Valid values:
  34762. // `'auto'/null/undefined`: from axisLine to data
  34763. // `'start'`: from min to data
  34764. // `'end'`: from data to max
  34765. // origin: 'auto'
  34766. // },
  34767. // false, 'start', 'end', 'middle'
  34768. step: false,
  34769. // Disabled if step is true
  34770. smooth: false,
  34771. smoothMonotone: null,
  34772. symbol: 'emptyCircle',
  34773. symbolSize: 4,
  34774. symbolRotate: null,
  34775. showSymbol: true,
  34776. // `false`: follow the label interval strategy.
  34777. // `true`: show all symbols.
  34778. // `'auto'`: If possible, show all symbols, otherwise
  34779. // follow the label interval strategy.
  34780. showAllSymbol: 'auto',
  34781. // Whether to connect break point.
  34782. connectNulls: false,
  34783. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum', 'lttb'.
  34784. sampling: 'none',
  34785. animationEasing: 'linear',
  34786. // Disable progressive
  34787. progressive: 0,
  34788. hoverLayerThreshold: Infinity
  34789. };
  34790. return LineSeriesModel;
  34791. }(SeriesModel);
  34792. /**
  34793. * @return label string. Not null/undefined
  34794. */
  34795. function getDefaultLabel(data, dataIndex) {
  34796. var labelDims = data.mapDimensionsAll('defaultedLabel');
  34797. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  34798. if (len === 1) {
  34799. var rawVal = retrieveRawValue(data, dataIndex, labelDims[0]);
  34800. return rawVal != null ? rawVal + '' : null;
  34801. } else if (len) {
  34802. var vals = [];
  34803. for (var i = 0; i < labelDims.length; i++) {
  34804. vals.push(retrieveRawValue(data, dataIndex, labelDims[i]));
  34805. }
  34806. return vals.join(' ');
  34807. }
  34808. }
  34809. function getDefaultInterpolatedLabel(data, interpolatedValue) {
  34810. var labelDims = data.mapDimensionsAll('defaultedLabel');
  34811. if (!isArray(interpolatedValue)) {
  34812. return interpolatedValue + '';
  34813. }
  34814. var vals = [];
  34815. for (var i = 0; i < labelDims.length; i++) {
  34816. var dimInfo = data.getDimensionInfo(labelDims[i]);
  34817. if (dimInfo) {
  34818. vals.push(interpolatedValue[dimInfo.index]);
  34819. }
  34820. }
  34821. return vals.join(' ');
  34822. }
  34823. var Symbol =
  34824. /** @class */
  34825. function (_super) {
  34826. __extends(Symbol, _super);
  34827. function Symbol(data, idx, seriesScope, opts) {
  34828. var _this = _super.call(this) || this;
  34829. _this.updateData(data, idx, seriesScope, opts);
  34830. return _this;
  34831. }
  34832. Symbol.prototype._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  34833. // Remove paths created before
  34834. this.removeAll(); // let symbolPath = createSymbol(
  34835. // symbolType, -0.5, -0.5, 1, 1, color
  34836. // );
  34837. // If width/height are set too small (e.g., set to 1) on ios10
  34838. // and macOS Sierra, a circle stroke become a rect, no matter what
  34839. // the scale is set. So we set width/height as 2. See #4150.
  34840. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, null, keepAspect);
  34841. symbolPath.attr({
  34842. z2: 100,
  34843. culling: true,
  34844. scaleX: symbolSize[0] / 2,
  34845. scaleY: symbolSize[1] / 2
  34846. }); // Rewrite drift method
  34847. symbolPath.drift = driftSymbol;
  34848. this._symbolType = symbolType;
  34849. this.add(symbolPath);
  34850. };
  34851. /**
  34852. * Stop animation
  34853. * @param {boolean} toLastFrame
  34854. */
  34855. Symbol.prototype.stopSymbolAnimation = function (toLastFrame) {
  34856. this.childAt(0).stopAnimation(null, toLastFrame);
  34857. };
  34858. /**
  34859. * FIXME:
  34860. * Caution: This method breaks the encapsulation of this module,
  34861. * but it indeed brings convenience. So do not use the method
  34862. * unless you detailedly know all the implements of `Symbol`,
  34863. * especially animation.
  34864. *
  34865. * Get symbol path element.
  34866. */
  34867. Symbol.prototype.getSymbolPath = function () {
  34868. return this.childAt(0);
  34869. };
  34870. /**
  34871. * Highlight symbol
  34872. */
  34873. Symbol.prototype.highlight = function () {
  34874. enterEmphasis(this.childAt(0));
  34875. };
  34876. /**
  34877. * Downplay symbol
  34878. */
  34879. Symbol.prototype.downplay = function () {
  34880. leaveEmphasis(this.childAt(0));
  34881. };
  34882. /**
  34883. * @param {number} zlevel
  34884. * @param {number} z
  34885. */
  34886. Symbol.prototype.setZ = function (zlevel, z) {
  34887. var symbolPath = this.childAt(0);
  34888. symbolPath.zlevel = zlevel;
  34889. symbolPath.z = z;
  34890. };
  34891. Symbol.prototype.setDraggable = function (draggable) {
  34892. var symbolPath = this.childAt(0);
  34893. symbolPath.draggable = draggable;
  34894. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  34895. };
  34896. /**
  34897. * Update symbol properties
  34898. */
  34899. Symbol.prototype.updateData = function (data, idx, seriesScope, opts) {
  34900. this.silent = false;
  34901. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  34902. var seriesModel = data.hostModel;
  34903. var symbolSize = Symbol.getSymbolSize(data, idx);
  34904. var isInit = symbolType !== this._symbolType;
  34905. var disableAnimation = opts && opts.disableAnimation;
  34906. if (isInit) {
  34907. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  34908. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  34909. } else {
  34910. var symbolPath = this.childAt(0);
  34911. symbolPath.silent = false;
  34912. var target = {
  34913. scaleX: symbolSize[0] / 2,
  34914. scaleY: symbolSize[1] / 2
  34915. };
  34916. disableAnimation ? symbolPath.attr(target) : updateProps(symbolPath, target, seriesModel, idx);
  34917. }
  34918. this._updateCommon(data, idx, symbolSize, seriesScope, opts);
  34919. if (isInit) {
  34920. var symbolPath = this.childAt(0);
  34921. if (!disableAnimation) {
  34922. var target = {
  34923. scaleX: this._sizeX,
  34924. scaleY: this._sizeY,
  34925. style: {
  34926. // Always fadeIn. Because it has fadeOut animation when symbol is removed..
  34927. opacity: symbolPath.style.opacity
  34928. }
  34929. };
  34930. symbolPath.scaleX = symbolPath.scaleY = 0;
  34931. symbolPath.style.opacity = 0;
  34932. initProps(symbolPath, target, seriesModel, idx);
  34933. }
  34934. }
  34935. if (disableAnimation) {
  34936. // Must stop remove animation manually if don't call initProps or updateProps.
  34937. this.childAt(0).stopAnimation('remove');
  34938. }
  34939. this._seriesModel = seriesModel;
  34940. };
  34941. Symbol.prototype._updateCommon = function (data, idx, symbolSize, seriesScope, opts) {
  34942. var symbolPath = this.childAt(0);
  34943. var seriesModel = data.hostModel;
  34944. var emphasisItemStyle;
  34945. var blurItemStyle;
  34946. var selectItemStyle;
  34947. var focus;
  34948. var blurScope;
  34949. var symbolOffset;
  34950. var labelStatesModels;
  34951. var hoverScale;
  34952. var cursorStyle;
  34953. if (seriesScope) {
  34954. emphasisItemStyle = seriesScope.emphasisItemStyle;
  34955. blurItemStyle = seriesScope.blurItemStyle;
  34956. selectItemStyle = seriesScope.selectItemStyle;
  34957. focus = seriesScope.focus;
  34958. blurScope = seriesScope.blurScope;
  34959. symbolOffset = seriesScope.symbolOffset;
  34960. labelStatesModels = seriesScope.labelStatesModels;
  34961. hoverScale = seriesScope.hoverScale;
  34962. cursorStyle = seriesScope.cursorStyle;
  34963. }
  34964. if (!seriesScope || data.hasItemOption) {
  34965. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx);
  34966. var emphasisModel = itemModel.getModel('emphasis');
  34967. emphasisItemStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  34968. selectItemStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  34969. blurItemStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  34970. focus = emphasisModel.get('focus');
  34971. blurScope = emphasisModel.get('blurScope');
  34972. symbolOffset = itemModel.getShallow('symbolOffset');
  34973. labelStatesModels = getLabelStatesModels(itemModel);
  34974. hoverScale = emphasisModel.getShallow('scale');
  34975. cursorStyle = itemModel.getShallow('cursor');
  34976. }
  34977. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  34978. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  34979. if (symbolOffset) {
  34980. symbolPath.x = parsePercent$1(symbolOffset[0], symbolSize[0]);
  34981. symbolPath.y = parsePercent$1(symbolOffset[1], symbolSize[1]);
  34982. }
  34983. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  34984. var symbolStyle = data.getItemVisual(idx, 'style');
  34985. var visualColor = symbolStyle.fill;
  34986. if (symbolPath instanceof ZRImage) {
  34987. var pathStyle = symbolPath.style;
  34988. symbolPath.useStyle(extend({
  34989. // TODO other properties like x, y ?
  34990. image: pathStyle.image,
  34991. x: pathStyle.x,
  34992. y: pathStyle.y,
  34993. width: pathStyle.width,
  34994. height: pathStyle.height
  34995. }, symbolStyle));
  34996. } else {
  34997. if (symbolPath.__isEmptyBrush) {
  34998. // fill and stroke will be swapped if it's empty.
  34999. // So we cloned a new style to avoid it affecting the original style in visual storage.
  35000. // TODO Better implementation. No empty logic!
  35001. symbolPath.useStyle(extend({}, symbolStyle));
  35002. } else {
  35003. symbolPath.useStyle(symbolStyle);
  35004. } // Disable decal because symbol scale will been applied on the decal.
  35005. symbolPath.style.decal = null;
  35006. symbolPath.setColor(visualColor, opts && opts.symbolInnerColor);
  35007. symbolPath.style.strokeNoScale = true;
  35008. }
  35009. var liftZ = data.getItemVisual(idx, 'liftZ');
  35010. var z2Origin = this._z2;
  35011. if (liftZ != null) {
  35012. if (z2Origin == null) {
  35013. this._z2 = symbolPath.z2;
  35014. symbolPath.z2 += liftZ;
  35015. }
  35016. } else if (z2Origin != null) {
  35017. symbolPath.z2 = z2Origin;
  35018. this._z2 = null;
  35019. }
  35020. var useNameLabel = opts && opts.useNameLabel;
  35021. setLabelStyle(symbolPath, labelStatesModels, {
  35022. labelFetcher: seriesModel,
  35023. labelDataIndex: idx,
  35024. defaultText: getLabelDefaultText,
  35025. inheritColor: visualColor,
  35026. defaultOpacity: symbolStyle.opacity
  35027. }); // Do not execute util needed.
  35028. function getLabelDefaultText(idx) {
  35029. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  35030. }
  35031. this._sizeX = symbolSize[0] / 2;
  35032. this._sizeY = symbolSize[1] / 2;
  35033. var emphasisState = symbolPath.ensureState('emphasis');
  35034. emphasisState.style = emphasisItemStyle;
  35035. symbolPath.ensureState('select').style = selectItemStyle;
  35036. symbolPath.ensureState('blur').style = blurItemStyle;
  35037. if (hoverScale) {
  35038. var scaleRatio = Math.max(1.1, 3 / this._sizeY);
  35039. emphasisState.scaleX = this._sizeX * scaleRatio;
  35040. emphasisState.scaleY = this._sizeY * scaleRatio;
  35041. }
  35042. this.setSymbolScale(1);
  35043. enableHoverEmphasis(this, focus, blurScope);
  35044. };
  35045. Symbol.prototype.setSymbolScale = function (scale) {
  35046. this.scaleX = this.scaleY = scale;
  35047. };
  35048. Symbol.prototype.fadeOut = function (cb, opt) {
  35049. var symbolPath = this.childAt(0);
  35050. var seriesModel = this._seriesModel;
  35051. var dataIndex = getECData(this).dataIndex;
  35052. var animationOpt = opt && opt.animation; // Avoid mistaken hover when fading out
  35053. this.silent = symbolPath.silent = true; // Not show text when animating
  35054. if (opt && opt.fadeLabel) {
  35055. var textContent = symbolPath.getTextContent();
  35056. if (textContent) {
  35057. removeElement(textContent, {
  35058. style: {
  35059. opacity: 0
  35060. }
  35061. }, seriesModel, {
  35062. dataIndex: dataIndex,
  35063. removeOpt: animationOpt,
  35064. cb: function () {
  35065. symbolPath.removeTextContent();
  35066. }
  35067. });
  35068. }
  35069. } else {
  35070. symbolPath.removeTextContent();
  35071. }
  35072. removeElement(symbolPath, {
  35073. style: {
  35074. opacity: 0
  35075. },
  35076. scaleX: 0,
  35077. scaleY: 0
  35078. }, seriesModel, {
  35079. dataIndex: dataIndex,
  35080. cb: cb,
  35081. removeOpt: animationOpt
  35082. });
  35083. };
  35084. Symbol.getSymbolSize = function (data, idx) {
  35085. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  35086. return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  35087. };
  35088. return Symbol;
  35089. }(Group);
  35090. function driftSymbol(dx, dy) {
  35091. this.parent.drift(dx, dy);
  35092. }
  35093. function symbolNeedsDraw(data, point, idx, opt) {
  35094. 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
  35095. // the symbol element shape. We use the same clip shape here as
  35096. // the line clip.
  35097. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  35098. }
  35099. function normalizeUpdateOpt(opt) {
  35100. if (opt != null && !isObject(opt)) {
  35101. opt = {
  35102. isIgnore: opt
  35103. };
  35104. }
  35105. return opt || {};
  35106. }
  35107. function makeSeriesScope(data) {
  35108. var seriesModel = data.hostModel;
  35109. var emphasisModel = seriesModel.getModel('emphasis');
  35110. return {
  35111. emphasisItemStyle: emphasisModel.getModel('itemStyle').getItemStyle(),
  35112. blurItemStyle: seriesModel.getModel(['blur', 'itemStyle']).getItemStyle(),
  35113. selectItemStyle: seriesModel.getModel(['select', 'itemStyle']).getItemStyle(),
  35114. focus: emphasisModel.get('focus'),
  35115. blurScope: emphasisModel.get('blurScope'),
  35116. symbolRotate: seriesModel.get('symbolRotate'),
  35117. symbolOffset: seriesModel.get('symbolOffset'),
  35118. hoverScale: emphasisModel.get('scale'),
  35119. labelStatesModels: getLabelStatesModels(seriesModel),
  35120. cursorStyle: seriesModel.get('cursor')
  35121. };
  35122. }
  35123. var SymbolDraw =
  35124. /** @class */
  35125. function () {
  35126. function SymbolDraw(SymbolCtor) {
  35127. this.group = new Group();
  35128. this._SymbolCtor = SymbolCtor || Symbol;
  35129. }
  35130. /**
  35131. * Update symbols draw by new data
  35132. */
  35133. SymbolDraw.prototype.updateData = function (data, opt) {
  35134. opt = normalizeUpdateOpt(opt);
  35135. var group = this.group;
  35136. var seriesModel = data.hostModel;
  35137. var oldData = this._data;
  35138. var SymbolCtor = this._SymbolCtor;
  35139. var disableAnimation = opt.disableAnimation;
  35140. var seriesScope = makeSeriesScope(data);
  35141. var symbolUpdateOpt = {
  35142. disableAnimation: disableAnimation
  35143. };
  35144. var getSymbolPoint = opt.getSymbolPoint || function (idx) {
  35145. return data.getItemLayout(idx);
  35146. }; // There is no oldLineData only when first rendering or switching from
  35147. // stream mode to normal mode, where previous elements should be removed.
  35148. if (!oldData) {
  35149. group.removeAll();
  35150. }
  35151. data.diff(oldData).add(function (newIdx) {
  35152. var point = getSymbolPoint(newIdx);
  35153. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  35154. var symbolEl = new SymbolCtor(data, newIdx, seriesScope, symbolUpdateOpt);
  35155. symbolEl.setPosition(point);
  35156. data.setItemGraphicEl(newIdx, symbolEl);
  35157. group.add(symbolEl);
  35158. }
  35159. }).update(function (newIdx, oldIdx) {
  35160. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  35161. var point = getSymbolPoint(newIdx);
  35162. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  35163. group.remove(symbolEl);
  35164. return;
  35165. }
  35166. if (!symbolEl) {
  35167. symbolEl = new SymbolCtor(data, newIdx);
  35168. symbolEl.setPosition(point);
  35169. } else {
  35170. symbolEl.updateData(data, newIdx, seriesScope, symbolUpdateOpt);
  35171. var target = {
  35172. x: point[0],
  35173. y: point[1]
  35174. };
  35175. disableAnimation ? symbolEl.attr(target) : updateProps(symbolEl, target, seriesModel);
  35176. } // Add back
  35177. group.add(symbolEl);
  35178. data.setItemGraphicEl(newIdx, symbolEl);
  35179. }).remove(function (oldIdx) {
  35180. var el = oldData.getItemGraphicEl(oldIdx);
  35181. el && el.fadeOut(function () {
  35182. group.remove(el);
  35183. });
  35184. }).execute();
  35185. this._getSymbolPoint = getSymbolPoint;
  35186. this._data = data;
  35187. };
  35188. SymbolDraw.prototype.isPersistent = function () {
  35189. return true;
  35190. };
  35191. SymbolDraw.prototype.updateLayout = function () {
  35192. var _this = this;
  35193. var data = this._data;
  35194. if (data) {
  35195. // Not use animation
  35196. data.eachItemGraphicEl(function (el, idx) {
  35197. var point = _this._getSymbolPoint(idx);
  35198. el.setPosition(point);
  35199. el.markRedraw();
  35200. });
  35201. }
  35202. };
  35203. SymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  35204. this._seriesScope = makeSeriesScope(data);
  35205. this._data = null;
  35206. this.group.removeAll();
  35207. };
  35208. /**
  35209. * Update symbols draw by new data
  35210. */
  35211. SymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  35212. opt = normalizeUpdateOpt(opt);
  35213. function updateIncrementalAndHover(el) {
  35214. if (!el.isGroup) {
  35215. el.incremental = true;
  35216. el.ensureState('emphasis').hoverLayer = true;
  35217. }
  35218. }
  35219. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  35220. var point = data.getItemLayout(idx);
  35221. if (symbolNeedsDraw(data, point, idx, opt)) {
  35222. var el = new this._SymbolCtor(data, idx, this._seriesScope);
  35223. el.traverse(updateIncrementalAndHover);
  35224. el.setPosition(point);
  35225. this.group.add(el);
  35226. data.setItemGraphicEl(idx, el);
  35227. }
  35228. }
  35229. };
  35230. SymbolDraw.prototype.remove = function (enableAnimation) {
  35231. var group = this.group;
  35232. var data = this._data; // Incremental model do not have this._data.
  35233. if (data && enableAnimation) {
  35234. data.eachItemGraphicEl(function (el) {
  35235. el.fadeOut(function () {
  35236. group.remove(el);
  35237. });
  35238. });
  35239. } else {
  35240. group.removeAll();
  35241. }
  35242. };
  35243. return SymbolDraw;
  35244. }();
  35245. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  35246. var baseAxis = coordSys.getBaseAxis();
  35247. var valueAxis = coordSys.getOtherAxis(baseAxis);
  35248. var valueStart = getValueStart(valueAxis, valueOrigin);
  35249. var baseAxisDim = baseAxis.dim;
  35250. var valueAxisDim = valueAxis.dim;
  35251. var valueDim = data.mapDimension(valueAxisDim);
  35252. var baseDim = data.mapDimension(baseAxisDim);
  35253. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  35254. var dims = map(coordSys.dimensions, function (coordDim) {
  35255. return data.mapDimension(coordDim);
  35256. });
  35257. var stacked = false;
  35258. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35259. if (isDimensionStacked(data, dims[0]
  35260. /*, dims[1]*/
  35261. )) {
  35262. // jshint ignore:line
  35263. stacked = true;
  35264. dims[0] = stackResultDim;
  35265. }
  35266. if (isDimensionStacked(data, dims[1]
  35267. /*, dims[0]*/
  35268. )) {
  35269. // jshint ignore:line
  35270. stacked = true;
  35271. dims[1] = stackResultDim;
  35272. }
  35273. return {
  35274. dataDimsForPoint: dims,
  35275. valueStart: valueStart,
  35276. valueAxisDim: valueAxisDim,
  35277. baseAxisDim: baseAxisDim,
  35278. stacked: !!stacked,
  35279. valueDim: valueDim,
  35280. baseDim: baseDim,
  35281. baseDataOffset: baseDataOffset,
  35282. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  35283. };
  35284. }
  35285. function getValueStart(valueAxis, valueOrigin) {
  35286. var valueStart = 0;
  35287. var extent = valueAxis.scale.getExtent();
  35288. if (valueOrigin === 'start') {
  35289. valueStart = extent[0];
  35290. } else if (valueOrigin === 'end') {
  35291. valueStart = extent[1];
  35292. } // auto
  35293. else {
  35294. // Both positive
  35295. if (extent[0] > 0) {
  35296. valueStart = extent[0];
  35297. } // Both negative
  35298. else if (extent[1] < 0) {
  35299. valueStart = extent[1];
  35300. } // If is one positive, and one negative, onZero shall be true
  35301. }
  35302. return valueStart;
  35303. }
  35304. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  35305. var value = NaN;
  35306. if (dataCoordInfo.stacked) {
  35307. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  35308. }
  35309. if (isNaN(value)) {
  35310. value = dataCoordInfo.valueStart;
  35311. }
  35312. var baseDataOffset = dataCoordInfo.baseDataOffset;
  35313. var stackedData = [];
  35314. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  35315. stackedData[1 - baseDataOffset] = value;
  35316. return coordSys.dataToPoint(stackedData);
  35317. }
  35318. /* global Float32Array */
  35319. var supportFloat32Array = typeof Float32Array !== 'undefined';
  35320. var Float32ArrayCtor = !supportFloat32Array ? Array : Float32Array;
  35321. function createFloat32Array(arg) {
  35322. if (isArray(arg)) {
  35323. // Return self directly if don't support TypedArray.
  35324. return supportFloat32Array ? new Float32Array(arg) : arg;
  35325. } // Else is number
  35326. return new Float32ArrayCtor(arg);
  35327. }
  35328. function diffData(oldData, newData) {
  35329. var diffResult = [];
  35330. newData.diff(oldData).add(function (idx) {
  35331. diffResult.push({
  35332. cmd: '+',
  35333. idx: idx
  35334. });
  35335. }).update(function (newIdx, oldIdx) {
  35336. diffResult.push({
  35337. cmd: '=',
  35338. idx: oldIdx,
  35339. idx1: newIdx
  35340. });
  35341. }).remove(function (idx) {
  35342. diffResult.push({
  35343. cmd: '-',
  35344. idx: idx
  35345. });
  35346. }).execute();
  35347. return diffResult;
  35348. }
  35349. function lineAnimationDiff(oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  35350. var diff = diffData(oldData, newData); // let newIdList = newData.mapArray(newData.getId);
  35351. // let oldIdList = oldData.mapArray(oldData.getId);
  35352. // convertToIntId(newIdList, oldIdList);
  35353. // // FIXME One data ?
  35354. // diff = arrayDiff(oldIdList, newIdList);
  35355. var currPoints = [];
  35356. var nextPoints = []; // Points for stacking base line
  35357. var currStackedPoints = [];
  35358. var nextStackedPoints = [];
  35359. var status = [];
  35360. var sortedIndices = [];
  35361. var rawIndices = [];
  35362. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  35363. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  35364. var oldPoints = oldData.getLayout('points') || [];
  35365. var newPoints = newData.getLayout('points') || [];
  35366. for (var i = 0; i < diff.length; i++) {
  35367. var diffItem = diff[i];
  35368. var pointAdded = true;
  35369. var oldIdx2 = void 0;
  35370. var newIdx2 = void 0; // FIXME, animation is not so perfect when dataZoom window moves fast
  35371. // Which is in case remvoing or add more than one data in the tail or head
  35372. switch (diffItem.cmd) {
  35373. case '=':
  35374. oldIdx2 = diffItem.idx * 2;
  35375. newIdx2 = diffItem.idx1 * 2;
  35376. var currentX = oldPoints[oldIdx2];
  35377. var currentY = oldPoints[oldIdx2 + 1];
  35378. var nextX = newPoints[newIdx2];
  35379. var nextY = newPoints[newIdx2 + 1]; // If previous data is NaN, use next point directly
  35380. if (isNaN(currentX) || isNaN(currentY)) {
  35381. currentX = nextX;
  35382. currentY = nextY;
  35383. }
  35384. currPoints.push(currentX, currentY);
  35385. nextPoints.push(nextX, nextY);
  35386. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  35387. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35388. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  35389. break;
  35390. case '+':
  35391. var newIdx = diffItem.idx;
  35392. var newDataDimsForPoint = newDataOldCoordInfo.dataDimsForPoint;
  35393. var oldPt = oldCoordSys.dataToPoint([newData.get(newDataDimsForPoint[0], newIdx), newData.get(newDataDimsForPoint[1], newIdx)]);
  35394. newIdx2 = newIdx * 2;
  35395. currPoints.push(oldPt[0], oldPt[1]);
  35396. nextPoints.push(newPoints[newIdx2], newPoints[newIdx2 + 1]);
  35397. var stackedOnPoint = getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, newIdx);
  35398. currStackedPoints.push(stackedOnPoint[0], stackedOnPoint[1]);
  35399. nextStackedPoints.push(newStackedOnPoints[newIdx2], newStackedOnPoints[newIdx2 + 1]);
  35400. rawIndices.push(newData.getRawIndex(newIdx));
  35401. break;
  35402. case '-':
  35403. var oldIdx = diffItem.idx;
  35404. var rawIndex = oldData.getRawIndex(oldIdx);
  35405. var oldDataDimsForPoint = oldDataNewCoordInfo.dataDimsForPoint;
  35406. oldIdx2 = oldIdx * 2; // Data is replaced. In the case of dynamic data queue
  35407. // FIXME FIXME FIXME
  35408. if (rawIndex !== oldIdx) {
  35409. var newPt = newCoordSys.dataToPoint([oldData.get(oldDataDimsForPoint[0], oldIdx), oldData.get(oldDataDimsForPoint[1], oldIdx)]);
  35410. var newStackedOnPt = getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, oldIdx);
  35411. currPoints.push(oldPoints[oldIdx2], oldPoints[oldIdx2 + 1]);
  35412. nextPoints.push(newPt[0], newPt[1]);
  35413. currStackedPoints.push(oldStackedOnPoints[oldIdx2], oldStackedOnPoints[oldIdx2 + 1]);
  35414. nextStackedPoints.push(newStackedOnPt[0], newStackedOnPt[1]);
  35415. rawIndices.push(rawIndex);
  35416. } else {
  35417. pointAdded = false;
  35418. }
  35419. } // Original indices
  35420. if (pointAdded) {
  35421. status.push(diffItem);
  35422. sortedIndices.push(sortedIndices.length);
  35423. }
  35424. } // Diff result may be crossed if all items are changed
  35425. // Sort by data index
  35426. sortedIndices.sort(function (a, b) {
  35427. return rawIndices[a] - rawIndices[b];
  35428. });
  35429. var len = currPoints.length;
  35430. var sortedCurrPoints = createFloat32Array(len);
  35431. var sortedNextPoints = createFloat32Array(len);
  35432. var sortedCurrStackedPoints = createFloat32Array(len);
  35433. var sortedNextStackedPoints = createFloat32Array(len);
  35434. var sortedStatus = [];
  35435. for (var i = 0; i < sortedIndices.length; i++) {
  35436. var idx = sortedIndices[i];
  35437. var i2 = i * 2;
  35438. var idx2 = idx * 2;
  35439. sortedCurrPoints[i2] = currPoints[idx2];
  35440. sortedCurrPoints[i2 + 1] = currPoints[idx2 + 1];
  35441. sortedNextPoints[i2] = nextPoints[idx2];
  35442. sortedNextPoints[i2 + 1] = nextPoints[idx2 + 1];
  35443. sortedCurrStackedPoints[i2] = currStackedPoints[idx2];
  35444. sortedCurrStackedPoints[i2 + 1] = currStackedPoints[idx2 + 1];
  35445. sortedNextStackedPoints[i2] = nextStackedPoints[idx2];
  35446. sortedNextStackedPoints[i2 + 1] = nextStackedPoints[idx2 + 1];
  35447. sortedStatus[i] = status[idx];
  35448. }
  35449. return {
  35450. current: sortedCurrPoints,
  35451. next: sortedNextPoints,
  35452. stackedOnCurrent: sortedCurrStackedPoints,
  35453. stackedOnNext: sortedNextStackedPoints,
  35454. status: sortedStatus
  35455. };
  35456. }
  35457. var mathMin$5 = Math.min;
  35458. var mathMax$5 = Math.max;
  35459. function isPointNull(x, y) {
  35460. return isNaN(x) || isNaN(y);
  35461. }
  35462. /**
  35463. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  35464. * situations. This should be used when points are non-monotone neither in x or
  35465. * y dimension.
  35466. */
  35467. function drawSegment(ctx, points, start, segLen, allLen, dir, smooth, smoothMonotone, connectNulls) {
  35468. var prevX;
  35469. var prevY;
  35470. var cpx0;
  35471. var cpy0;
  35472. var cpx1;
  35473. var cpy1;
  35474. var idx = start;
  35475. var k = 0;
  35476. for (; k < segLen; k++) {
  35477. var x = points[idx * 2];
  35478. var y = points[idx * 2 + 1];
  35479. if (idx >= allLen || idx < 0) {
  35480. break;
  35481. }
  35482. if (isPointNull(x, y)) {
  35483. if (connectNulls) {
  35484. idx += dir;
  35485. continue;
  35486. }
  35487. break;
  35488. }
  35489. if (idx === start) {
  35490. ctx[dir > 0 ? 'moveTo' : 'lineTo'](x, y);
  35491. cpx0 = x;
  35492. cpy0 = y;
  35493. } else {
  35494. var dx = x - prevX;
  35495. var dy = y - prevY; // Ignore tiny segment.
  35496. if (dx * dx + dy * dy < 0.5) {
  35497. idx += dir;
  35498. continue;
  35499. }
  35500. if (smooth > 0) {
  35501. var nextIdx = idx + dir;
  35502. var nextX = points[nextIdx * 2];
  35503. var nextY = points[nextIdx * 2 + 1];
  35504. var tmpK = k + 1;
  35505. if (connectNulls) {
  35506. // Find next point not null
  35507. while (isPointNull(nextX, nextY) && tmpK < segLen) {
  35508. tmpK++;
  35509. nextIdx += dir;
  35510. nextX = points[nextIdx * 2];
  35511. nextY = points[nextIdx * 2 + 1];
  35512. }
  35513. }
  35514. var ratioNextSeg = 0.5;
  35515. var vx = 0;
  35516. var vy = 0;
  35517. var nextCpx0 = void 0;
  35518. var nextCpy0 = void 0; // Is last point
  35519. if (tmpK >= segLen || isPointNull(nextX, nextY)) {
  35520. cpx1 = x;
  35521. cpy1 = y;
  35522. } else {
  35523. vx = nextX - prevX;
  35524. vy = nextY - prevY;
  35525. var dx0 = x - prevX;
  35526. var dx1 = nextX - x;
  35527. var dy0 = y - prevY;
  35528. var dy1 = nextY - y;
  35529. var lenPrevSeg = void 0;
  35530. var lenNextSeg = void 0;
  35531. if (smoothMonotone === 'x') {
  35532. lenPrevSeg = Math.abs(dx0);
  35533. lenNextSeg = Math.abs(dx1);
  35534. cpx1 = x - lenPrevSeg * smooth;
  35535. cpy1 = y;
  35536. nextCpx0 = x + lenPrevSeg * smooth;
  35537. nextCpy0 = y;
  35538. } else if (smoothMonotone === 'y') {
  35539. lenPrevSeg = Math.abs(dy0);
  35540. lenNextSeg = Math.abs(dy1);
  35541. cpx1 = x;
  35542. cpy1 = y - lenPrevSeg * smooth;
  35543. nextCpx0 = x;
  35544. nextCpy0 = y + lenPrevSeg * smooth;
  35545. } else {
  35546. lenPrevSeg = Math.sqrt(dx0 * dx0 + dy0 * dy0);
  35547. lenNextSeg = Math.sqrt(dx1 * dx1 + dy1 * dy1); // Use ratio of seg length
  35548. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  35549. cpx1 = x - vx * smooth * (1 - ratioNextSeg);
  35550. cpy1 = y - vy * smooth * (1 - ratioNextSeg); // cp0 of next segment
  35551. nextCpx0 = x + vx * smooth * ratioNextSeg;
  35552. nextCpy0 = y + vy * smooth * ratioNextSeg; // Smooth constraint between point and next point.
  35553. // Avoid exceeding extreme after smoothing.
  35554. nextCpx0 = mathMin$5(nextCpx0, mathMax$5(nextX, x));
  35555. nextCpy0 = mathMin$5(nextCpy0, mathMax$5(nextY, y));
  35556. nextCpx0 = mathMax$5(nextCpx0, mathMin$5(nextX, x));
  35557. nextCpy0 = mathMax$5(nextCpy0, mathMin$5(nextY, y)); // Reclaculate cp1 based on the adjusted cp0 of next seg.
  35558. vx = nextCpx0 - x;
  35559. vy = nextCpy0 - y;
  35560. cpx1 = x - vx * lenPrevSeg / lenNextSeg;
  35561. cpy1 = y - vy * lenPrevSeg / lenNextSeg; // Smooth constraint between point and prev point.
  35562. // Avoid exceeding extreme after smoothing.
  35563. cpx1 = mathMin$5(cpx1, mathMax$5(prevX, x));
  35564. cpy1 = mathMin$5(cpy1, mathMax$5(prevY, y));
  35565. cpx1 = mathMax$5(cpx1, mathMin$5(prevX, x));
  35566. cpy1 = mathMax$5(cpy1, mathMin$5(prevY, y)); // Adjust next cp0 again.
  35567. vx = x - cpx1;
  35568. vy = y - cpy1;
  35569. nextCpx0 = x + vx * lenNextSeg / lenPrevSeg;
  35570. nextCpy0 = y + vy * lenNextSeg / lenPrevSeg;
  35571. }
  35572. }
  35573. ctx.bezierCurveTo(cpx0, cpy0, cpx1, cpy1, x, y);
  35574. cpx0 = nextCpx0;
  35575. cpy0 = nextCpy0;
  35576. } else {
  35577. ctx.lineTo(x, y);
  35578. }
  35579. }
  35580. prevX = x;
  35581. prevY = y;
  35582. idx += dir;
  35583. }
  35584. return k;
  35585. }
  35586. var ECPolylineShape =
  35587. /** @class */
  35588. function () {
  35589. function ECPolylineShape() {
  35590. this.smooth = 0;
  35591. this.smoothConstraint = true;
  35592. }
  35593. return ECPolylineShape;
  35594. }();
  35595. var ECPolyline =
  35596. /** @class */
  35597. function (_super) {
  35598. __extends(ECPolyline, _super);
  35599. function ECPolyline(opts) {
  35600. var _this = _super.call(this, opts) || this;
  35601. _this.type = 'ec-polyline';
  35602. return _this;
  35603. }
  35604. ECPolyline.prototype.getDefaultStyle = function () {
  35605. return {
  35606. stroke: '#000',
  35607. fill: null
  35608. };
  35609. };
  35610. ECPolyline.prototype.getDefaultShape = function () {
  35611. return new ECPolylineShape();
  35612. };
  35613. ECPolyline.prototype.buildPath = function (ctx, shape) {
  35614. var points = shape.points;
  35615. var i = 0;
  35616. var len = points.length / 2; // const result = getBoundingBox(points, shape.smoothConstraint);
  35617. if (shape.connectNulls) {
  35618. // Must remove first and last null values avoid draw error in polygon
  35619. for (; len > 0; len--) {
  35620. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  35621. break;
  35622. }
  35623. }
  35624. for (; i < len; i++) {
  35625. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  35626. break;
  35627. }
  35628. }
  35629. }
  35630. while (i < len) {
  35631. i += drawSegment(ctx, points, i, len, len, 1, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  35632. }
  35633. };
  35634. ECPolyline.prototype.getPointOn = function (xOrY, dim) {
  35635. if (!this.path) {
  35636. this.createPathProxy();
  35637. this.buildPath(this.path, this.shape);
  35638. }
  35639. var path = this.path;
  35640. var data = path.data;
  35641. var CMD = PathProxy.CMD;
  35642. var x0;
  35643. var y0;
  35644. var isDimX = dim === 'x';
  35645. var roots = [];
  35646. for (var i = 0; i < data.length;) {
  35647. var cmd = data[i++];
  35648. var x = void 0;
  35649. var y = void 0;
  35650. var x2 = void 0;
  35651. var y2 = void 0;
  35652. var x3 = void 0;
  35653. var y3 = void 0;
  35654. var t = void 0;
  35655. switch (cmd) {
  35656. case CMD.M:
  35657. x0 = data[i++];
  35658. y0 = data[i++];
  35659. break;
  35660. case CMD.L:
  35661. x = data[i++];
  35662. y = data[i++];
  35663. t = isDimX ? (xOrY - x0) / (x - x0) : (xOrY - y0) / (y - y0);
  35664. if (t <= 1 && t >= 0) {
  35665. var val = isDimX ? (y - y0) * t + y0 : (x - x0) * t + x0;
  35666. return isDimX ? [xOrY, val] : [val, xOrY];
  35667. }
  35668. x0 = x;
  35669. y0 = y;
  35670. break;
  35671. case CMD.C:
  35672. x = data[i++];
  35673. y = data[i++];
  35674. x2 = data[i++];
  35675. y2 = data[i++];
  35676. x3 = data[i++];
  35677. y3 = data[i++];
  35678. var nRoot = isDimX ? cubicRootAt(x0, x, x2, x3, xOrY, roots) : cubicRootAt(y0, y, y2, y3, xOrY, roots);
  35679. if (nRoot > 0) {
  35680. for (var i_1 = 0; i_1 < nRoot; i_1++) {
  35681. var t_1 = roots[i_1];
  35682. if (t_1 <= 1 && t_1 >= 0) {
  35683. var val = isDimX ? cubicAt(y0, y, y2, y3, t_1) : cubicAt(x0, x, x2, x3, t_1);
  35684. return isDimX ? [xOrY, val] : [val, xOrY];
  35685. }
  35686. }
  35687. }
  35688. x0 = x3;
  35689. y0 = y3;
  35690. break;
  35691. }
  35692. }
  35693. };
  35694. return ECPolyline;
  35695. }(Path);
  35696. var ECPolygonShape =
  35697. /** @class */
  35698. function (_super) {
  35699. __extends(ECPolygonShape, _super);
  35700. function ECPolygonShape() {
  35701. return _super !== null && _super.apply(this, arguments) || this;
  35702. }
  35703. return ECPolygonShape;
  35704. }(ECPolylineShape);
  35705. var ECPolygon =
  35706. /** @class */
  35707. function (_super) {
  35708. __extends(ECPolygon, _super);
  35709. function ECPolygon(opts) {
  35710. var _this = _super.call(this, opts) || this;
  35711. _this.type = 'ec-polygon';
  35712. return _this;
  35713. }
  35714. ECPolygon.prototype.getDefaultShape = function () {
  35715. return new ECPolygonShape();
  35716. };
  35717. ECPolygon.prototype.buildPath = function (ctx, shape) {
  35718. var points = shape.points;
  35719. var stackedOnPoints = shape.stackedOnPoints;
  35720. var i = 0;
  35721. var len = points.length / 2;
  35722. var smoothMonotone = shape.smoothMonotone;
  35723. if (shape.connectNulls) {
  35724. // Must remove first and last null values avoid draw error in polygon
  35725. for (; len > 0; len--) {
  35726. if (!isPointNull(points[len * 2 - 2], points[len * 2 - 1])) {
  35727. break;
  35728. }
  35729. }
  35730. for (; i < len; i++) {
  35731. if (!isPointNull(points[i * 2], points[i * 2 + 1])) {
  35732. break;
  35733. }
  35734. }
  35735. }
  35736. while (i < len) {
  35737. var k = drawSegment(ctx, points, i, len, len, 1, shape.smooth, smoothMonotone, shape.connectNulls);
  35738. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len, -1, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  35739. i += k + 1;
  35740. ctx.closePath();
  35741. }
  35742. };
  35743. return ECPolygon;
  35744. }(Path);
  35745. function createGridClipPath(cartesian, hasAnimation, seriesModel, done, during) {
  35746. var rect = cartesian.getArea();
  35747. var x = rect.x;
  35748. var y = rect.y;
  35749. var width = rect.width;
  35750. var height = rect.height;
  35751. var lineWidth = seriesModel.get(['lineStyle', 'width']) || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  35752. x -= lineWidth / 2;
  35753. y -= lineWidth / 2;
  35754. width += lineWidth;
  35755. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  35756. x = Math.floor(x);
  35757. width = Math.round(width);
  35758. var clipPath = new Rect({
  35759. shape: {
  35760. x: x,
  35761. y: y,
  35762. width: width,
  35763. height: height
  35764. }
  35765. });
  35766. if (hasAnimation) {
  35767. var baseAxis = cartesian.getBaseAxis();
  35768. var isHorizontal = baseAxis.isHorizontal();
  35769. var isAxisInversed = baseAxis.inverse;
  35770. if (isHorizontal) {
  35771. if (isAxisInversed) {
  35772. clipPath.shape.x += width;
  35773. }
  35774. clipPath.shape.width = 0;
  35775. } else {
  35776. if (!isAxisInversed) {
  35777. clipPath.shape.y += height;
  35778. }
  35779. clipPath.shape.height = 0;
  35780. }
  35781. var duringCb = typeof during === 'function' ? function (percent) {
  35782. during(percent, clipPath);
  35783. } : null;
  35784. initProps(clipPath, {
  35785. shape: {
  35786. width: width,
  35787. height: height,
  35788. x: x,
  35789. y: y
  35790. }
  35791. }, seriesModel, null, done, duringCb);
  35792. }
  35793. return clipPath;
  35794. }
  35795. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  35796. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  35797. var r0 = round(sectorArea.r0, 1);
  35798. var r = round(sectorArea.r, 1);
  35799. var clipPath = new Sector({
  35800. shape: {
  35801. cx: round(polar.cx, 1),
  35802. cy: round(polar.cy, 1),
  35803. r0: r0,
  35804. r: r,
  35805. startAngle: sectorArea.startAngle,
  35806. endAngle: sectorArea.endAngle,
  35807. clockwise: sectorArea.clockwise
  35808. }
  35809. });
  35810. if (hasAnimation) {
  35811. var isRadial = polar.getBaseAxis().dim === 'angle';
  35812. if (isRadial) {
  35813. clipPath.shape.endAngle = sectorArea.startAngle;
  35814. } else {
  35815. clipPath.shape.r = r0;
  35816. }
  35817. initProps(clipPath, {
  35818. shape: {
  35819. endAngle: sectorArea.endAngle,
  35820. r: r
  35821. }
  35822. }, seriesModel);
  35823. }
  35824. return clipPath;
  35825. }
  35826. function createClipPath(coordSys, hasAnimation, seriesModel, done, during) {
  35827. if (!coordSys) {
  35828. return null;
  35829. } else if (coordSys.type === 'polar') {
  35830. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  35831. } else if (coordSys.type === 'cartesian2d') {
  35832. return createGridClipPath(coordSys, hasAnimation, seriesModel, done, during);
  35833. }
  35834. return null;
  35835. }
  35836. /*
  35837. * Licensed to the Apache Software Foundation (ASF) under one
  35838. * or more contributor license agreements. See the NOTICE file
  35839. * distributed with this work for additional information
  35840. * regarding copyright ownership. The ASF licenses this file
  35841. * to you under the Apache License, Version 2.0 (the
  35842. * "License"); you may not use this file except in compliance
  35843. * with the License. You may obtain a copy of the License at
  35844. *
  35845. * http://www.apache.org/licenses/LICENSE-2.0
  35846. *
  35847. * Unless required by applicable law or agreed to in writing,
  35848. * software distributed under the License is distributed on an
  35849. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35850. * KIND, either express or implied. See the License for the
  35851. * specific language governing permissions and limitations
  35852. * under the License.
  35853. */
  35854. /**
  35855. * AUTO-GENERATED FILE. DO NOT MODIFY.
  35856. */
  35857. /*
  35858. * Licensed to the Apache Software Foundation (ASF) under one
  35859. * or more contributor license agreements. See the NOTICE file
  35860. * distributed with this work for additional information
  35861. * regarding copyright ownership. The ASF licenses this file
  35862. * to you under the Apache License, Version 2.0 (the
  35863. * "License"); you may not use this file except in compliance
  35864. * with the License. You may obtain a copy of the License at
  35865. *
  35866. * http://www.apache.org/licenses/LICENSE-2.0
  35867. *
  35868. * Unless required by applicable law or agreed to in writing,
  35869. * software distributed under the License is distributed on an
  35870. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35871. * KIND, either express or implied. See the License for the
  35872. * specific language governing permissions and limitations
  35873. * under the License.
  35874. */
  35875. function isCoordinateSystemType(coordSys, type) {
  35876. return coordSys.type === type;
  35877. }
  35878. function isPointsSame(points1, points2) {
  35879. if (points1.length !== points2.length) {
  35880. return;
  35881. }
  35882. for (var i = 0; i < points1.length; i++) {
  35883. if (points1[i] !== points2[i]) {
  35884. return;
  35885. }
  35886. }
  35887. return true;
  35888. }
  35889. function bboxFromPoints(points) {
  35890. var minX = Infinity;
  35891. var minY = Infinity;
  35892. var maxX = -Infinity;
  35893. var maxY = -Infinity;
  35894. for (var i = 0; i < points.length;) {
  35895. var x = points[i++];
  35896. var y = points[i++];
  35897. if (!isNaN(x)) {
  35898. minX = Math.min(x, minX);
  35899. maxX = Math.max(x, maxX);
  35900. }
  35901. if (!isNaN(y)) {
  35902. minY = Math.min(y, minY);
  35903. maxY = Math.max(y, maxY);
  35904. }
  35905. }
  35906. return [[minX, minY], [maxX, maxY]];
  35907. }
  35908. function getBoundingDiff(points1, points2) {
  35909. var _a = bboxFromPoints(points1),
  35910. min1 = _a[0],
  35911. max1 = _a[1];
  35912. var _b = bboxFromPoints(points2),
  35913. min2 = _b[0],
  35914. max2 = _b[1]; // Get a max value from each corner of two boundings.
  35915. 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]));
  35916. }
  35917. function getSmooth(smooth) {
  35918. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  35919. }
  35920. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  35921. if (!dataCoordInfo.valueDim) {
  35922. return [];
  35923. }
  35924. var len = data.count();
  35925. var points = createFloat32Array(len * 2);
  35926. for (var idx = 0; idx < len; idx++) {
  35927. var pt = getStackedOnPoint(dataCoordInfo, coordSys, data, idx);
  35928. points[idx * 2] = pt[0];
  35929. points[idx * 2 + 1] = pt[1];
  35930. }
  35931. return points;
  35932. }
  35933. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  35934. var baseAxis = coordSys.getBaseAxis();
  35935. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  35936. var stepPoints = [];
  35937. var i = 0;
  35938. var stepPt = [];
  35939. var pt = [];
  35940. var nextPt = [];
  35941. for (; i < points.length - 2; i += 2) {
  35942. nextPt[0] = points[i + 2];
  35943. nextPt[1] = points[i + 3];
  35944. pt[0] = points[i];
  35945. pt[1] = points[i + 1];
  35946. stepPoints.push(pt[0], pt[1]);
  35947. switch (stepTurnAt) {
  35948. case 'end':
  35949. stepPt[baseIndex] = nextPt[baseIndex];
  35950. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35951. stepPoints.push(stepPt[0], stepPt[1]);
  35952. break;
  35953. case 'middle':
  35954. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  35955. var stepPt2 = [];
  35956. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  35957. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  35958. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  35959. stepPoints.push(stepPt[0], stepPt[1]);
  35960. stepPoints.push(stepPt2[0], stepPt2[1]);
  35961. break;
  35962. default:
  35963. // default is start
  35964. stepPt[baseIndex] = pt[baseIndex];
  35965. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  35966. stepPoints.push(stepPt[0], stepPt[1]);
  35967. }
  35968. } // Last points
  35969. stepPoints.push(points[i++], points[i++]);
  35970. return stepPoints;
  35971. }
  35972. function getVisualGradient(data, coordSys) {
  35973. var visualMetaList = data.getVisual('visualMeta');
  35974. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  35975. // When data.count() is 0, gradient range can not be calculated.
  35976. return;
  35977. }
  35978. if (coordSys.type !== 'cartesian2d') {
  35979. if ("development" !== 'production') {
  35980. console.warn('Visual map on line style is only supported on cartesian2d.');
  35981. }
  35982. return;
  35983. }
  35984. var coordDim;
  35985. var visualMeta;
  35986. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  35987. var dimIndex = visualMetaList[i].dimension;
  35988. var dimName = data.dimensions[dimIndex];
  35989. var dimInfo = data.getDimensionInfo(dimName);
  35990. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  35991. if (coordDim === 'x' || coordDim === 'y') {
  35992. visualMeta = visualMetaList[i];
  35993. break;
  35994. }
  35995. }
  35996. if (!visualMeta) {
  35997. if ("development" !== 'production') {
  35998. console.warn('Visual map on line style only support x or y dimension.');
  35999. }
  36000. return;
  36001. } // If the area to be rendered is bigger than area defined by LinearGradient,
  36002. // the canvas spec prescribes that the color of the first stop and the last
  36003. // stop should be used. But if two stops are added at offset 0, in effect
  36004. // browsers use the color of the second stop to render area outside
  36005. // LinearGradient. So we can only infinitesimally extend area defined in
  36006. // LinearGradient to render `outerColors`.
  36007. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic.
  36008. var colorStops = map(visualMeta.stops, function (stop) {
  36009. return {
  36010. offset: 0,
  36011. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  36012. color: stop.color
  36013. };
  36014. });
  36015. var stopLen = colorStops.length;
  36016. var outerColors = visualMeta.outerColors.slice();
  36017. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  36018. colorStops.reverse();
  36019. outerColors.reverse();
  36020. }
  36021. var tinyExtent = 10; // Arbitrary value: 10px
  36022. var minCoord = colorStops[0].coord - tinyExtent;
  36023. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  36024. var coordSpan = maxCoord - minCoord;
  36025. if (coordSpan < 1e-3) {
  36026. return 'transparent';
  36027. }
  36028. each(colorStops, function (stop) {
  36029. stop.offset = (stop.coord - minCoord) / coordSpan;
  36030. });
  36031. colorStops.push({
  36032. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  36033. color: outerColors[1] || 'transparent'
  36034. });
  36035. colorStops.unshift({
  36036. offset: stopLen ? colorStops[0].offset : 0.5,
  36037. color: outerColors[0] || 'transparent'
  36038. }); // zrUtil.each(colorStops, function (colorStop) {
  36039. // // Make sure each offset has rounded px to avoid not sharp edge
  36040. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  36041. // });
  36042. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  36043. gradient[coordDim] = minCoord;
  36044. gradient[coordDim + '2'] = maxCoord;
  36045. return gradient;
  36046. }
  36047. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  36048. var showAllSymbol = seriesModel.get('showAllSymbol');
  36049. var isAuto = showAllSymbol === 'auto';
  36050. if (showAllSymbol && !isAuto) {
  36051. return;
  36052. }
  36053. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  36054. if (!categoryAxis) {
  36055. return;
  36056. } // Note that category label interval strategy might bring some weird effect
  36057. // in some scenario: users may wonder why some of the symbols are not
  36058. // displayed. So we show all symbols as possible as we can.
  36059. if (isAuto // Simplify the logic, do not determine label overlap here.
  36060. && canShowAllSymbolForCategory(categoryAxis, data)) {
  36061. return;
  36062. } // Otherwise follow the label interval strategy on category axis.
  36063. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  36064. var labelMap = {};
  36065. each(categoryAxis.getViewLabels(), function (labelItem) {
  36066. var ordinalNumber = categoryAxis.scale.getRawOrdinalNumber(labelItem.tickValue);
  36067. labelMap[ordinalNumber] = 1;
  36068. });
  36069. return function (dataIndex) {
  36070. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  36071. };
  36072. }
  36073. function canShowAllSymbolForCategory(categoryAxis, data) {
  36074. // In mose cases, line is monotonous on category axis, and the label size
  36075. // is close with each other. So we check the symbol size and some of the
  36076. // label size alone with the category axis to estimate whether all symbol
  36077. // can be shown without overlap.
  36078. var axisExtent = categoryAxis.getExtent();
  36079. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  36080. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  36081. // Sampling some points, max 5.
  36082. var dataLen = data.count();
  36083. var step = Math.max(1, Math.round(dataLen / 5));
  36084. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  36085. if (Symbol.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  36086. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  36087. * 1.5 > availSize) {
  36088. return false;
  36089. }
  36090. }
  36091. return true;
  36092. }
  36093. function isPointNull$1(x, y) {
  36094. return isNaN(x) || isNaN(y);
  36095. }
  36096. function getLastIndexNotNull(points) {
  36097. var len = points.length / 2;
  36098. for (; len > 0; len--) {
  36099. if (!isPointNull$1(points[len * 2 - 2], points[len * 2 - 1])) {
  36100. break;
  36101. }
  36102. }
  36103. return len - 1;
  36104. }
  36105. function getPointAtIndex(points, idx) {
  36106. return [points[idx * 2], points[idx * 2 + 1]];
  36107. }
  36108. function getIndexRange(points, xOrY, dim) {
  36109. var len = points.length / 2;
  36110. var dimIdx = dim === 'x' ? 0 : 1;
  36111. var a;
  36112. var b;
  36113. var prevIndex = 0;
  36114. var nextIndex = -1;
  36115. for (var i = 0; i < len; i++) {
  36116. b = points[i * 2 + dimIdx];
  36117. if (isNaN(b) || isNaN(points[i * 2 + 1 - dimIdx])) {
  36118. continue;
  36119. }
  36120. if (i === 0) {
  36121. a = b;
  36122. continue;
  36123. }
  36124. if (a <= xOrY && b >= xOrY || a >= xOrY && b <= xOrY) {
  36125. nextIndex = i;
  36126. break;
  36127. }
  36128. prevIndex = i;
  36129. a = b;
  36130. }
  36131. return {
  36132. range: [prevIndex, nextIndex],
  36133. t: (xOrY - a) / (b - a)
  36134. };
  36135. }
  36136. function createLineClipPath(lineView, coordSys, hasAnimation, seriesModel) {
  36137. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  36138. var endLabelModel_1 = seriesModel.getModel('endLabel');
  36139. var showEndLabel = endLabelModel_1.get('show');
  36140. var valueAnimation_1 = endLabelModel_1.get('valueAnimation');
  36141. var data_1 = seriesModel.getData();
  36142. var labelAnimationRecord_1 = {
  36143. lastFrameIndex: 0
  36144. };
  36145. var during = showEndLabel ? function (percent, clipRect) {
  36146. lineView._endLabelOnDuring(percent, clipRect, data_1, labelAnimationRecord_1, valueAnimation_1, endLabelModel_1, coordSys);
  36147. } : null;
  36148. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  36149. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel, function () {
  36150. var endLabel = lineView._endLabel;
  36151. if (endLabel && hasAnimation) {
  36152. if (labelAnimationRecord_1.originalX != null) {
  36153. endLabel.attr({
  36154. x: labelAnimationRecord_1.originalX,
  36155. y: labelAnimationRecord_1.originalY
  36156. });
  36157. }
  36158. }
  36159. }, during); // Expand clip shape to avoid clipping when line value exceeds axis
  36160. if (!seriesModel.get('clip', true)) {
  36161. var rectShape = clipPath.shape;
  36162. var expandSize = Math.max(rectShape.width, rectShape.height);
  36163. if (isHorizontal) {
  36164. rectShape.y -= expandSize;
  36165. rectShape.height += expandSize * 2;
  36166. } else {
  36167. rectShape.x -= expandSize;
  36168. rectShape.width += expandSize * 2;
  36169. }
  36170. } // Set to the final frame. To make sure label layout is right.
  36171. if (during) {
  36172. during(1, clipPath);
  36173. }
  36174. return clipPath;
  36175. } else {
  36176. if ("development" !== 'production') {
  36177. if (seriesModel.get(['endLabel', 'show'])) {
  36178. console.warn('endLabel is not supported for lines in polar systems.');
  36179. }
  36180. }
  36181. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  36182. }
  36183. }
  36184. function getEndLabelStateSpecified(endLabelModel, coordSys) {
  36185. var baseAxis = coordSys.getBaseAxis();
  36186. var isHorizontal = baseAxis.isHorizontal();
  36187. var isBaseInversed = baseAxis.inverse;
  36188. var align = isHorizontal ? isBaseInversed ? 'right' : 'left' : 'center';
  36189. var verticalAlign = isHorizontal ? 'middle' : isBaseInversed ? 'top' : 'bottom';
  36190. return {
  36191. normal: {
  36192. align: endLabelModel.get('align') || align,
  36193. verticalAlign: endLabelModel.get('verticalAlign') || verticalAlign
  36194. }
  36195. };
  36196. }
  36197. var LineView =
  36198. /** @class */
  36199. function (_super) {
  36200. __extends(LineView, _super);
  36201. function LineView() {
  36202. return _super !== null && _super.apply(this, arguments) || this;
  36203. }
  36204. LineView.prototype.init = function () {
  36205. var lineGroup = new Group();
  36206. var symbolDraw = new SymbolDraw();
  36207. this.group.add(symbolDraw.group);
  36208. this._symbolDraw = symbolDraw;
  36209. this._lineGroup = lineGroup;
  36210. };
  36211. LineView.prototype.render = function (seriesModel, ecModel, api) {
  36212. var _this = this;
  36213. var coordSys = seriesModel.coordinateSystem;
  36214. var group = this.group;
  36215. var data = seriesModel.getData();
  36216. var lineStyleModel = seriesModel.getModel('lineStyle');
  36217. var areaStyleModel = seriesModel.getModel('areaStyle');
  36218. var points = data.getLayout('points') || [];
  36219. var isCoordSysPolar = coordSys.type === 'polar';
  36220. var prevCoordSys = this._coordSys;
  36221. var symbolDraw = this._symbolDraw;
  36222. var polyline = this._polyline;
  36223. var polygon = this._polygon;
  36224. var lineGroup = this._lineGroup;
  36225. var hasAnimation = seriesModel.get('animation');
  36226. var isAreaChart = !areaStyleModel.isEmpty();
  36227. var valueOrigin = areaStyleModel.get('origin');
  36228. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  36229. var stackedOnPoints = isAreaChart && getStackedOnPoints(coordSys, data, dataCoordInfo);
  36230. var showSymbol = seriesModel.get('showSymbol');
  36231. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  36232. var oldData = this._data;
  36233. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  36234. if (el.__temp) {
  36235. group.remove(el);
  36236. oldData.setItemGraphicEl(idx, null);
  36237. }
  36238. }); // Remove previous created symbols if showSymbol changed to false
  36239. if (!showSymbol) {
  36240. symbolDraw.remove();
  36241. }
  36242. group.add(lineGroup); // FIXME step not support polar
  36243. var step = !isCoordSysPolar ? seriesModel.get('step') : false;
  36244. var clipShapeForSymbol;
  36245. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  36246. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  36247. // See #7913 and `test/dataZoom-clip.html`.
  36248. if (clipShapeForSymbol.width != null) {
  36249. clipShapeForSymbol.x -= 0.1;
  36250. clipShapeForSymbol.y -= 0.1;
  36251. clipShapeForSymbol.width += 0.2;
  36252. clipShapeForSymbol.height += 0.2;
  36253. } else if (clipShapeForSymbol.r0) {
  36254. clipShapeForSymbol.r0 -= 0.5;
  36255. clipShapeForSymbol.r += 0.5;
  36256. }
  36257. }
  36258. this._clipShapeForSymbol = clipShapeForSymbol;
  36259. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('style')[data.getVisual('drawType')]; // Initialization animation or coordinate system changed
  36260. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  36261. showSymbol && symbolDraw.updateData(data, {
  36262. isIgnore: isIgnoreFunc,
  36263. clipShape: clipShapeForSymbol,
  36264. disableAnimation: true,
  36265. getSymbolPoint: function (idx) {
  36266. return [points[idx * 2], points[idx * 2 + 1]];
  36267. }
  36268. });
  36269. hasAnimation && this._initSymbolLabelAnimation(data, coordSys, clipShapeForSymbol);
  36270. if (step) {
  36271. // TODO If stacked series is not step
  36272. points = turnPointsIntoStep(points, coordSys, step);
  36273. if (stackedOnPoints) {
  36274. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  36275. }
  36276. }
  36277. polyline = this._newPolyline(points);
  36278. if (isAreaChart) {
  36279. polygon = this._newPolygon(points, stackedOnPoints);
  36280. } // NOTE: Must update _endLabel before setClipPath.
  36281. if (!isCoordSysPolar) {
  36282. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36283. }
  36284. lineGroup.setClipPath(createLineClipPath(this, coordSys, true, seriesModel));
  36285. } else {
  36286. if (isAreaChart && !polygon) {
  36287. // If areaStyle is added
  36288. polygon = this._newPolygon(points, stackedOnPoints);
  36289. } else if (polygon && !isAreaChart) {
  36290. // If areaStyle is removed
  36291. lineGroup.remove(polygon);
  36292. polygon = this._polygon = null;
  36293. } // NOTE: Must update _endLabel before setClipPath.
  36294. if (!isCoordSysPolar) {
  36295. this._initOrUpdateEndLabel(seriesModel, coordSys, convertToColorString(visualColor));
  36296. } // Update clipPath
  36297. lineGroup.setClipPath(createLineClipPath(this, coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  36298. // because points are not changed
  36299. showSymbol && symbolDraw.updateData(data, {
  36300. isIgnore: isIgnoreFunc,
  36301. clipShape: clipShapeForSymbol,
  36302. disableAnimation: true,
  36303. getSymbolPoint: function (idx) {
  36304. return [points[idx * 2], points[idx * 2 + 1]];
  36305. }
  36306. }); // In the case data zoom triggerred refreshing frequently
  36307. // Data may not change if line has a category axis. So it should animate nothing
  36308. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  36309. if (hasAnimation) {
  36310. this._doUpdateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  36311. } else {
  36312. // Not do it in update with animation
  36313. if (step) {
  36314. // TODO If stacked series is not step
  36315. points = turnPointsIntoStep(points, coordSys, step);
  36316. if (stackedOnPoints) {
  36317. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  36318. }
  36319. }
  36320. polyline.setShape({
  36321. points: points
  36322. });
  36323. polygon && polygon.setShape({
  36324. points: points,
  36325. stackedOnPoints: stackedOnPoints
  36326. });
  36327. }
  36328. }
  36329. }
  36330. var focus = seriesModel.get(['emphasis', 'focus']);
  36331. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  36332. polyline.useStyle(defaults( // Use color in lineStyle first
  36333. lineStyleModel.getLineStyle(), {
  36334. fill: 'none',
  36335. stroke: visualColor,
  36336. lineJoin: 'bevel'
  36337. }));
  36338. setStatesStylesFromModel(polyline, seriesModel, 'lineStyle');
  36339. if (polyline.style.lineWidth > 0 && seriesModel.get(['emphasis', 'lineStyle', 'width']) === 'bolder') {
  36340. var emphasisLineStyle = polyline.getState('emphasis').style;
  36341. emphasisLineStyle.lineWidth = polyline.style.lineWidth + 1;
  36342. } // Needs seriesIndex for focus
  36343. getECData(polyline).seriesIndex = seriesModel.seriesIndex;
  36344. enableHoverEmphasis(polyline, focus, blurScope);
  36345. var smooth = getSmooth(seriesModel.get('smooth'));
  36346. var smoothMonotone = seriesModel.get('smoothMonotone');
  36347. var connectNulls = seriesModel.get('connectNulls');
  36348. polyline.setShape({
  36349. smooth: smooth,
  36350. smoothMonotone: smoothMonotone,
  36351. connectNulls: connectNulls
  36352. });
  36353. if (polygon) {
  36354. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  36355. var stackedOnSmooth = 0;
  36356. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  36357. fill: visualColor,
  36358. opacity: 0.7,
  36359. lineJoin: 'bevel',
  36360. decal: data.getVisual('style').decal
  36361. }));
  36362. if (stackedOnSeries) {
  36363. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  36364. }
  36365. polygon.setShape({
  36366. smooth: smooth,
  36367. stackedOnSmooth: stackedOnSmooth,
  36368. smoothMonotone: smoothMonotone,
  36369. connectNulls: connectNulls
  36370. });
  36371. setStatesStylesFromModel(polygon, seriesModel, 'areaStyle'); // Needs seriesIndex for focus
  36372. getECData(polygon).seriesIndex = seriesModel.seriesIndex;
  36373. enableHoverEmphasis(polygon, focus, blurScope);
  36374. }
  36375. var changePolyState = function (toState) {
  36376. _this._changePolyState(toState);
  36377. };
  36378. data.eachItemGraphicEl(function (el) {
  36379. // Switch polyline / polygon state if element changed its state.
  36380. el && (el.onHoverStateChange = changePolyState);
  36381. });
  36382. this._polyline.onHoverStateChange = changePolyState;
  36383. this._data = data; // Save the coordinate system for transition animation when data changed
  36384. this._coordSys = coordSys;
  36385. this._stackedOnPoints = stackedOnPoints;
  36386. this._points = points;
  36387. this._step = step;
  36388. this._valueOrigin = valueOrigin;
  36389. };
  36390. LineView.prototype.dispose = function () {};
  36391. LineView.prototype.highlight = function (seriesModel, ecModel, api, payload) {
  36392. var data = seriesModel.getData();
  36393. var dataIndex = queryDataIndex(data, payload);
  36394. this._changePolyState('emphasis');
  36395. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  36396. var points = data.getLayout('points');
  36397. var symbol = data.getItemGraphicEl(dataIndex);
  36398. if (!symbol) {
  36399. // Create a temporary symbol if it is not exists
  36400. var x = points[dataIndex * 2];
  36401. var y = points[dataIndex * 2 + 1];
  36402. if (isNaN(x) || isNaN(y)) {
  36403. // Null data
  36404. return;
  36405. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  36406. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(x, y)) {
  36407. return;
  36408. }
  36409. symbol = new Symbol(data, dataIndex);
  36410. symbol.x = x;
  36411. symbol.y = y;
  36412. symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z'));
  36413. symbol.__temp = true;
  36414. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  36415. symbol.stopSymbolAnimation(true);
  36416. this.group.add(symbol);
  36417. }
  36418. symbol.highlight();
  36419. } else {
  36420. // Highlight whole series
  36421. ChartView.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  36422. }
  36423. };
  36424. LineView.prototype.downplay = function (seriesModel, ecModel, api, payload) {
  36425. var data = seriesModel.getData();
  36426. var dataIndex = queryDataIndex(data, payload);
  36427. this._changePolyState('normal');
  36428. if (dataIndex != null && dataIndex >= 0) {
  36429. var symbol = data.getItemGraphicEl(dataIndex);
  36430. if (symbol) {
  36431. if (symbol.__temp) {
  36432. data.setItemGraphicEl(dataIndex, null);
  36433. this.group.remove(symbol);
  36434. } else {
  36435. symbol.downplay();
  36436. }
  36437. }
  36438. } else {
  36439. // FIXME
  36440. // can not downplay completely.
  36441. // Downplay whole series
  36442. ChartView.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  36443. }
  36444. };
  36445. LineView.prototype._changePolyState = function (toState) {
  36446. var polygon = this._polygon;
  36447. setStatesFlag(this._polyline, toState);
  36448. polygon && setStatesFlag(polygon, toState);
  36449. };
  36450. LineView.prototype._newPolyline = function (points) {
  36451. var polyline = this._polyline; // Remove previous created polyline
  36452. if (polyline) {
  36453. this._lineGroup.remove(polyline);
  36454. }
  36455. polyline = new ECPolyline({
  36456. shape: {
  36457. points: points
  36458. },
  36459. segmentIgnoreThreshold: 2,
  36460. z2: 10
  36461. });
  36462. this._lineGroup.add(polyline);
  36463. this._polyline = polyline;
  36464. return polyline;
  36465. };
  36466. LineView.prototype._newPolygon = function (points, stackedOnPoints) {
  36467. var polygon = this._polygon; // Remove previous created polygon
  36468. if (polygon) {
  36469. this._lineGroup.remove(polygon);
  36470. }
  36471. polygon = new ECPolygon({
  36472. shape: {
  36473. points: points,
  36474. stackedOnPoints: stackedOnPoints
  36475. },
  36476. segmentIgnoreThreshold: 2
  36477. });
  36478. this._lineGroup.add(polygon);
  36479. this._polygon = polygon;
  36480. return polygon;
  36481. };
  36482. LineView.prototype._initSymbolLabelAnimation = function (data, coordSys, clipShape) {
  36483. var isHorizontalOrRadial;
  36484. var isCoordSysPolar;
  36485. var baseAxis = coordSys.getBaseAxis();
  36486. var isAxisInverse = baseAxis.inverse;
  36487. if (coordSys.type === 'cartesian2d') {
  36488. isHorizontalOrRadial = baseAxis.isHorizontal();
  36489. isCoordSysPolar = false;
  36490. } else if (coordSys.type === 'polar') {
  36491. isHorizontalOrRadial = baseAxis.dim === 'angle';
  36492. isCoordSysPolar = true;
  36493. }
  36494. var seriesModel = data.hostModel;
  36495. var seriesDuration = seriesModel.get('animationDuration');
  36496. if (typeof seriesDuration === 'function') {
  36497. seriesDuration = seriesDuration(null);
  36498. }
  36499. var seriesDalay = seriesModel.get('animationDelay') || 0;
  36500. var seriesDalayValue = typeof seriesDalay === 'function' ? seriesDalay(null) : seriesDalay;
  36501. data.eachItemGraphicEl(function (symbol, idx) {
  36502. var el = symbol;
  36503. if (el) {
  36504. var point = [symbol.x, symbol.y];
  36505. var start = void 0;
  36506. var end = void 0;
  36507. var current = void 0;
  36508. if (isCoordSysPolar) {
  36509. var polarClip = clipShape;
  36510. var coord = coordSys.pointToCoord(point);
  36511. if (isHorizontalOrRadial) {
  36512. start = polarClip.startAngle;
  36513. end = polarClip.endAngle;
  36514. current = -coord[1] / 180 * Math.PI;
  36515. } else {
  36516. start = polarClip.r0;
  36517. end = polarClip.r;
  36518. current = coord[0];
  36519. }
  36520. } else {
  36521. var gridClip = clipShape;
  36522. if (isHorizontalOrRadial) {
  36523. start = gridClip.x;
  36524. end = gridClip.x + gridClip.width;
  36525. current = symbol.x;
  36526. } else {
  36527. start = gridClip.y + gridClip.height;
  36528. end = gridClip.y;
  36529. current = symbol.y;
  36530. }
  36531. }
  36532. var ratio = end === start ? 0 : (current - start) / (end - start);
  36533. if (isAxisInverse) {
  36534. ratio = 1 - ratio;
  36535. }
  36536. var delay = typeof seriesDalay === 'function' ? seriesDalay(idx) : seriesDuration * ratio + seriesDalayValue;
  36537. var symbolPath = el.getSymbolPath();
  36538. var text = symbolPath.getTextContent();
  36539. el.attr({
  36540. scaleX: 0,
  36541. scaleY: 0
  36542. });
  36543. el.animateTo({
  36544. scaleX: 1,
  36545. scaleY: 1
  36546. }, {
  36547. duration: 200,
  36548. delay: delay
  36549. });
  36550. if (text) {
  36551. text.animateFrom({
  36552. style: {
  36553. opacity: 0
  36554. }
  36555. }, {
  36556. duration: 300,
  36557. delay: delay
  36558. });
  36559. }
  36560. symbolPath.disableLabelAnimation = true;
  36561. }
  36562. });
  36563. };
  36564. LineView.prototype._initOrUpdateEndLabel = function (seriesModel, coordSys, inheritColor) {
  36565. var endLabelModel = seriesModel.getModel('endLabel');
  36566. if (endLabelModel.get('show')) {
  36567. var data_2 = seriesModel.getData();
  36568. var polyline = this._polyline;
  36569. var endLabel = this._endLabel;
  36570. if (!endLabel) {
  36571. endLabel = this._endLabel = new ZRText({
  36572. z2: 200 // should be higher than item symbol
  36573. });
  36574. endLabel.ignoreClip = true;
  36575. polyline.setTextContent(this._endLabel);
  36576. polyline.disableLabelAnimation = true;
  36577. } // Find last non-NaN data to display data
  36578. var dataIndex = getLastIndexNotNull(data_2.getLayout('points'));
  36579. if (dataIndex >= 0) {
  36580. setLabelStyle(polyline, getLabelStatesModels(seriesModel, 'endLabel'), {
  36581. inheritColor: inheritColor,
  36582. labelFetcher: seriesModel,
  36583. labelDataIndex: dataIndex,
  36584. defaultText: function (dataIndex, opt, interpolatedValue) {
  36585. return interpolatedValue != null ? getDefaultInterpolatedLabel(data_2, interpolatedValue) : getDefaultLabel(data_2, dataIndex);
  36586. },
  36587. enableTextSetter: true
  36588. }, getEndLabelStateSpecified(endLabelModel, coordSys));
  36589. polyline.textConfig.position = null;
  36590. }
  36591. } else if (this._endLabel) {
  36592. this._polyline.removeTextContent();
  36593. this._endLabel = null;
  36594. }
  36595. };
  36596. LineView.prototype._endLabelOnDuring = function (percent, clipRect, data, animationRecord, valueAnimation, endLabelModel, coordSys) {
  36597. var endLabel = this._endLabel;
  36598. var polyline = this._polyline;
  36599. if (endLabel) {
  36600. // NOTE: Don't remove percent < 1. percent === 1 means the first frame during render.
  36601. // The label is not prepared at this time.
  36602. if (percent < 1 && animationRecord.originalX == null) {
  36603. animationRecord.originalX = endLabel.x;
  36604. animationRecord.originalY = endLabel.y;
  36605. }
  36606. var points = data.getLayout('points');
  36607. var seriesModel = data.hostModel;
  36608. var connectNulls = seriesModel.get('connectNulls');
  36609. var precision = endLabelModel.get('precision');
  36610. var distance = endLabelModel.get('distance') || 0;
  36611. var baseAxis = coordSys.getBaseAxis();
  36612. var isHorizontal = baseAxis.isHorizontal();
  36613. var isBaseInversed = baseAxis.inverse;
  36614. var clipShape = clipRect.shape;
  36615. var xOrY = isBaseInversed ? isHorizontal ? clipShape.x : clipShape.y + clipShape.height : isHorizontal ? clipShape.x + clipShape.width : clipShape.y;
  36616. var distanceX = (isHorizontal ? distance : 0) * (isBaseInversed ? -1 : 1);
  36617. var distanceY = (isHorizontal ? 0 : -distance) * (isBaseInversed ? -1 : 1);
  36618. var dim = isHorizontal ? 'x' : 'y';
  36619. var dataIndexRange = getIndexRange(points, xOrY, dim);
  36620. var indices = dataIndexRange.range;
  36621. var diff = indices[1] - indices[0];
  36622. var value = void 0;
  36623. if (diff >= 1) {
  36624. // diff > 1 && connectNulls, which is on the null data.
  36625. if (diff > 1 && !connectNulls) {
  36626. var pt = getPointAtIndex(points, indices[0]);
  36627. endLabel.attr({
  36628. x: pt[0] + distanceX,
  36629. y: pt[1] + distanceY
  36630. });
  36631. valueAnimation && (value = seriesModel.getRawValue(indices[0]));
  36632. } else {
  36633. var pt = polyline.getPointOn(xOrY, dim);
  36634. pt && endLabel.attr({
  36635. x: pt[0] + distanceX,
  36636. y: pt[1] + distanceY
  36637. });
  36638. var startValue = seriesModel.getRawValue(indices[0]);
  36639. var endValue = seriesModel.getRawValue(indices[1]);
  36640. valueAnimation && (value = interpolateRawValues(data, precision, startValue, endValue, dataIndexRange.t));
  36641. }
  36642. animationRecord.lastFrameIndex = indices[0];
  36643. } else {
  36644. // If diff <= 0, which is the range is not found(Include NaN)
  36645. // Choose the first point or last point.
  36646. var idx = percent === 1 || animationRecord.lastFrameIndex > 0 ? indices[0] : 0;
  36647. var pt = getPointAtIndex(points, idx);
  36648. valueAnimation && (value = seriesModel.getRawValue(idx));
  36649. endLabel.attr({
  36650. x: pt[0] + distanceX,
  36651. y: pt[1] + distanceY
  36652. });
  36653. }
  36654. if (valueAnimation) {
  36655. labelInner(endLabel).setLabelText(value);
  36656. }
  36657. }
  36658. };
  36659. /**
  36660. * @private
  36661. */
  36662. // FIXME Two value axis
  36663. LineView.prototype._doUpdateAnimation = function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  36664. var polyline = this._polyline;
  36665. var polygon = this._polygon;
  36666. var seriesModel = data.hostModel;
  36667. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin);
  36668. var current = diff.current;
  36669. var stackedOnCurrent = diff.stackedOnCurrent;
  36670. var next = diff.next;
  36671. var stackedOnNext = diff.stackedOnNext;
  36672. if (step) {
  36673. // TODO If stacked series is not step
  36674. current = turnPointsIntoStep(diff.current, coordSys, step);
  36675. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  36676. next = turnPointsIntoStep(diff.next, coordSys, step);
  36677. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  36678. } // Don't apply animation if diff is large.
  36679. // For better result and avoid memory explosion problems like
  36680. // https://github.com/apache/incubator-echarts/issues/12229
  36681. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  36682. polyline.setShape({
  36683. points: next
  36684. });
  36685. if (polygon) {
  36686. polygon.setShape({
  36687. points: next,
  36688. stackedOnPoints: stackedOnNext
  36689. });
  36690. }
  36691. return;
  36692. }
  36693. polyline.shape.__points = diff.current;
  36694. polyline.shape.points = current;
  36695. var target = {
  36696. shape: {
  36697. points: next
  36698. }
  36699. }; // Also animate the original points.
  36700. // If points reference is changed when turning into step line.
  36701. if (diff.current !== current) {
  36702. target.shape.__points = diff.next;
  36703. } // Stop previous animation.
  36704. polyline.stopAnimation();
  36705. updateProps(polyline, target, seriesModel);
  36706. if (polygon) {
  36707. polygon.setShape({
  36708. // Reuse the points with polyline.
  36709. points: current,
  36710. stackedOnPoints: stackedOnCurrent
  36711. });
  36712. polygon.stopAnimation();
  36713. updateProps(polygon, {
  36714. shape: {
  36715. stackedOnPoints: stackedOnNext
  36716. }
  36717. }, seriesModel); // If use attr directly in updateProps.
  36718. if (polyline.shape.points !== polygon.shape.points) {
  36719. polygon.shape.points = polyline.shape.points;
  36720. }
  36721. }
  36722. var updatedDataInfo = [];
  36723. var diffStatus = diff.status;
  36724. for (var i = 0; i < diffStatus.length; i++) {
  36725. var cmd = diffStatus[i].cmd;
  36726. if (cmd === '=') {
  36727. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  36728. if (el) {
  36729. updatedDataInfo.push({
  36730. el: el,
  36731. ptIdx: i // Index of points
  36732. });
  36733. }
  36734. }
  36735. }
  36736. if (polyline.animators && polyline.animators.length) {
  36737. polyline.animators[0].during(function () {
  36738. polygon && polygon.dirtyShape();
  36739. var points = polyline.shape.__points;
  36740. for (var i = 0; i < updatedDataInfo.length; i++) {
  36741. var el = updatedDataInfo[i].el;
  36742. var offset = updatedDataInfo[i].ptIdx * 2;
  36743. el.x = points[offset];
  36744. el.y = points[offset + 1];
  36745. el.markRedraw();
  36746. }
  36747. });
  36748. }
  36749. };
  36750. LineView.prototype.remove = function (ecModel) {
  36751. var group = this.group;
  36752. var oldData = this._data;
  36753. this._lineGroup.removeAll();
  36754. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  36755. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  36756. if (el.__temp) {
  36757. group.remove(el);
  36758. oldData.setItemGraphicEl(idx, null);
  36759. }
  36760. });
  36761. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._endLabel = this._data = null;
  36762. };
  36763. LineView.type = 'line';
  36764. return LineView;
  36765. }(ChartView);
  36766. function pointsLayout(seriesType, forceStoreInTypedArray) {
  36767. return {
  36768. seriesType: seriesType,
  36769. plan: createRenderPlanner(),
  36770. reset: function (seriesModel) {
  36771. var data = seriesModel.getData();
  36772. var coordSys = seriesModel.coordinateSystem;
  36773. var pipelineContext = seriesModel.pipelineContext;
  36774. var useTypedArray = forceStoreInTypedArray || pipelineContext.large;
  36775. if (!coordSys) {
  36776. return;
  36777. }
  36778. var dims = map(coordSys.dimensions, function (dim) {
  36779. return data.mapDimension(dim);
  36780. }).slice(0, 2);
  36781. var dimLen = dims.length;
  36782. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  36783. if (isDimensionStacked(data, dims[0]
  36784. /*, dims[1]*/
  36785. )) {
  36786. dims[0] = stackResultDim;
  36787. }
  36788. if (isDimensionStacked(data, dims[1]
  36789. /*, dims[0]*/
  36790. )) {
  36791. dims[1] = stackResultDim;
  36792. }
  36793. var dimInfo0 = data.getDimensionInfo(dims[0]);
  36794. var dimInfo1 = data.getDimensionInfo(dims[1]);
  36795. var dimIdx0 = dimInfo0 && dimInfo0.index;
  36796. var dimIdx1 = dimInfo1 && dimInfo1.index;
  36797. return dimLen && {
  36798. progress: function (params, data) {
  36799. var segCount = params.end - params.start;
  36800. var points = useTypedArray && createFloat32Array(segCount * dimLen);
  36801. var tmpIn = [];
  36802. var tmpOut = [];
  36803. for (var i = params.start, offset = 0; i < params.end; i++) {
  36804. var point = void 0;
  36805. if (dimLen === 1) {
  36806. var x = data.getByDimIdx(dimIdx0, i); // NOTE: Make sure the second parameter is null to use default strategy.
  36807. point = coordSys.dataToPoint(x, null, tmpOut);
  36808. } else {
  36809. tmpIn[0] = data.getByDimIdx(dimIdx0, i);
  36810. tmpIn[1] = data.getByDimIdx(dimIdx1, i); // Let coordinate system to handle the NaN data.
  36811. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  36812. }
  36813. if (useTypedArray) {
  36814. points[offset++] = point[0];
  36815. points[offset++] = point[1];
  36816. } else {
  36817. data.setItemLayout(i, point.slice());
  36818. }
  36819. }
  36820. useTypedArray && data.setLayout('points', points);
  36821. }
  36822. };
  36823. }
  36824. };
  36825. }
  36826. /*
  36827. * Licensed to the Apache Software Foundation (ASF) under one
  36828. * or more contributor license agreements. See the NOTICE file
  36829. * distributed with this work for additional information
  36830. * regarding copyright ownership. The ASF licenses this file
  36831. * to you under the Apache License, Version 2.0 (the
  36832. * "License"); you may not use this file except in compliance
  36833. * with the License. You may obtain a copy of the License at
  36834. *
  36835. * http://www.apache.org/licenses/LICENSE-2.0
  36836. *
  36837. * Unless required by applicable law or agreed to in writing,
  36838. * software distributed under the License is distributed on an
  36839. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36840. * KIND, either express or implied. See the License for the
  36841. * specific language governing permissions and limitations
  36842. * under the License.
  36843. */
  36844. /**
  36845. * AUTO-GENERATED FILE. DO NOT MODIFY.
  36846. */
  36847. /*
  36848. * Licensed to the Apache Software Foundation (ASF) under one
  36849. * or more contributor license agreements. See the NOTICE file
  36850. * distributed with this work for additional information
  36851. * regarding copyright ownership. The ASF licenses this file
  36852. * to you under the Apache License, Version 2.0 (the
  36853. * "License"); you may not use this file except in compliance
  36854. * with the License. You may obtain a copy of the License at
  36855. *
  36856. * http://www.apache.org/licenses/LICENSE-2.0
  36857. *
  36858. * Unless required by applicable law or agreed to in writing,
  36859. * software distributed under the License is distributed on an
  36860. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36861. * KIND, either express or implied. See the License for the
  36862. * specific language governing permissions and limitations
  36863. * under the License.
  36864. */
  36865. var samplers = {
  36866. average: function (frame) {
  36867. var sum = 0;
  36868. var count = 0;
  36869. for (var i = 0; i < frame.length; i++) {
  36870. if (!isNaN(frame[i])) {
  36871. sum += frame[i];
  36872. count++;
  36873. }
  36874. } // Return NaN if count is 0
  36875. return count === 0 ? NaN : sum / count;
  36876. },
  36877. sum: function (frame) {
  36878. var sum = 0;
  36879. for (var i = 0; i < frame.length; i++) {
  36880. // Ignore NaN
  36881. sum += frame[i] || 0;
  36882. }
  36883. return sum;
  36884. },
  36885. max: function (frame) {
  36886. var max = -Infinity;
  36887. for (var i = 0; i < frame.length; i++) {
  36888. frame[i] > max && (max = frame[i]);
  36889. } // NaN will cause illegal axis extent.
  36890. return isFinite(max) ? max : NaN;
  36891. },
  36892. min: function (frame) {
  36893. var min = Infinity;
  36894. for (var i = 0; i < frame.length; i++) {
  36895. frame[i] < min && (min = frame[i]);
  36896. } // NaN will cause illegal axis extent.
  36897. return isFinite(min) ? min : NaN;
  36898. },
  36899. // TODO
  36900. // Median
  36901. nearest: function (frame) {
  36902. return frame[0];
  36903. }
  36904. };
  36905. var indexSampler = function (frame) {
  36906. return Math.round(frame.length / 2);
  36907. };
  36908. function dataSample(seriesType) {
  36909. return {
  36910. seriesType: seriesType,
  36911. // FIXME:TS never used, so comment it
  36912. // modifyOutputEnd: true,
  36913. reset: function (seriesModel, ecModel, api) {
  36914. var data = seriesModel.getData();
  36915. var sampling = seriesModel.get('sampling');
  36916. var coordSys = seriesModel.coordinateSystem;
  36917. var count = data.count(); // Only cartesian2d support down sampling. Disable it when there is few data.
  36918. if (count > 10 && coordSys.type === 'cartesian2d' && sampling) {
  36919. var baseAxis = coordSys.getBaseAxis();
  36920. var valueAxis = coordSys.getOtherAxis(baseAxis);
  36921. var extent = baseAxis.getExtent();
  36922. var dpr = api.getDevicePixelRatio(); // Coordinste system has been resized
  36923. var size = Math.abs(extent[1] - extent[0]) * (dpr || 1);
  36924. var rate = Math.round(count / size);
  36925. if (rate > 1) {
  36926. if (sampling === 'lttb') {
  36927. seriesModel.setData(data.lttbDownSample(data.mapDimension(valueAxis.dim), 1 / rate));
  36928. }
  36929. var sampler = void 0;
  36930. if (typeof sampling === 'string') {
  36931. sampler = samplers[sampling];
  36932. } else if (typeof sampling === 'function') {
  36933. sampler = sampling;
  36934. }
  36935. if (sampler) {
  36936. // Only support sample the first dim mapped from value axis.
  36937. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  36938. }
  36939. }
  36940. }
  36941. }
  36942. };
  36943. }
  36944. function install$2(registers) {
  36945. registers.registerChartView(LineView);
  36946. registers.registerSeriesModel(LineSeriesModel);
  36947. registers.registerLayout(pointsLayout('line', true)); // Down sample after filter
  36948. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  36949. }
  36950. var BaseBarSeriesModel =
  36951. /** @class */
  36952. function (_super) {
  36953. __extends(BaseBarSeriesModel, _super);
  36954. function BaseBarSeriesModel() {
  36955. var _this = _super !== null && _super.apply(this, arguments) || this;
  36956. _this.type = BaseBarSeriesModel.type;
  36957. return _this;
  36958. }
  36959. BaseBarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  36960. return createListFromArray(this.getSource(), this, {
  36961. useEncodeDefaulter: true
  36962. });
  36963. };
  36964. BaseBarSeriesModel.prototype.getMarkerPosition = function (value) {
  36965. var coordSys = this.coordinateSystem;
  36966. if (coordSys) {
  36967. // PENDING if clamp ?
  36968. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  36969. var data = this.getData();
  36970. var offset = data.getLayout('offset');
  36971. var size = data.getLayout('size');
  36972. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  36973. pt[offsetIndex] += offset + size / 2;
  36974. return pt;
  36975. }
  36976. return [NaN, NaN];
  36977. };
  36978. BaseBarSeriesModel.type = 'series.__base_bar__';
  36979. BaseBarSeriesModel.defaultOption = {
  36980. zlevel: 0,
  36981. z: 2,
  36982. coordinateSystem: 'cartesian2d',
  36983. legendHoverLink: true,
  36984. // stack: null
  36985. // Cartesian coordinate system
  36986. // xAxisIndex: 0,
  36987. // yAxisIndex: 0,
  36988. barMinHeight: 0,
  36989. barMinAngle: 0,
  36990. // cursor: null,
  36991. large: false,
  36992. largeThreshold: 400,
  36993. progressive: 3e3,
  36994. progressiveChunkMode: 'mod'
  36995. };
  36996. return BaseBarSeriesModel;
  36997. }(SeriesModel);
  36998. SeriesModel.registerClass(BaseBarSeriesModel);
  36999. var BarSeriesModel =
  37000. /** @class */
  37001. function (_super) {
  37002. __extends(BarSeriesModel, _super);
  37003. function BarSeriesModel() {
  37004. var _this = _super !== null && _super.apply(this, arguments) || this;
  37005. _this.type = BarSeriesModel.type;
  37006. return _this;
  37007. }
  37008. BarSeriesModel.prototype.getInitialData = function () {
  37009. return createListFromArray(this.getSource(), this, {
  37010. useEncodeDefaulter: true,
  37011. createInvertedIndices: !!this.get('realtimeSort', true) || null
  37012. });
  37013. };
  37014. /**
  37015. * @override
  37016. */
  37017. BarSeriesModel.prototype.getProgressive = function () {
  37018. // Do not support progressive in normal mode.
  37019. return this.get('large') ? this.get('progressive') : false;
  37020. };
  37021. /**
  37022. * @override
  37023. */
  37024. BarSeriesModel.prototype.getProgressiveThreshold = function () {
  37025. // Do not support progressive in normal mode.
  37026. var progressiveThreshold = this.get('progressiveThreshold');
  37027. var largeThreshold = this.get('largeThreshold');
  37028. if (largeThreshold > progressiveThreshold) {
  37029. progressiveThreshold = largeThreshold;
  37030. }
  37031. return progressiveThreshold;
  37032. };
  37033. BarSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  37034. return selectors.rect(data.getItemLayout(dataIndex));
  37035. };
  37036. BarSeriesModel.type = 'series.bar';
  37037. BarSeriesModel.dependencies = ['grid', 'polar'];
  37038. BarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  37039. // If clipped
  37040. // Only available on cartesian2d
  37041. clip: true,
  37042. roundCap: false,
  37043. showBackground: false,
  37044. backgroundStyle: {
  37045. color: 'rgba(180, 180, 180, 0.2)',
  37046. borderColor: null,
  37047. borderWidth: 0,
  37048. borderType: 'solid',
  37049. borderRadius: 0,
  37050. shadowBlur: 0,
  37051. shadowColor: null,
  37052. shadowOffsetX: 0,
  37053. shadowOffsetY: 0,
  37054. opacity: 1
  37055. },
  37056. select: {
  37057. itemStyle: {
  37058. borderColor: '#212121'
  37059. }
  37060. },
  37061. realtimeSort: false
  37062. });
  37063. return BarSeriesModel;
  37064. }(BaseBarSeriesModel);
  37065. /**
  37066. * Sausage: similar to sector, but have half circle on both sides
  37067. */
  37068. var SausageShape =
  37069. /** @class */
  37070. function () {
  37071. function SausageShape() {
  37072. this.cx = 0;
  37073. this.cy = 0;
  37074. this.r0 = 0;
  37075. this.r = 0;
  37076. this.startAngle = 0;
  37077. this.endAngle = Math.PI * 2;
  37078. this.clockwise = true;
  37079. }
  37080. return SausageShape;
  37081. }();
  37082. var SausagePath =
  37083. /** @class */
  37084. function (_super) {
  37085. __extends(SausagePath, _super);
  37086. function SausagePath(opts) {
  37087. var _this = _super.call(this, opts) || this;
  37088. _this.type = 'sausage';
  37089. return _this;
  37090. }
  37091. SausagePath.prototype.getDefaultShape = function () {
  37092. return new SausageShape();
  37093. };
  37094. SausagePath.prototype.buildPath = function (ctx, shape) {
  37095. var x = shape.cx;
  37096. var y = shape.cy;
  37097. var r0 = Math.max(shape.r0 || 0, 0);
  37098. var r = Math.max(shape.r, 0);
  37099. var dr = (r - r0) * 0.5;
  37100. var rCenter = r0 + dr;
  37101. var startAngle = shape.startAngle;
  37102. var endAngle = shape.endAngle;
  37103. var clockwise = shape.clockwise;
  37104. var unitStartX = Math.cos(startAngle);
  37105. var unitStartY = Math.sin(startAngle);
  37106. var unitEndX = Math.cos(endAngle);
  37107. var unitEndY = Math.sin(endAngle);
  37108. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  37109. if (lessThanCircle) {
  37110. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  37111. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  37112. }
  37113. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  37114. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  37115. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  37116. if (r0 !== 0) {
  37117. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  37118. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  37119. }
  37120. ctx.closePath();
  37121. };
  37122. return SausagePath;
  37123. }(Path);
  37124. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'borderWidth'];
  37125. var BAR_BORDER_RADIUS_QUERY = ['itemStyle', 'borderRadius'];
  37126. var _eventPos = [0, 0];
  37127. var mathMax$6 = Math.max;
  37128. var mathMin$6 = Math.min;
  37129. function getClipArea(coord, data) {
  37130. var coordSysClipArea = coord.getArea && coord.getArea();
  37131. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  37132. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  37133. // We should not clip this part.
  37134. // See test/bar2.html
  37135. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  37136. var expandWidth = data.getLayout('bandWidth');
  37137. if (baseAxis.isHorizontal()) {
  37138. coordSysClipArea.x -= expandWidth;
  37139. coordSysClipArea.width += expandWidth * 2;
  37140. } else {
  37141. coordSysClipArea.y -= expandWidth;
  37142. coordSysClipArea.height += expandWidth * 2;
  37143. }
  37144. }
  37145. }
  37146. return coordSysClipArea;
  37147. }
  37148. var BarView =
  37149. /** @class */
  37150. function (_super) {
  37151. __extends(BarView, _super);
  37152. function BarView() {
  37153. var _this = _super.call(this) || this;
  37154. _this.type = BarView.type;
  37155. _this._isFirstFrame = true;
  37156. return _this;
  37157. }
  37158. BarView.prototype.render = function (seriesModel, ecModel, api, payload) {
  37159. this._model = seriesModel;
  37160. this._removeOnRenderedListener(api);
  37161. this._updateDrawMode(seriesModel);
  37162. var coordinateSystemType = seriesModel.get('coordinateSystem');
  37163. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  37164. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api, payload);
  37165. } else if ("development" !== 'production') {
  37166. warn('Only cartesian2d and polar supported for bar.');
  37167. }
  37168. };
  37169. BarView.prototype.incrementalPrepareRender = function (seriesModel) {
  37170. this._clear();
  37171. this._updateDrawMode(seriesModel); // incremental also need to clip, otherwise might be overlow.
  37172. // But must not set clip in each frame, otherwise all of the children will be marked redraw.
  37173. this._updateLargeClip(seriesModel);
  37174. };
  37175. BarView.prototype.incrementalRender = function (params, seriesModel) {
  37176. // Do not support progressive in normal mode.
  37177. this._incrementalRenderLarge(params, seriesModel);
  37178. };
  37179. BarView.prototype._updateDrawMode = function (seriesModel) {
  37180. var isLargeDraw = seriesModel.pipelineContext.large;
  37181. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  37182. this._isLargeDraw = isLargeDraw;
  37183. this._clear();
  37184. }
  37185. };
  37186. BarView.prototype._renderNormal = function (seriesModel, ecModel, api, payload) {
  37187. var group = this.group;
  37188. var data = seriesModel.getData();
  37189. var oldData = this._data;
  37190. var coord = seriesModel.coordinateSystem;
  37191. var baseAxis = coord.getBaseAxis();
  37192. var isHorizontalOrRadial;
  37193. if (coord.type === 'cartesian2d') {
  37194. isHorizontalOrRadial = baseAxis.isHorizontal();
  37195. } else if (coord.type === 'polar') {
  37196. isHorizontalOrRadial = baseAxis.dim === 'angle';
  37197. }
  37198. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  37199. var realtimeSortCfg = shouldRealtimeSort(seriesModel, coord);
  37200. if (realtimeSortCfg) {
  37201. this._enableRealtimeSort(realtimeSortCfg, data, api);
  37202. }
  37203. var needsClip = seriesModel.get('clip', true) || realtimeSortCfg;
  37204. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  37205. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  37206. // And don't want the label are clipped.
  37207. var roundCap = seriesModel.get('roundCap', true);
  37208. var drawBackground = seriesModel.get('showBackground', true);
  37209. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37210. var barBorderRadius = backgroundModel.get('borderRadius') || 0;
  37211. var bgEls = [];
  37212. var oldBgEls = this._backgroundEls;
  37213. var isInitSort = payload && payload.isInitSort;
  37214. var isChangeOrder = payload && payload.type === 'changeAxisOrder';
  37215. function createBackground(dataIndex) {
  37216. var bgLayout = getLayout[coord.type](data, dataIndex);
  37217. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  37218. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  37219. if (coord.type === 'cartesian2d') {
  37220. bgEl.setShape('r', barBorderRadius);
  37221. }
  37222. bgEls[dataIndex] = bgEl;
  37223. return bgEl;
  37224. }
  37225. data.diff(oldData).add(function (dataIndex) {
  37226. var itemModel = data.getItemModel(dataIndex);
  37227. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  37228. if (drawBackground) {
  37229. createBackground(dataIndex);
  37230. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  37231. if (!data.hasValue(dataIndex)) {
  37232. return;
  37233. }
  37234. var isClipped = false;
  37235. if (needsClip) {
  37236. // Clip will modify the layout params.
  37237. // And return a boolean to determine if the shape are fully clipped.
  37238. isClipped = clip[coord.type](coordSysClipArea, layout);
  37239. }
  37240. var el = elementCreator[coord.type](seriesModel, data, dataIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, false, roundCap);
  37241. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  37242. if (isInitSort) {
  37243. el.attr({
  37244. shape: layout
  37245. });
  37246. } else if (realtimeSortCfg) {
  37247. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, dataIndex, isHorizontalOrRadial, false, false);
  37248. } else {
  37249. initProps(el, {
  37250. shape: layout
  37251. }, seriesModel, dataIndex);
  37252. }
  37253. data.setItemGraphicEl(dataIndex, el);
  37254. group.add(el);
  37255. el.ignore = isClipped;
  37256. }).update(function (newIndex, oldIndex) {
  37257. var itemModel = data.getItemModel(newIndex);
  37258. var layout = getLayout[coord.type](data, newIndex, itemModel);
  37259. if (drawBackground) {
  37260. var bgEl = void 0;
  37261. if (oldBgEls.length === 0) {
  37262. bgEl = createBackground(oldIndex);
  37263. } else {
  37264. bgEl = oldBgEls[oldIndex];
  37265. bgEl.useStyle(backgroundModel.getItemStyle()); // Only cartesian2d support borderRadius.
  37266. if (coord.type === 'cartesian2d') {
  37267. bgEl.setShape('r', barBorderRadius);
  37268. }
  37269. bgEls[newIndex] = bgEl;
  37270. }
  37271. var bgLayout = getLayout[coord.type](data, newIndex);
  37272. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  37273. updateProps(bgEl, {
  37274. shape: shape
  37275. }, animationModel, newIndex);
  37276. }
  37277. var el = oldData.getItemGraphicEl(oldIndex);
  37278. if (!data.hasValue(newIndex)) {
  37279. group.remove(el);
  37280. el = null;
  37281. return;
  37282. }
  37283. var isClipped = false;
  37284. if (needsClip) {
  37285. isClipped = clip[coord.type](coordSysClipArea, layout);
  37286. if (isClipped) {
  37287. group.remove(el);
  37288. }
  37289. }
  37290. if (!el) {
  37291. el = elementCreator[coord.type](seriesModel, data, newIndex, layout, isHorizontalOrRadial, animationModel, baseAxis.model, !!el, roundCap);
  37292. } // Not change anything if only order changed.
  37293. // Especially not change label.
  37294. if (!isChangeOrder) {
  37295. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  37296. }
  37297. if (isInitSort) {
  37298. el.attr({
  37299. shape: layout
  37300. });
  37301. } else if (realtimeSortCfg) {
  37302. updateRealtimeAnimation(realtimeSortCfg, animationModel, el, layout, newIndex, isHorizontalOrRadial, true, isChangeOrder);
  37303. } else {
  37304. updateProps(el, {
  37305. shape: layout
  37306. }, seriesModel, newIndex, null);
  37307. }
  37308. data.setItemGraphicEl(newIndex, el);
  37309. el.ignore = isClipped;
  37310. group.add(el);
  37311. }).remove(function (dataIndex) {
  37312. var el = oldData.getItemGraphicEl(dataIndex);
  37313. el && removeElementWithFadeOut(el, seriesModel, dataIndex);
  37314. }).execute();
  37315. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  37316. bgGroup.removeAll();
  37317. for (var i = 0; i < bgEls.length; ++i) {
  37318. bgGroup.add(bgEls[i]);
  37319. }
  37320. group.add(bgGroup);
  37321. this._backgroundEls = bgEls;
  37322. this._data = data;
  37323. };
  37324. BarView.prototype._renderLarge = function (seriesModel, ecModel, api) {
  37325. this._clear();
  37326. createLarge(seriesModel, this.group);
  37327. this._updateLargeClip(seriesModel);
  37328. };
  37329. BarView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  37330. this._removeBackground();
  37331. createLarge(seriesModel, this.group, true);
  37332. };
  37333. BarView.prototype._updateLargeClip = function (seriesModel) {
  37334. // Use clipPath in large mode.
  37335. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  37336. if (clipPath) {
  37337. this.group.setClipPath(clipPath);
  37338. } else {
  37339. this.group.removeClipPath();
  37340. }
  37341. };
  37342. BarView.prototype._enableRealtimeSort = function (realtimeSortCfg, data, api) {
  37343. var _this = this; // If no data in the first frame, wait for data to initSort
  37344. if (!data.count()) {
  37345. return;
  37346. }
  37347. var baseAxis = realtimeSortCfg.baseAxis;
  37348. if (this._isFirstFrame) {
  37349. this._dispatchInitSort(data, realtimeSortCfg, api);
  37350. this._isFirstFrame = false;
  37351. } else {
  37352. var orderMapping_1 = function (idx) {
  37353. var el = data.getItemGraphicEl(idx);
  37354. if (el) {
  37355. var shape = el.shape; // If data is NaN, shape.xxx may be NaN, so use || 0 here in case
  37356. return (baseAxis.isHorizontal() // The result should be consistent with the initial sort by data value.
  37357. // Do not support the case that both positive and negative exist.
  37358. ? Math.abs(shape.height) : Math.abs(shape.width)) || 0;
  37359. } else {
  37360. return 0;
  37361. }
  37362. };
  37363. this._onRendered = function () {
  37364. _this._updateSortWithinSameData(data, orderMapping_1, baseAxis, api);
  37365. };
  37366. api.getZr().on('rendered', this._onRendered);
  37367. }
  37368. };
  37369. BarView.prototype._dataSort = function (data, baseAxis, orderMapping) {
  37370. var info = [];
  37371. data.each(data.mapDimension(baseAxis.dim), function (ordinalNumber, dataIdx) {
  37372. var mappedValue = orderMapping(dataIdx);
  37373. mappedValue = mappedValue == null ? NaN : mappedValue;
  37374. info.push({
  37375. dataIndex: dataIdx,
  37376. mappedValue: mappedValue,
  37377. ordinalNumber: ordinalNumber
  37378. });
  37379. });
  37380. info.sort(function (a, b) {
  37381. // If NaN, it will be treated as min val.
  37382. return b.mappedValue - a.mappedValue;
  37383. });
  37384. return {
  37385. ordinalNumbers: map(info, function (item) {
  37386. return item.ordinalNumber;
  37387. })
  37388. };
  37389. };
  37390. BarView.prototype._isOrderChangedWithinSameData = function (data, orderMapping, baseAxis) {
  37391. var scale = baseAxis.scale;
  37392. var ordinalDataDim = data.mapDimension(baseAxis.dim);
  37393. var lastValue = Number.MAX_VALUE;
  37394. for (var tickNum = 0, len = scale.getOrdinalMeta().categories.length; tickNum < len; ++tickNum) {
  37395. var rawIdx = data.rawIndexOf(ordinalDataDim, scale.getRawOrdinalNumber(tickNum));
  37396. var value = rawIdx < 0 // If some tick have no bar, the tick will be treated as min.
  37397. ? Number.MIN_VALUE // PENDING: if dataZoom on baseAxis exits, is it a performance issue?
  37398. : orderMapping(data.indexOfRawIndex(rawIdx));
  37399. if (value > lastValue) {
  37400. return true;
  37401. }
  37402. lastValue = value;
  37403. }
  37404. return false;
  37405. };
  37406. /*
  37407. * Consider the case when A and B changed order, whose representing
  37408. * bars are both out of sight, we don't wish to trigger reorder action
  37409. * as long as the order in the view doesn't change.
  37410. */
  37411. BarView.prototype._isOrderDifferentInView = function (orderInfo, baseAxis) {
  37412. var scale = baseAxis.scale;
  37413. var extent = scale.getExtent();
  37414. var tickNum = Math.max(0, extent[0]);
  37415. var tickMax = Math.min(extent[1], scale.getOrdinalMeta().categories.length - 1);
  37416. for (; tickNum <= tickMax; ++tickNum) {
  37417. if (orderInfo.ordinalNumbers[tickNum] !== scale.getRawOrdinalNumber(tickNum)) {
  37418. return true;
  37419. }
  37420. }
  37421. };
  37422. BarView.prototype._updateSortWithinSameData = function (data, orderMapping, baseAxis, api) {
  37423. if (!this._isOrderChangedWithinSameData(data, orderMapping, baseAxis)) {
  37424. return;
  37425. }
  37426. var sortInfo = this._dataSort(data, baseAxis, orderMapping);
  37427. if (this._isOrderDifferentInView(sortInfo, baseAxis)) {
  37428. this._removeOnRenderedListener(api);
  37429. api.dispatchAction({
  37430. type: 'changeAxisOrder',
  37431. componentType: baseAxis.dim + 'Axis',
  37432. axisId: baseAxis.index,
  37433. sortInfo: sortInfo
  37434. });
  37435. }
  37436. };
  37437. BarView.prototype._dispatchInitSort = function (data, realtimeSortCfg, api) {
  37438. var baseAxis = realtimeSortCfg.baseAxis;
  37439. var sortResult = this._dataSort(data, baseAxis, function (dataIdx) {
  37440. return data.get(data.mapDimension(realtimeSortCfg.otherAxis.dim), dataIdx);
  37441. });
  37442. api.dispatchAction({
  37443. type: 'changeAxisOrder',
  37444. componentType: baseAxis.dim + 'Axis',
  37445. isInitSort: true,
  37446. axisId: baseAxis.index,
  37447. sortInfo: sortResult,
  37448. animation: {
  37449. // Update the axis label from the natural initial layout to
  37450. // sorted layout should has no animation.
  37451. duration: 0
  37452. }
  37453. });
  37454. };
  37455. BarView.prototype.remove = function (ecModel, api) {
  37456. this._clear(this._model);
  37457. this._removeOnRenderedListener(api);
  37458. };
  37459. BarView.prototype.dispose = function (ecModel, api) {
  37460. this._removeOnRenderedListener(api);
  37461. };
  37462. BarView.prototype._removeOnRenderedListener = function (api) {
  37463. if (this._onRendered) {
  37464. api.getZr().off('rendered', this._onRendered);
  37465. this._onRendered = null;
  37466. }
  37467. };
  37468. BarView.prototype._clear = function (model) {
  37469. var group = this.group;
  37470. var data = this._data;
  37471. if (model && model.isAnimationEnabled() && data && !this._isLargeDraw) {
  37472. this._removeBackground();
  37473. this._backgroundEls = [];
  37474. data.eachItemGraphicEl(function (el) {
  37475. removeElementWithFadeOut(el, model, getECData(el).dataIndex);
  37476. });
  37477. } else {
  37478. group.removeAll();
  37479. }
  37480. this._data = null;
  37481. this._isFirstFrame = true;
  37482. };
  37483. BarView.prototype._removeBackground = function () {
  37484. this.group.remove(this._backgroundGroup);
  37485. this._backgroundGroup = null;
  37486. };
  37487. BarView.type = 'bar';
  37488. return BarView;
  37489. }(ChartView);
  37490. var clip = {
  37491. cartesian2d: function (coordSysBoundingRect, layout) {
  37492. var signWidth = layout.width < 0 ? -1 : 1;
  37493. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  37494. if (signWidth < 0) {
  37495. layout.x += layout.width;
  37496. layout.width = -layout.width;
  37497. }
  37498. if (signHeight < 0) {
  37499. layout.y += layout.height;
  37500. layout.height = -layout.height;
  37501. }
  37502. var coordSysX2 = coordSysBoundingRect.x + coordSysBoundingRect.width;
  37503. var coordSysY2 = coordSysBoundingRect.y + coordSysBoundingRect.height;
  37504. var x = mathMax$6(layout.x, coordSysBoundingRect.x);
  37505. var x2 = mathMin$6(layout.x + layout.width, coordSysX2);
  37506. var y = mathMax$6(layout.y, coordSysBoundingRect.y);
  37507. var y2 = mathMin$6(layout.y + layout.height, coordSysY2);
  37508. var xClipped = x2 < x;
  37509. var yClipped = y2 < y; // When xClipped or yClipped, the element will be marked as `ignore`.
  37510. // But we should also place the element at the edge of the coord sys bounding rect.
  37511. // Beause if data changed and the bar show again, its transition animaiton
  37512. // will begin at this place.
  37513. layout.x = xClipped && x > coordSysX2 ? x2 : x;
  37514. layout.y = yClipped && y > coordSysY2 ? y2 : y;
  37515. layout.width = xClipped ? 0 : x2 - x;
  37516. layout.height = yClipped ? 0 : y2 - y; // Reverse back
  37517. if (signWidth < 0) {
  37518. layout.x += layout.width;
  37519. layout.width = -layout.width;
  37520. }
  37521. if (signHeight < 0) {
  37522. layout.y += layout.height;
  37523. layout.height = -layout.height;
  37524. }
  37525. return xClipped || yClipped;
  37526. },
  37527. polar: function (coordSysClipArea, layout) {
  37528. var signR = layout.r0 <= layout.r ? 1 : -1; // Make sure r is larger than r0
  37529. if (signR < 0) {
  37530. var tmp = layout.r;
  37531. layout.r = layout.r0;
  37532. layout.r0 = tmp;
  37533. }
  37534. var r = mathMin$6(layout.r, coordSysClipArea.r);
  37535. var r0 = mathMax$6(layout.r0, coordSysClipArea.r0);
  37536. layout.r = r;
  37537. layout.r0 = r0;
  37538. var clipped = r - r0 < 0; // Reverse back
  37539. if (signR < 0) {
  37540. var tmp = layout.r;
  37541. layout.r = layout.r0;
  37542. layout.r0 = tmp;
  37543. }
  37544. return clipped;
  37545. }
  37546. };
  37547. var elementCreator = {
  37548. cartesian2d: function (seriesModel, data, newIndex, layout, isHorizontal, animationModel, axisModel, isUpdate, roundCap) {
  37549. var rect = new Rect({
  37550. shape: extend({}, layout),
  37551. z2: 1
  37552. });
  37553. rect.__dataIndex = newIndex;
  37554. rect.name = 'item';
  37555. if (animationModel) {
  37556. var rectShape = rect.shape;
  37557. var animateProperty = isHorizontal ? 'height' : 'width';
  37558. rectShape[animateProperty] = 0;
  37559. }
  37560. return rect;
  37561. },
  37562. polar: function (seriesModel, data, newIndex, layout, isRadial, animationModel, axisModel, isUpdate, roundCap) {
  37563. // Keep the same logic with bar in catesion: use end value to control
  37564. // direction. Notice that if clockwise is true (by default), the sector
  37565. // will always draw clockwisely, no matter whether endAngle is greater
  37566. // or less than startAngle.
  37567. var clockwise = layout.startAngle < layout.endAngle;
  37568. var ShapeClass = !isRadial && roundCap ? SausagePath : Sector;
  37569. var sector = new ShapeClass({
  37570. shape: defaults({
  37571. clockwise: clockwise
  37572. }, layout),
  37573. z2: 1
  37574. });
  37575. sector.name = 'item'; // Animation
  37576. if (animationModel) {
  37577. var sectorShape = sector.shape;
  37578. var animateProperty = isRadial ? 'r' : 'endAngle';
  37579. var animateTarget = {};
  37580. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  37581. animateTarget[animateProperty] = layout[animateProperty];
  37582. (isUpdate ? updateProps : initProps)(sector, {
  37583. shape: animateTarget // __value: typeof dataValue === 'string' ? parseInt(dataValue, 10) : dataValue
  37584. }, animationModel);
  37585. }
  37586. return sector;
  37587. }
  37588. };
  37589. function shouldRealtimeSort(seriesModel, coordSys) {
  37590. var realtimeSortOption = seriesModel.get('realtimeSort', true);
  37591. var baseAxis = coordSys.getBaseAxis();
  37592. if ("development" !== 'production') {
  37593. if (realtimeSortOption) {
  37594. if (baseAxis.type !== 'category') {
  37595. warn('`realtimeSort` will not work because this bar series is not based on a category axis.');
  37596. }
  37597. if (coordSys.type !== 'cartesian2d') {
  37598. warn('`realtimeSort` will not work because this bar series is not on cartesian2d.');
  37599. }
  37600. }
  37601. }
  37602. if (realtimeSortOption && baseAxis.type === 'category' && coordSys.type === 'cartesian2d') {
  37603. return {
  37604. baseAxis: baseAxis,
  37605. otherAxis: coordSys.getOtherAxis(baseAxis)
  37606. };
  37607. }
  37608. }
  37609. function updateRealtimeAnimation(realtimeSortCfg, seriesAnimationModel, el, layout, newIndex, isHorizontal, isUpdate, isChangeOrder) {
  37610. var seriesTarget;
  37611. var axisTarget;
  37612. if (isHorizontal) {
  37613. axisTarget = {
  37614. x: layout.x,
  37615. width: layout.width
  37616. };
  37617. seriesTarget = {
  37618. y: layout.y,
  37619. height: layout.height
  37620. };
  37621. } else {
  37622. axisTarget = {
  37623. y: layout.y,
  37624. height: layout.height
  37625. };
  37626. seriesTarget = {
  37627. x: layout.x,
  37628. width: layout.width
  37629. };
  37630. }
  37631. if (!isChangeOrder) {
  37632. // Keep the original growth animation if only axis order changed.
  37633. // Not start a new animation.
  37634. (isUpdate ? updateProps : initProps)(el, {
  37635. shape: seriesTarget
  37636. }, seriesAnimationModel, newIndex, null);
  37637. }
  37638. var axisAnimationModel = seriesAnimationModel ? realtimeSortCfg.baseAxis.model : null;
  37639. (isUpdate ? updateProps : initProps)(el, {
  37640. shape: axisTarget
  37641. }, axisAnimationModel, newIndex);
  37642. }
  37643. var getLayout = {
  37644. // itemModel is only used to get borderWidth, which is not needed
  37645. // when calculating bar background layout.
  37646. cartesian2d: function (data, dataIndex, itemModel) {
  37647. var layout = data.getItemLayout(dataIndex);
  37648. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  37649. var signX = layout.width > 0 ? 1 : -1;
  37650. var signY = layout.height > 0 ? 1 : -1;
  37651. return {
  37652. x: layout.x + signX * fixedLineWidth / 2,
  37653. y: layout.y + signY * fixedLineWidth / 2,
  37654. width: layout.width - signX * fixedLineWidth,
  37655. height: layout.height - signY * fixedLineWidth
  37656. };
  37657. },
  37658. polar: function (data, dataIndex, itemModel) {
  37659. var layout = data.getItemLayout(dataIndex);
  37660. return {
  37661. cx: layout.cx,
  37662. cy: layout.cy,
  37663. r0: layout.r0,
  37664. r: layout.r,
  37665. startAngle: layout.startAngle,
  37666. endAngle: layout.endAngle
  37667. };
  37668. }
  37669. };
  37670. function isZeroOnPolar(layout) {
  37671. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  37672. }
  37673. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) {
  37674. var style = data.getItemVisual(dataIndex, 'style');
  37675. if (!isPolar) {
  37676. el.setShape('r', itemModel.get(BAR_BORDER_RADIUS_QUERY) || 0);
  37677. }
  37678. el.useStyle(style);
  37679. var cursorStyle = itemModel.getShallow('cursor');
  37680. cursorStyle && el.attr('cursor', cursorStyle);
  37681. if (!isPolar) {
  37682. var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right';
  37683. var labelStatesModels = getLabelStatesModels(itemModel);
  37684. setLabelStyle(el, labelStatesModels, {
  37685. labelFetcher: seriesModel,
  37686. labelDataIndex: dataIndex,
  37687. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  37688. inheritColor: style.fill,
  37689. defaultOpacity: style.opacity,
  37690. defaultOutsidePosition: labelPositionOutside
  37691. });
  37692. var label = el.getTextContent();
  37693. setLabelValueAnimation(label, labelStatesModels, seriesModel.getRawValue(dataIndex), function (value) {
  37694. return getDefaultInterpolatedLabel(data, value);
  37695. });
  37696. }
  37697. var emphasisModel = itemModel.getModel(['emphasis']);
  37698. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  37699. setStatesStylesFromModel(el, itemModel);
  37700. if (isZeroOnPolar(layout)) {
  37701. el.style.fill = 'none';
  37702. el.style.stroke = 'none';
  37703. each(el.states, function (state) {
  37704. if (state.style) {
  37705. state.style.fill = state.style.stroke = 'none';
  37706. }
  37707. });
  37708. }
  37709. } // In case width or height are too small.
  37710. function getLineWidth(itemModel, rawLayout) {
  37711. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; // width or height may be NaN for empty data
  37712. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  37713. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  37714. return Math.min(lineWidth, width, height);
  37715. }
  37716. var LagePathShape =
  37717. /** @class */
  37718. function () {
  37719. function LagePathShape() {}
  37720. return LagePathShape;
  37721. }();
  37722. var LargePath =
  37723. /** @class */
  37724. function (_super) {
  37725. __extends(LargePath, _super);
  37726. function LargePath(opts) {
  37727. var _this = _super.call(this, opts) || this;
  37728. _this.type = 'largeBar';
  37729. return _this;
  37730. }
  37731. LargePath.prototype.getDefaultShape = function () {
  37732. return new LagePathShape();
  37733. };
  37734. LargePath.prototype.buildPath = function (ctx, shape) {
  37735. // Drawing lines is more efficient than drawing
  37736. // a whole line or drawing rects.
  37737. var points = shape.points;
  37738. var startPoint = this.__startPoint;
  37739. var baseDimIdx = this.__baseDimIdx;
  37740. for (var i = 0; i < points.length; i += 2) {
  37741. startPoint[baseDimIdx] = points[i + baseDimIdx];
  37742. ctx.moveTo(startPoint[0], startPoint[1]);
  37743. ctx.lineTo(points[i], points[i + 1]);
  37744. }
  37745. };
  37746. return LargePath;
  37747. }(Path);
  37748. function createLarge(seriesModel, group, incremental) {
  37749. // TODO support polar
  37750. var data = seriesModel.getData();
  37751. var startPoint = [];
  37752. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  37753. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  37754. var largeDataIndices = data.getLayout('largeDataIndices');
  37755. var barWidth = data.getLayout('barWidth');
  37756. var backgroundModel = seriesModel.getModel('backgroundStyle');
  37757. var drawBackground = seriesModel.get('showBackground', true);
  37758. if (drawBackground) {
  37759. var points = data.getLayout('largeBackgroundPoints');
  37760. var backgroundStartPoint = [];
  37761. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  37762. var bgEl = new LargePath({
  37763. shape: {
  37764. points: points
  37765. },
  37766. incremental: !!incremental,
  37767. silent: true,
  37768. z2: 0
  37769. });
  37770. bgEl.__startPoint = backgroundStartPoint;
  37771. bgEl.__baseDimIdx = baseDimIdx;
  37772. bgEl.__largeDataIndices = largeDataIndices;
  37773. bgEl.__barWidth = barWidth;
  37774. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  37775. group.add(bgEl);
  37776. }
  37777. var el = new LargePath({
  37778. shape: {
  37779. points: data.getLayout('largePoints')
  37780. },
  37781. incremental: !!incremental
  37782. });
  37783. el.__startPoint = startPoint;
  37784. el.__baseDimIdx = baseDimIdx;
  37785. el.__largeDataIndices = largeDataIndices;
  37786. el.__barWidth = barWidth;
  37787. group.add(el);
  37788. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  37789. getECData(el).seriesIndex = seriesModel.seriesIndex;
  37790. if (!seriesModel.get('silent')) {
  37791. el.on('mousedown', largePathUpdateDataIndex);
  37792. el.on('mousemove', largePathUpdateDataIndex);
  37793. }
  37794. } // Use throttle to avoid frequently traverse to find dataIndex.
  37795. var largePathUpdateDataIndex = throttle(function (event) {
  37796. var largePath = this;
  37797. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  37798. getECData(largePath).dataIndex = dataIndex >= 0 ? dataIndex : null;
  37799. }, 30, false);
  37800. function largePathFindDataIndex(largePath, x, y) {
  37801. var baseDimIdx = largePath.__baseDimIdx;
  37802. var valueDimIdx = 1 - baseDimIdx;
  37803. var points = largePath.shape.points;
  37804. var largeDataIndices = largePath.__largeDataIndices;
  37805. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  37806. var startValueVal = largePath.__startPoint[valueDimIdx];
  37807. _eventPos[0] = x;
  37808. _eventPos[1] = y;
  37809. var pointerBaseVal = _eventPos[baseDimIdx];
  37810. var pointerValueVal = _eventPos[1 - baseDimIdx];
  37811. var baseLowerBound = pointerBaseVal - barWidthHalf;
  37812. var baseUpperBound = pointerBaseVal + barWidthHalf;
  37813. for (var i = 0, len = points.length / 2; i < len; i++) {
  37814. var ii = i * 2;
  37815. var barBaseVal = points[ii + baseDimIdx];
  37816. var barValueVal = points[ii + valueDimIdx];
  37817. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  37818. return largeDataIndices[i];
  37819. }
  37820. }
  37821. return -1;
  37822. }
  37823. function setLargeStyle(el, seriesModel, data) {
  37824. var globalStyle = data.getVisual('style');
  37825. el.useStyle(extend({}, globalStyle)); // Use stroke instead of fill.
  37826. el.style.fill = null;
  37827. el.style.stroke = globalStyle.fill;
  37828. el.style.lineWidth = data.getLayout('barWidth');
  37829. }
  37830. function setLargeBackgroundStyle(el, backgroundModel, data) {
  37831. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  37832. var itemStyle = backgroundModel.getItemStyle();
  37833. el.useStyle(itemStyle);
  37834. el.style.fill = null;
  37835. el.style.stroke = borderColor;
  37836. el.style.lineWidth = data.getLayout('barWidth');
  37837. }
  37838. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  37839. if (isCoordinateSystemType(coord, 'cartesian2d')) {
  37840. var rectShape = layout;
  37841. var coordLayout = coord.getArea();
  37842. return {
  37843. x: isHorizontalOrRadial ? rectShape.x : coordLayout.x,
  37844. y: isHorizontalOrRadial ? coordLayout.y : rectShape.y,
  37845. width: isHorizontalOrRadial ? rectShape.width : coordLayout.width,
  37846. height: isHorizontalOrRadial ? coordLayout.height : rectShape.height
  37847. };
  37848. } else {
  37849. var coordLayout = coord.getArea();
  37850. var sectorShape = layout;
  37851. return {
  37852. cx: coordLayout.cx,
  37853. cy: coordLayout.cy,
  37854. r0: isHorizontalOrRadial ? coordLayout.r0 : sectorShape.r0,
  37855. r: isHorizontalOrRadial ? coordLayout.r : sectorShape.r,
  37856. startAngle: isHorizontalOrRadial ? sectorShape.startAngle : 0,
  37857. endAngle: isHorizontalOrRadial ? sectorShape.endAngle : Math.PI * 2
  37858. };
  37859. }
  37860. }
  37861. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  37862. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  37863. return new ElementClz({
  37864. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  37865. silent: true,
  37866. z2: 0
  37867. });
  37868. }
  37869. function install$3(registers) {
  37870. registers.registerChartView(BarView);
  37871. registers.registerSeriesModel(BarSeriesModel);
  37872. registers.registerLayout(registers.PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  37873. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  37874. registers.registerLayout(registers.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  37875. registers.registerVisual({
  37876. seriesType: 'bar',
  37877. reset: function (seriesModel) {
  37878. // Visual coding for legend
  37879. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  37880. }
  37881. }); // Down sample after filter
  37882. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, dataSample('bar'));
  37883. /**
  37884. * @payload
  37885. * @property {string} [componentType=series]
  37886. * @property {number} [dx]
  37887. * @property {number} [dy]
  37888. * @property {number} [zoom]
  37889. * @property {number} [originX]
  37890. * @property {number} [originY]
  37891. */
  37892. registers.registerAction({
  37893. type: 'changeAxisOrder',
  37894. event: 'changeAxisOrder',
  37895. update: 'update'
  37896. }, function (payload, ecModel) {
  37897. var componentType = payload.componentType || 'series';
  37898. ecModel.eachComponent({
  37899. mainType: componentType,
  37900. query: payload
  37901. }, function (componentModel) {
  37902. if (payload.sortInfo) {
  37903. componentModel.axis.setCategorySortInfo(payload.sortInfo);
  37904. }
  37905. });
  37906. });
  37907. }
  37908. var PI2$8 = Math.PI * 2;
  37909. var RADIAN = Math.PI / 180;
  37910. function getViewRect(seriesModel, api) {
  37911. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  37912. width: api.getWidth(),
  37913. height: api.getHeight()
  37914. });
  37915. }
  37916. function pieLayout(seriesType, ecModel, api) {
  37917. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  37918. var data = seriesModel.getData();
  37919. var valueDim = data.mapDimension('value');
  37920. var viewRect = getViewRect(seriesModel, api);
  37921. var center = seriesModel.get('center');
  37922. var radius = seriesModel.get('radius');
  37923. if (!isArray(radius)) {
  37924. radius = [0, radius];
  37925. }
  37926. if (!isArray(center)) {
  37927. center = [center, center];
  37928. }
  37929. var width = parsePercent$1(viewRect.width, api.getWidth());
  37930. var height = parsePercent$1(viewRect.height, api.getHeight());
  37931. var size = Math.min(width, height);
  37932. var cx = parsePercent$1(center[0], width) + viewRect.x;
  37933. var cy = parsePercent$1(center[1], height) + viewRect.y;
  37934. var r0 = parsePercent$1(radius[0], size / 2);
  37935. var r = parsePercent$1(radius[1], size / 2);
  37936. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  37937. var minAngle = seriesModel.get('minAngle') * RADIAN;
  37938. var validDataCount = 0;
  37939. data.each(valueDim, function (value) {
  37940. !isNaN(value) && validDataCount++;
  37941. });
  37942. var sum = data.getSum(valueDim); // Sum may be 0
  37943. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  37944. var clockwise = seriesModel.get('clockwise');
  37945. var roseType = seriesModel.get('roseType');
  37946. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  37947. var extent = data.getDataExtent(valueDim);
  37948. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  37949. var restAngle = PI2$8;
  37950. var valueSumLargerThanMinAngle = 0;
  37951. var currentAngle = startAngle;
  37952. var dir = clockwise ? 1 : -1;
  37953. data.setLayout({
  37954. viewRect: viewRect,
  37955. r: r
  37956. });
  37957. data.each(valueDim, function (value, idx) {
  37958. var angle;
  37959. if (isNaN(value)) {
  37960. data.setItemLayout(idx, {
  37961. angle: NaN,
  37962. startAngle: NaN,
  37963. endAngle: NaN,
  37964. clockwise: clockwise,
  37965. cx: cx,
  37966. cy: cy,
  37967. r0: r0,
  37968. r: roseType ? NaN : r
  37969. });
  37970. return;
  37971. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  37972. if (roseType !== 'area') {
  37973. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  37974. } else {
  37975. angle = PI2$8 / validDataCount;
  37976. }
  37977. if (angle < minAngle) {
  37978. angle = minAngle;
  37979. restAngle -= minAngle;
  37980. } else {
  37981. valueSumLargerThanMinAngle += value;
  37982. }
  37983. var endAngle = currentAngle + dir * angle;
  37984. data.setItemLayout(idx, {
  37985. angle: angle,
  37986. startAngle: currentAngle,
  37987. endAngle: endAngle,
  37988. clockwise: clockwise,
  37989. cx: cx,
  37990. cy: cy,
  37991. r0: r0,
  37992. r: roseType ? linearMap(value, extent, [r0, r]) : r
  37993. });
  37994. currentAngle = endAngle;
  37995. }); // Some sector is constrained by minAngle
  37996. // Rest sectors needs recalculate angle
  37997. if (restAngle < PI2$8 && validDataCount) {
  37998. // Average the angle if rest angle is not enough after all angles is
  37999. // Constrained by minAngle
  38000. if (restAngle <= 1e-3) {
  38001. var angle_1 = PI2$8 / validDataCount;
  38002. data.each(valueDim, function (value, idx) {
  38003. if (!isNaN(value)) {
  38004. var layout_1 = data.getItemLayout(idx);
  38005. layout_1.angle = angle_1;
  38006. layout_1.startAngle = startAngle + dir * idx * angle_1;
  38007. layout_1.endAngle = startAngle + dir * (idx + 1) * angle_1;
  38008. }
  38009. });
  38010. } else {
  38011. unitRadian = restAngle / valueSumLargerThanMinAngle;
  38012. currentAngle = startAngle;
  38013. data.each(valueDim, function (value, idx) {
  38014. if (!isNaN(value)) {
  38015. var layout_2 = data.getItemLayout(idx);
  38016. var angle = layout_2.angle === minAngle ? minAngle : value * unitRadian;
  38017. layout_2.startAngle = currentAngle;
  38018. layout_2.endAngle = currentAngle + dir * angle;
  38019. currentAngle += dir * angle;
  38020. }
  38021. });
  38022. }
  38023. }
  38024. });
  38025. }
  38026. /*
  38027. * Licensed to the Apache Software Foundation (ASF) under one
  38028. * or more contributor license agreements. See the NOTICE file
  38029. * distributed with this work for additional information
  38030. * regarding copyright ownership. The ASF licenses this file
  38031. * to you under the Apache License, Version 2.0 (the
  38032. * "License"); you may not use this file except in compliance
  38033. * with the License. You may obtain a copy of the License at
  38034. *
  38035. * http://www.apache.org/licenses/LICENSE-2.0
  38036. *
  38037. * Unless required by applicable law or agreed to in writing,
  38038. * software distributed under the License is distributed on an
  38039. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38040. * KIND, either express or implied. See the License for the
  38041. * specific language governing permissions and limitations
  38042. * under the License.
  38043. */
  38044. /**
  38045. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38046. */
  38047. /*
  38048. * Licensed to the Apache Software Foundation (ASF) under one
  38049. * or more contributor license agreements. See the NOTICE file
  38050. * distributed with this work for additional information
  38051. * regarding copyright ownership. The ASF licenses this file
  38052. * to you under the Apache License, Version 2.0 (the
  38053. * "License"); you may not use this file except in compliance
  38054. * with the License. You may obtain a copy of the License at
  38055. *
  38056. * http://www.apache.org/licenses/LICENSE-2.0
  38057. *
  38058. * Unless required by applicable law or agreed to in writing,
  38059. * software distributed under the License is distributed on an
  38060. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38061. * KIND, either express or implied. See the License for the
  38062. * specific language governing permissions and limitations
  38063. * under the License.
  38064. */
  38065. function dataFilter(seriesType) {
  38066. return {
  38067. seriesType: seriesType,
  38068. reset: function (seriesModel, ecModel) {
  38069. var legendModels = ecModel.findComponents({
  38070. mainType: 'legend'
  38071. });
  38072. if (!legendModels || !legendModels.length) {
  38073. return;
  38074. }
  38075. var data = seriesModel.getData();
  38076. data.filterSelf(function (idx) {
  38077. var name = data.getName(idx); // If in any legend component the status is not selected.
  38078. for (var i = 0; i < legendModels.length; i++) {
  38079. // @ts-ignore FIXME: LegendModel
  38080. if (!legendModels[i].isSelected(name)) {
  38081. return false;
  38082. }
  38083. }
  38084. return true;
  38085. });
  38086. }
  38087. };
  38088. }
  38089. var RADIAN$1 = Math.PI / 180;
  38090. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  38091. if (list.length < 2) {
  38092. return;
  38093. }
  38094. function recalculateXOnSemiToAlignOnEllipseCurve(semi) {
  38095. var rB = semi.rB;
  38096. var rB2 = rB * rB;
  38097. for (var i = 0; i < semi.list.length; i++) {
  38098. var item = semi.list[i];
  38099. var dy = Math.abs(item.label.y - cy); // horizontal r is always same with original r because x is not changed.
  38100. var rA = r + item.len;
  38101. var rA2 = rA * rA; // Use ellipse implicit function to calculate x
  38102. var dx = Math.sqrt((1 - Math.abs(dy * dy / rB2)) * rA2);
  38103. item.label.x = cx + (dx + item.len2) * dir;
  38104. }
  38105. } // Adjust X based on the shifted y. Make tight labels aligned on an ellipse curve.
  38106. function recalculateX(items) {
  38107. // Extremes of
  38108. var topSemi = {
  38109. list: [],
  38110. maxY: 0
  38111. };
  38112. var bottomSemi = {
  38113. list: [],
  38114. maxY: 0
  38115. };
  38116. for (var i = 0; i < items.length; i++) {
  38117. if (items[i].labelAlignTo !== 'none') {
  38118. continue;
  38119. }
  38120. var item = items[i];
  38121. var semi = item.label.y > cy ? bottomSemi : topSemi;
  38122. var dy = Math.abs(item.label.y - cy);
  38123. if (dy > semi.maxY) {
  38124. var dx = item.label.x - cx - item.len2 * dir; // horizontal r is always same with original r because x is not changed.
  38125. var rA = r + item.len; // Canculate rB based on the topest / bottemest label.
  38126. var rB = Math.abs(dx) < rA ? Math.sqrt(dy * dy / (1 - dx * dx / rA / rA)) : rA;
  38127. semi.rB = rB;
  38128. semi.maxY = dy;
  38129. }
  38130. semi.list.push(item);
  38131. }
  38132. recalculateXOnSemiToAlignOnEllipseCurve(topSemi);
  38133. recalculateXOnSemiToAlignOnEllipseCurve(bottomSemi);
  38134. }
  38135. var len = list.length;
  38136. for (var i = 0; i < len; i++) {
  38137. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  38138. var dx = list[i].label.x - farthestX;
  38139. list[i].linePoints[1][0] += dx;
  38140. list[i].label.x = farthestX;
  38141. }
  38142. }
  38143. if (shiftLayoutOnY(list, viewTop, viewTop + viewHeight)) {
  38144. recalculateX(list);
  38145. }
  38146. }
  38147. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  38148. var leftList = [];
  38149. var rightList = [];
  38150. var leftmostX = Number.MAX_VALUE;
  38151. var rightmostX = -Number.MAX_VALUE;
  38152. for (var i = 0; i < labelLayoutList.length; i++) {
  38153. var label = labelLayoutList[i].label;
  38154. if (isPositionCenter(labelLayoutList[i])) {
  38155. continue;
  38156. }
  38157. if (label.x < cx) {
  38158. leftmostX = Math.min(leftmostX, label.x);
  38159. leftList.push(labelLayoutList[i]);
  38160. } else {
  38161. rightmostX = Math.max(rightmostX, label.x);
  38162. rightList.push(labelLayoutList[i]);
  38163. }
  38164. }
  38165. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  38166. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  38167. for (var i = 0; i < labelLayoutList.length; i++) {
  38168. var layout = labelLayoutList[i];
  38169. var label = layout.label;
  38170. if (isPositionCenter(layout)) {
  38171. continue;
  38172. }
  38173. var linePoints = layout.linePoints;
  38174. if (linePoints) {
  38175. var isAlignToEdge = layout.labelAlignTo === 'edge';
  38176. var realTextWidth = layout.rect.width;
  38177. var targetTextWidth = void 0;
  38178. if (isAlignToEdge) {
  38179. if (label.x < cx) {
  38180. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.edgeDistance;
  38181. } else {
  38182. targetTextWidth = viewLeft + viewWidth - layout.edgeDistance - linePoints[2][0] - layout.labelDistance;
  38183. }
  38184. } else {
  38185. if (label.x < cx) {
  38186. targetTextWidth = label.x - viewLeft - layout.bleedMargin;
  38187. } else {
  38188. targetTextWidth = viewLeft + viewWidth - label.x - layout.bleedMargin;
  38189. }
  38190. }
  38191. if (targetTextWidth < layout.rect.width) {
  38192. // TODOTODO
  38193. // layout.text = textContain.truncateText(layout.text, targetTextWidth, layout.font);
  38194. layout.label.style.width = targetTextWidth;
  38195. if (layout.labelAlignTo === 'edge') {
  38196. realTextWidth = targetTextWidth; // realTextWidth = textContain.getWidth(layout.text, layout.font);
  38197. }
  38198. }
  38199. var dist = linePoints[1][0] - linePoints[2][0];
  38200. if (isAlignToEdge) {
  38201. if (label.x < cx) {
  38202. linePoints[2][0] = viewLeft + layout.edgeDistance + realTextWidth + layout.labelDistance;
  38203. } else {
  38204. linePoints[2][0] = viewLeft + viewWidth - layout.edgeDistance - realTextWidth - layout.labelDistance;
  38205. }
  38206. } else {
  38207. if (label.x < cx) {
  38208. linePoints[2][0] = label.x + layout.labelDistance;
  38209. } else {
  38210. linePoints[2][0] = label.x - layout.labelDistance;
  38211. }
  38212. linePoints[1][0] = linePoints[2][0] + dist;
  38213. }
  38214. linePoints[1][1] = linePoints[2][1] = label.y;
  38215. }
  38216. }
  38217. }
  38218. function isPositionCenter(sectorShape) {
  38219. // Not change x for center label
  38220. return sectorShape.position === 'center';
  38221. }
  38222. function pieLabelLayout(seriesModel) {
  38223. var data = seriesModel.getData();
  38224. var labelLayoutList = [];
  38225. var cx;
  38226. var cy;
  38227. var hasLabelRotate = false;
  38228. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  38229. var viewRect = data.getLayout('viewRect');
  38230. var r = data.getLayout('r');
  38231. var viewWidth = viewRect.width;
  38232. var viewLeft = viewRect.x;
  38233. var viewTop = viewRect.y;
  38234. var viewHeight = viewRect.height;
  38235. function setNotShow(el) {
  38236. el.ignore = true;
  38237. }
  38238. function isLabelShown(label) {
  38239. if (!label.ignore) {
  38240. return true;
  38241. }
  38242. for (var key in label.states) {
  38243. if (label.states[key].ignore === false) {
  38244. return true;
  38245. }
  38246. }
  38247. return false;
  38248. }
  38249. data.each(function (idx) {
  38250. var sector = data.getItemGraphicEl(idx);
  38251. var sectorShape = sector.shape;
  38252. var label = sector.getTextContent();
  38253. var labelLine = sector.getTextGuideLine();
  38254. var itemModel = data.getItemModel(idx);
  38255. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  38256. var labelPosition = labelModel.get('position') || itemModel.get(['emphasis', 'label', 'position']);
  38257. var labelDistance = labelModel.get('distanceToLabelLine');
  38258. var labelAlignTo = labelModel.get('alignTo');
  38259. var edgeDistance = parsePercent$1(labelModel.get('edgeDistance'), viewWidth);
  38260. var bleedMargin = labelModel.get('bleedMargin');
  38261. var labelLineModel = itemModel.getModel('labelLine');
  38262. var labelLineLen = labelLineModel.get('length');
  38263. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  38264. var labelLineLen2 = labelLineModel.get('length2');
  38265. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  38266. if (Math.abs(sectorShape.endAngle - sectorShape.startAngle) < minShowLabelRadian) {
  38267. each(label.states, setNotShow);
  38268. label.ignore = true;
  38269. return;
  38270. }
  38271. if (!isLabelShown(label)) {
  38272. return;
  38273. }
  38274. var midAngle = (sectorShape.startAngle + sectorShape.endAngle) / 2;
  38275. var nx = Math.cos(midAngle);
  38276. var ny = Math.sin(midAngle);
  38277. var textX;
  38278. var textY;
  38279. var linePoints;
  38280. var textAlign;
  38281. cx = sectorShape.cx;
  38282. cy = sectorShape.cy;
  38283. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  38284. if (labelPosition === 'center') {
  38285. textX = sectorShape.cx;
  38286. textY = sectorShape.cy;
  38287. textAlign = 'center';
  38288. } else {
  38289. var x1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * nx : sectorShape.r * nx) + cx;
  38290. var y1 = (isLabelInside ? (sectorShape.r + sectorShape.r0) / 2 * ny : sectorShape.r * ny) + cy;
  38291. textX = x1 + nx * 3;
  38292. textY = y1 + ny * 3;
  38293. if (!isLabelInside) {
  38294. // For roseType
  38295. var x2 = x1 + nx * (labelLineLen + r - sectorShape.r);
  38296. var y2 = y1 + ny * (labelLineLen + r - sectorShape.r);
  38297. var x3 = x2 + (nx < 0 ? -1 : 1) * labelLineLen2;
  38298. var y3 = y2;
  38299. if (labelAlignTo === 'edge') {
  38300. // Adjust textX because text align of edge is opposite
  38301. textX = nx < 0 ? viewLeft + edgeDistance : viewLeft + viewWidth - edgeDistance;
  38302. } else {
  38303. textX = x3 + (nx < 0 ? -labelDistance : labelDistance);
  38304. }
  38305. textY = y3;
  38306. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  38307. }
  38308. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? nx > 0 ? 'right' : 'left' : nx > 0 ? 'left' : 'right';
  38309. }
  38310. var labelRotate;
  38311. var rotate = labelModel.get('rotate');
  38312. if (typeof rotate === 'number') {
  38313. labelRotate = rotate * (Math.PI / 180);
  38314. } else {
  38315. labelRotate = rotate ? nx < 0 ? -midAngle + Math.PI : -midAngle : 0;
  38316. }
  38317. hasLabelRotate = !!labelRotate;
  38318. label.x = textX;
  38319. label.y = textY;
  38320. label.rotation = labelRotate;
  38321. label.setStyle({
  38322. verticalAlign: 'middle'
  38323. }); // Not sectorShape the inside label
  38324. if (!isLabelInside) {
  38325. var textRect = label.getBoundingRect().clone();
  38326. textRect.applyTransform(label.getComputedTransform()); // Text has a default 1px stroke. Exclude this.
  38327. var margin = (label.style.margin || 0) + 2.1;
  38328. textRect.y -= margin / 2;
  38329. textRect.height += margin;
  38330. labelLayoutList.push({
  38331. label: label,
  38332. labelLine: labelLine,
  38333. position: labelPosition,
  38334. len: labelLineLen,
  38335. len2: labelLineLen2,
  38336. minTurnAngle: labelLineModel.get('minTurnAngle'),
  38337. maxSurfaceAngle: labelLineModel.get('maxSurfaceAngle'),
  38338. surfaceNormal: new Point(nx, ny),
  38339. linePoints: linePoints,
  38340. textAlign: textAlign,
  38341. labelDistance: labelDistance,
  38342. labelAlignTo: labelAlignTo,
  38343. edgeDistance: edgeDistance,
  38344. bleedMargin: bleedMargin,
  38345. rect: textRect
  38346. });
  38347. } else {
  38348. label.setStyle({
  38349. align: textAlign
  38350. });
  38351. var selectState = label.states.select;
  38352. if (selectState) {
  38353. selectState.x += label.x;
  38354. selectState.y += label.y;
  38355. }
  38356. }
  38357. sector.setTextConfig({
  38358. inside: isLabelInside
  38359. });
  38360. });
  38361. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  38362. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  38363. }
  38364. for (var i = 0; i < labelLayoutList.length; i++) {
  38365. var layout = labelLayoutList[i];
  38366. var label = layout.label;
  38367. var labelLine = layout.labelLine;
  38368. var notShowLabel = isNaN(label.x) || isNaN(label.y);
  38369. if (label) {
  38370. label.setStyle({
  38371. align: layout.textAlign
  38372. });
  38373. if (notShowLabel) {
  38374. each(label.states, setNotShow);
  38375. label.ignore = true;
  38376. }
  38377. var selectState = label.states.select;
  38378. if (selectState) {
  38379. selectState.x += label.x;
  38380. selectState.y += label.y;
  38381. }
  38382. }
  38383. if (labelLine) {
  38384. var linePoints = layout.linePoints;
  38385. if (notShowLabel || !linePoints) {
  38386. each(labelLine.states, setNotShow);
  38387. labelLine.ignore = true;
  38388. } else {
  38389. limitTurnAngle(linePoints, layout.minTurnAngle);
  38390. limitSurfaceAngle(linePoints, layout.surfaceNormal, layout.maxSurfaceAngle);
  38391. labelLine.setShape({
  38392. points: linePoints
  38393. }); // Set the anchor to the midpoint of sector
  38394. label.__hostTarget.textGuideLineConfig = {
  38395. anchor: new Point(linePoints[0][0], linePoints[0][1])
  38396. };
  38397. }
  38398. }
  38399. }
  38400. }
  38401. function getSectorCornerRadius(model, shape) {
  38402. var cornerRadius = model.get('borderRadius');
  38403. if (cornerRadius == null) {
  38404. return null;
  38405. }
  38406. if (!isArray(cornerRadius)) {
  38407. cornerRadius = [cornerRadius, cornerRadius];
  38408. }
  38409. return {
  38410. innerCornerRadius: parsePercent(cornerRadius[0], shape.r0),
  38411. cornerRadius: parsePercent(cornerRadius[1], shape.r)
  38412. };
  38413. }
  38414. /**
  38415. * Piece of pie including Sector, Label, LabelLine
  38416. */
  38417. var PiePiece =
  38418. /** @class */
  38419. function (_super) {
  38420. __extends(PiePiece, _super);
  38421. function PiePiece(data, idx, startAngle) {
  38422. var _this = _super.call(this) || this;
  38423. _this.z2 = 2;
  38424. var polyline = new Polyline();
  38425. var text = new ZRText();
  38426. _this.setTextGuideLine(polyline);
  38427. _this.setTextContent(text);
  38428. _this.updateData(data, idx, startAngle, true);
  38429. return _this;
  38430. }
  38431. PiePiece.prototype.updateData = function (data, idx, startAngle, firstCreate) {
  38432. var sector = this;
  38433. var seriesModel = data.hostModel;
  38434. var itemModel = data.getItemModel(idx);
  38435. var emphasisModel = itemModel.getModel('emphasis');
  38436. var layout = data.getItemLayout(idx);
  38437. var sectorShape = extend(getSectorCornerRadius(itemModel.getModel('itemStyle'), layout) || {}, layout);
  38438. if (firstCreate) {
  38439. sector.setShape(sectorShape);
  38440. var animationType = seriesModel.getShallow('animationType');
  38441. if (animationType === 'scale') {
  38442. sector.shape.r = layout.r0;
  38443. initProps(sector, {
  38444. shape: {
  38445. r: layout.r
  38446. }
  38447. }, seriesModel, idx);
  38448. } // Expansion
  38449. else {
  38450. if (startAngle != null) {
  38451. sector.setShape({
  38452. startAngle: startAngle,
  38453. endAngle: startAngle
  38454. });
  38455. initProps(sector, {
  38456. shape: {
  38457. startAngle: layout.startAngle,
  38458. endAngle: layout.endAngle
  38459. }
  38460. }, seriesModel, idx);
  38461. } else {
  38462. sector.shape.endAngle = layout.startAngle;
  38463. updateProps(sector, {
  38464. shape: {
  38465. endAngle: layout.endAngle
  38466. }
  38467. }, seriesModel, idx);
  38468. }
  38469. }
  38470. } else {
  38471. // Transition animation from the old shape
  38472. updateProps(sector, {
  38473. shape: sectorShape
  38474. }, seriesModel, idx);
  38475. }
  38476. sector.useStyle(data.getItemVisual(idx, 'style'));
  38477. setStatesStylesFromModel(sector, itemModel);
  38478. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  38479. var offset = seriesModel.get('selectedOffset');
  38480. var dx = Math.cos(midAngle) * offset;
  38481. var dy = Math.sin(midAngle) * offset;
  38482. var cursorStyle = itemModel.getShallow('cursor');
  38483. cursorStyle && sector.attr('cursor', cursorStyle);
  38484. this._updateLabel(seriesModel, data, idx);
  38485. sector.ensureState('emphasis').shape = __assign({
  38486. r: layout.r + (emphasisModel.get('scale') ? emphasisModel.get('scaleSize') || 0 : 0)
  38487. }, getSectorCornerRadius(emphasisModel.getModel('itemStyle'), layout));
  38488. extend(sector.ensureState('select'), {
  38489. x: dx,
  38490. y: dy,
  38491. shape: getSectorCornerRadius(itemModel.getModel(['select', 'itemStyle']), layout)
  38492. });
  38493. extend(sector.ensureState('blur'), {
  38494. shape: getSectorCornerRadius(itemModel.getModel(['blur', 'itemStyle']), layout)
  38495. });
  38496. var labelLine = sector.getTextGuideLine();
  38497. var labelText = sector.getTextContent();
  38498. labelLine && extend(labelLine.ensureState('select'), {
  38499. x: dx,
  38500. y: dy
  38501. }); // TODO: needs dx, dy in zrender?
  38502. extend(labelText.ensureState('select'), {
  38503. x: dx,
  38504. y: dy
  38505. });
  38506. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  38507. };
  38508. PiePiece.prototype._updateLabel = function (seriesModel, data, idx) {
  38509. var _a;
  38510. var sector = this;
  38511. var itemModel = data.getItemModel(idx);
  38512. var labelLineModel = itemModel.getModel('labelLine');
  38513. var style = data.getItemVisual(idx, 'style');
  38514. var visualColor = style && style.fill;
  38515. var visualOpacity = style && style.opacity;
  38516. setLabelStyle(sector, getLabelStatesModels(itemModel), {
  38517. labelFetcher: data.hostModel,
  38518. labelDataIndex: idx,
  38519. inheritColor: visualColor,
  38520. defaultOpacity: visualOpacity,
  38521. defaultText: seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx)
  38522. });
  38523. var labelText = sector.getTextContent(); // Set textConfig on sector.
  38524. sector.setTextConfig({
  38525. // reset position, rotation
  38526. position: null,
  38527. rotation: null
  38528. }); // Make sure update style on labelText after setLabelStyle.
  38529. // Because setLabelStyle will replace a new style on it.
  38530. labelText.attr({
  38531. z2: 10
  38532. });
  38533. var labelPosition = seriesModel.get(['label', 'position']);
  38534. if (labelPosition !== 'outside' && labelPosition !== 'outer') {
  38535. (_a = sector.getTextGuideLine()) === null || _a === void 0 ? void 0 : _a.hide();
  38536. return;
  38537. } // Default use item visual color
  38538. setLabelLineStyle(this, getLabelLineStatesModels(itemModel), {
  38539. stroke: visualColor,
  38540. opacity: retrieve3(labelLineModel.get(['lineStyle', 'opacity']), visualOpacity, 1)
  38541. });
  38542. };
  38543. return PiePiece;
  38544. }(Sector); // Pie view
  38545. var PieView =
  38546. /** @class */
  38547. function (_super) {
  38548. __extends(PieView, _super);
  38549. function PieView() {
  38550. var _this = _super !== null && _super.apply(this, arguments) || this;
  38551. _this.ignoreLabelLineUpdate = true;
  38552. return _this;
  38553. }
  38554. PieView.prototype.init = function () {
  38555. var sectorGroup = new Group();
  38556. this._sectorGroup = sectorGroup;
  38557. };
  38558. PieView.prototype.render = function (seriesModel, ecModel, api, payload) {
  38559. var data = seriesModel.getData();
  38560. var oldData = this._data;
  38561. var group = this.group;
  38562. var startAngle; // First render
  38563. if (!oldData && data.count() > 0) {
  38564. var shape = data.getItemLayout(0);
  38565. for (var s = 1; isNaN(shape && shape.startAngle) && s < data.count(); ++s) {
  38566. shape = data.getItemLayout(s);
  38567. }
  38568. if (shape) {
  38569. startAngle = shape.startAngle;
  38570. }
  38571. }
  38572. data.diff(oldData).add(function (idx) {
  38573. var piePiece = new PiePiece(data, idx, startAngle);
  38574. data.setItemGraphicEl(idx, piePiece);
  38575. group.add(piePiece);
  38576. }).update(function (newIdx, oldIdx) {
  38577. var piePiece = oldData.getItemGraphicEl(oldIdx);
  38578. piePiece.updateData(data, newIdx, startAngle);
  38579. piePiece.off('click');
  38580. group.add(piePiece);
  38581. data.setItemGraphicEl(newIdx, piePiece);
  38582. }).remove(function (idx) {
  38583. var piePiece = oldData.getItemGraphicEl(idx);
  38584. removeElementWithFadeOut(piePiece, seriesModel, idx);
  38585. }).execute();
  38586. pieLabelLayout(seriesModel); // Always use initial animation.
  38587. if (seriesModel.get('animationTypeUpdate') !== 'expansion') {
  38588. this._data = data;
  38589. }
  38590. };
  38591. PieView.prototype.dispose = function () {};
  38592. PieView.prototype.containPoint = function (point, seriesModel) {
  38593. var data = seriesModel.getData();
  38594. var itemLayout = data.getItemLayout(0);
  38595. if (itemLayout) {
  38596. var dx = point[0] - itemLayout.cx;
  38597. var dy = point[1] - itemLayout.cy;
  38598. var radius = Math.sqrt(dx * dx + dy * dy);
  38599. return radius <= itemLayout.r && radius >= itemLayout.r0;
  38600. }
  38601. };
  38602. PieView.type = 'pie';
  38603. return PieView;
  38604. }(ChartView);
  38605. /**
  38606. * [Usage]:
  38607. * (1)
  38608. * createListSimply(seriesModel, ['value']);
  38609. * (2)
  38610. * createListSimply(seriesModel, {
  38611. * coordDimensions: ['value'],
  38612. * dimensionsCount: 5
  38613. * });
  38614. */
  38615. function createListSimply(seriesModel, opt, nameList) {
  38616. opt = isArray(opt) && {
  38617. coordDimensions: opt
  38618. } || extend({}, opt);
  38619. var source = seriesModel.getSource();
  38620. var dimensionsInfo = createDimensions(source, opt);
  38621. var list = new List(dimensionsInfo, seriesModel);
  38622. list.initData(source, nameList);
  38623. return list;
  38624. }
  38625. /*
  38626. * Licensed to the Apache Software Foundation (ASF) under one
  38627. * or more contributor license agreements. See the NOTICE file
  38628. * distributed with this work for additional information
  38629. * regarding copyright ownership. The ASF licenses this file
  38630. * to you under the Apache License, Version 2.0 (the
  38631. * "License"); you may not use this file except in compliance
  38632. * with the License. You may obtain a copy of the License at
  38633. *
  38634. * http://www.apache.org/licenses/LICENSE-2.0
  38635. *
  38636. * Unless required by applicable law or agreed to in writing,
  38637. * software distributed under the License is distributed on an
  38638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38639. * KIND, either express or implied. See the License for the
  38640. * specific language governing permissions and limitations
  38641. * under the License.
  38642. */
  38643. /**
  38644. * AUTO-GENERATED FILE. DO NOT MODIFY.
  38645. */
  38646. /*
  38647. * Licensed to the Apache Software Foundation (ASF) under one
  38648. * or more contributor license agreements. See the NOTICE file
  38649. * distributed with this work for additional information
  38650. * regarding copyright ownership. The ASF licenses this file
  38651. * to you under the Apache License, Version 2.0 (the
  38652. * "License"); you may not use this file except in compliance
  38653. * with the License. You may obtain a copy of the License at
  38654. *
  38655. * http://www.apache.org/licenses/LICENSE-2.0
  38656. *
  38657. * Unless required by applicable law or agreed to in writing,
  38658. * software distributed under the License is distributed on an
  38659. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38660. * KIND, either express or implied. See the License for the
  38661. * specific language governing permissions and limitations
  38662. * under the License.
  38663. */
  38664. /**
  38665. * LegendVisualProvider is an bridge that pick encoded color from data and
  38666. * provide to the legend component.
  38667. */
  38668. var LegendVisualProvider =
  38669. /** @class */
  38670. function () {
  38671. function LegendVisualProvider( // Function to get data after filtered. It stores all the encoding info
  38672. getDataWithEncodedVisual, // Function to get raw data before filtered.
  38673. getRawData) {
  38674. this._getDataWithEncodedVisual = getDataWithEncodedVisual;
  38675. this._getRawData = getRawData;
  38676. }
  38677. LegendVisualProvider.prototype.getAllNames = function () {
  38678. var rawData = this._getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  38679. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  38680. return rawData.mapArray(rawData.getName);
  38681. };
  38682. LegendVisualProvider.prototype.containName = function (name) {
  38683. var rawData = this._getRawData();
  38684. return rawData.indexOfName(name) >= 0;
  38685. };
  38686. LegendVisualProvider.prototype.indexOfName = function (name) {
  38687. // Only get data when necessary.
  38688. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  38689. // Invoking Series#getData immediately will throw an error.
  38690. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38691. return dataWithEncodedVisual.indexOfName(name);
  38692. };
  38693. LegendVisualProvider.prototype.getItemVisual = function (dataIndex, key) {
  38694. // Get encoded visual properties from final filtered data.
  38695. var dataWithEncodedVisual = this._getDataWithEncodedVisual();
  38696. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  38697. };
  38698. return LegendVisualProvider;
  38699. }();
  38700. var PieSeriesModel =
  38701. /** @class */
  38702. function (_super) {
  38703. __extends(PieSeriesModel, _super);
  38704. function PieSeriesModel() {
  38705. var _this = _super !== null && _super.apply(this, arguments) || this;
  38706. _this.useColorPaletteOnData = true;
  38707. return _this;
  38708. }
  38709. /**
  38710. * @overwrite
  38711. */
  38712. PieSeriesModel.prototype.init = function (option) {
  38713. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  38714. // Use a function instead of direct access because data reference may changed
  38715. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  38716. this._defaultLabelLine(option);
  38717. };
  38718. /**
  38719. * @overwrite
  38720. */
  38721. PieSeriesModel.prototype.mergeOption = function () {
  38722. _super.prototype.mergeOption.apply(this, arguments);
  38723. };
  38724. /**
  38725. * @overwrite
  38726. */
  38727. PieSeriesModel.prototype.getInitialData = function () {
  38728. return createListSimply(this, {
  38729. coordDimensions: ['value'],
  38730. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  38731. });
  38732. };
  38733. /**
  38734. * @overwrite
  38735. */
  38736. PieSeriesModel.prototype.getDataParams = function (dataIndex) {
  38737. var data = this.getData();
  38738. var params = _super.prototype.getDataParams.call(this, dataIndex); // FIXME toFixed?
  38739. var valueList = [];
  38740. data.each(data.mapDimension('value'), function (value) {
  38741. valueList.push(value);
  38742. });
  38743. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  38744. params.$vars.push('percent');
  38745. return params;
  38746. };
  38747. PieSeriesModel.prototype._defaultLabelLine = function (option) {
  38748. // Extend labelLine emphasis
  38749. defaultEmphasis(option, 'labelLine', ['show']);
  38750. var labelLineNormalOpt = option.labelLine;
  38751. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  38752. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  38753. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  38754. };
  38755. PieSeriesModel.type = 'series.pie';
  38756. PieSeriesModel.defaultOption = {
  38757. zlevel: 0,
  38758. z: 2,
  38759. legendHoverLink: true,
  38760. // 默认全局居中
  38761. center: ['50%', '50%'],
  38762. radius: [0, '75%'],
  38763. // 默认顺时针
  38764. clockwise: true,
  38765. startAngle: 90,
  38766. // 最小角度改为0
  38767. minAngle: 0,
  38768. // If the angle of a sector less than `minShowLabelAngle`,
  38769. // the label will not be displayed.
  38770. minShowLabelAngle: 0,
  38771. // 选中时扇区偏移量
  38772. selectedOffset: 10,
  38773. // 选择模式,默认关闭,可选single,multiple
  38774. // selectedMode: false,
  38775. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  38776. // roseType: null,
  38777. percentPrecision: 2,
  38778. // If still show when all data zero.
  38779. stillShowZeroSum: true,
  38780. // cursor: null,
  38781. left: 0,
  38782. top: 0,
  38783. right: 0,
  38784. bottom: 0,
  38785. width: null,
  38786. height: null,
  38787. label: {
  38788. // color: 'inherit',
  38789. // If rotate around circle
  38790. rotate: 0,
  38791. show: true,
  38792. overflow: 'truncate',
  38793. // 'outer', 'inside', 'center'
  38794. position: 'outer',
  38795. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  38796. alignTo: 'none',
  38797. // Closest distance between label and chart edge.
  38798. // Works only position is 'outer' and alignTo is 'edge'.
  38799. edgeDistance: '25%',
  38800. // Works only position is 'outer' and alignTo is not 'edge'.
  38801. bleedMargin: 10,
  38802. // Distance between text and label line.
  38803. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  38804. // 默认使用全局文本样式,详见TEXTSTYLE
  38805. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  38806. },
  38807. // Enabled when label.normal.position is 'outer'
  38808. labelLine: {
  38809. show: true,
  38810. // 引导线两段中的第一段长度
  38811. length: 15,
  38812. // 引导线两段中的第二段长度
  38813. length2: 15,
  38814. smooth: false,
  38815. minTurnAngle: 90,
  38816. maxSurfaceAngle: 90,
  38817. lineStyle: {
  38818. // color: 各异,
  38819. width: 1,
  38820. type: 'solid'
  38821. }
  38822. },
  38823. itemStyle: {
  38824. borderWidth: 1
  38825. },
  38826. labelLayout: {
  38827. // Hide the overlapped label.
  38828. hideOverlap: true
  38829. },
  38830. emphasis: {
  38831. scale: true,
  38832. scaleSize: 5
  38833. },
  38834. // If use strategy to avoid label overlapping
  38835. avoidLabelOverlap: true,
  38836. // Animation type. Valid values: expansion, scale
  38837. animationType: 'expansion',
  38838. animationDuration: 1000,
  38839. // Animation type when update. Valid values: transition, expansion
  38840. animationTypeUpdate: 'transition',
  38841. animationEasingUpdate: 'cubicInOut',
  38842. animationDurationUpdate: 500,
  38843. animationEasing: 'cubicInOut'
  38844. };
  38845. return PieSeriesModel;
  38846. }(SeriesModel);
  38847. function install$4(registers) {
  38848. registers.registerChartView(PieView);
  38849. registers.registerSeriesModel(PieSeriesModel);
  38850. createLegacyDataSelectAction('pie', registers.registerAction);
  38851. registers.registerLayout(curry(pieLayout, 'pie'));
  38852. registers.registerProcessor(dataFilter('pie'));
  38853. }
  38854. var ScatterSeriesModel =
  38855. /** @class */
  38856. function (_super) {
  38857. __extends(ScatterSeriesModel, _super);
  38858. function ScatterSeriesModel() {
  38859. var _this = _super !== null && _super.apply(this, arguments) || this;
  38860. _this.type = ScatterSeriesModel.type;
  38861. _this.hasSymbolVisual = true;
  38862. return _this;
  38863. }
  38864. ScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  38865. return createListFromArray(this.getSource(), this, {
  38866. useEncodeDefaulter: true
  38867. });
  38868. };
  38869. ScatterSeriesModel.prototype.getProgressive = function () {
  38870. var progressive = this.option.progressive;
  38871. if (progressive == null) {
  38872. // PENDING
  38873. return this.option.large ? 5e3 : this.get('progressive');
  38874. }
  38875. return progressive;
  38876. };
  38877. ScatterSeriesModel.prototype.getProgressiveThreshold = function () {
  38878. var progressiveThreshold = this.option.progressiveThreshold;
  38879. if (progressiveThreshold == null) {
  38880. // PENDING
  38881. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  38882. }
  38883. return progressiveThreshold;
  38884. };
  38885. ScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  38886. return selectors.point(data.getItemLayout(dataIndex));
  38887. };
  38888. ScatterSeriesModel.type = 'series.scatter';
  38889. ScatterSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  38890. ScatterSeriesModel.defaultOption = {
  38891. coordinateSystem: 'cartesian2d',
  38892. zlevel: 0,
  38893. z: 2,
  38894. legendHoverLink: true,
  38895. symbolSize: 10,
  38896. // symbolRotate: null, // 图形旋转控制
  38897. large: false,
  38898. // Available when large is true
  38899. largeThreshold: 2000,
  38900. // cursor: null,
  38901. itemStyle: {
  38902. opacity: 0.8 // color: 各异
  38903. },
  38904. emphasis: {
  38905. scale: true
  38906. },
  38907. // If clip the overflow graphics
  38908. // Works on cartesian / polar series
  38909. clip: true,
  38910. select: {
  38911. itemStyle: {
  38912. borderColor: '#212121'
  38913. }
  38914. } // progressive: null
  38915. };
  38916. return ScatterSeriesModel;
  38917. }(SeriesModel);
  38918. var BOOST_SIZE_THRESHOLD = 4;
  38919. var LargeSymbolPathShape =
  38920. /** @class */
  38921. function () {
  38922. function LargeSymbolPathShape() {}
  38923. return LargeSymbolPathShape;
  38924. }();
  38925. var LargeSymbolPath =
  38926. /** @class */
  38927. function (_super) {
  38928. __extends(LargeSymbolPath, _super);
  38929. function LargeSymbolPath(opts) {
  38930. return _super.call(this, opts) || this;
  38931. }
  38932. LargeSymbolPath.prototype.getDefaultShape = function () {
  38933. return new LargeSymbolPathShape();
  38934. };
  38935. LargeSymbolPath.prototype.buildPath = function (path, shape) {
  38936. var points = shape.points;
  38937. var size = shape.size;
  38938. var symbolProxy = this.symbolProxy;
  38939. var symbolProxyShape = symbolProxy.shape;
  38940. var ctx = path.getContext ? path.getContext() : path;
  38941. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD; // Do draw in afterBrush.
  38942. if (canBoost) {
  38943. this._ctx = ctx;
  38944. return;
  38945. }
  38946. this._ctx = null;
  38947. for (var i = 0; i < points.length;) {
  38948. var x = points[i++];
  38949. var y = points[i++];
  38950. if (isNaN(x) || isNaN(y)) {
  38951. continue;
  38952. }
  38953. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  38954. continue;
  38955. }
  38956. symbolProxyShape.x = x - size[0] / 2;
  38957. symbolProxyShape.y = y - size[1] / 2;
  38958. symbolProxyShape.width = size[0];
  38959. symbolProxyShape.height = size[1];
  38960. symbolProxy.buildPath(path, symbolProxyShape, true);
  38961. }
  38962. };
  38963. LargeSymbolPath.prototype.afterBrush = function () {
  38964. var shape = this.shape;
  38965. var points = shape.points;
  38966. var size = shape.size;
  38967. var ctx = this._ctx;
  38968. if (!ctx) {
  38969. return;
  38970. } // PENDING If style or other canvas status changed?
  38971. for (var i = 0; i < points.length;) {
  38972. var x = points[i++];
  38973. var y = points[i++];
  38974. if (isNaN(x) || isNaN(y)) {
  38975. continue;
  38976. }
  38977. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  38978. continue;
  38979. } // fillRect is faster than building a rect path and draw.
  38980. // And it support light globalCompositeOperation.
  38981. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  38982. }
  38983. };
  38984. LargeSymbolPath.prototype.findDataIndex = function (x, y) {
  38985. // TODO ???
  38986. // Consider transform
  38987. var shape = this.shape;
  38988. var points = shape.points;
  38989. var size = shape.size;
  38990. var w = Math.max(size[0], 4);
  38991. var h = Math.max(size[1], 4); // Not consider transform
  38992. // Treat each element as a rect
  38993. // top down traverse
  38994. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  38995. var i = idx * 2;
  38996. var x0 = points[i] - w / 2;
  38997. var y0 = points[i + 1] - h / 2;
  38998. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  38999. return idx;
  39000. }
  39001. }
  39002. return -1;
  39003. };
  39004. return LargeSymbolPath;
  39005. }(Path);
  39006. var LargeSymbolDraw =
  39007. /** @class */
  39008. function () {
  39009. function LargeSymbolDraw() {
  39010. this.group = new Group();
  39011. }
  39012. LargeSymbolDraw.prototype.isPersistent = function () {
  39013. return !this._incremental;
  39014. };
  39015. /**
  39016. * Update symbols draw by new data
  39017. */
  39018. LargeSymbolDraw.prototype.updateData = function (data, opt) {
  39019. this.group.removeAll();
  39020. var symbolEl = new LargeSymbolPath({
  39021. rectHover: true,
  39022. cursor: 'default'
  39023. });
  39024. symbolEl.setShape({
  39025. points: data.getLayout('points')
  39026. });
  39027. this._setCommon(symbolEl, data, false, opt);
  39028. this.group.add(symbolEl);
  39029. this._incremental = null;
  39030. };
  39031. LargeSymbolDraw.prototype.updateLayout = function (data) {
  39032. if (this._incremental) {
  39033. return;
  39034. }
  39035. var points = data.getLayout('points');
  39036. this.group.eachChild(function (child) {
  39037. if (child.startIndex != null) {
  39038. var len = (child.endIndex - child.startIndex) * 2;
  39039. var byteOffset = child.startIndex * 4 * 2;
  39040. points = new Float32Array(points.buffer, byteOffset, len);
  39041. }
  39042. child.setShape('points', points);
  39043. });
  39044. };
  39045. LargeSymbolDraw.prototype.incrementalPrepareUpdate = function (data) {
  39046. this.group.removeAll();
  39047. this._clearIncremental(); // Only use incremental displayables when data amount is larger than 2 million.
  39048. // PENDING Incremental data?
  39049. if (data.count() > 2e6) {
  39050. if (!this._incremental) {
  39051. this._incremental = new IncrementalDisplayable({
  39052. silent: true
  39053. });
  39054. }
  39055. this.group.add(this._incremental);
  39056. } else {
  39057. this._incremental = null;
  39058. }
  39059. };
  39060. LargeSymbolDraw.prototype.incrementalUpdate = function (taskParams, data, opt) {
  39061. var symbolEl;
  39062. if (this._incremental) {
  39063. symbolEl = new LargeSymbolPath();
  39064. this._incremental.addDisplayable(symbolEl, true);
  39065. } else {
  39066. symbolEl = new LargeSymbolPath({
  39067. rectHover: true,
  39068. cursor: 'default',
  39069. startIndex: taskParams.start,
  39070. endIndex: taskParams.end
  39071. });
  39072. symbolEl.incremental = true;
  39073. this.group.add(symbolEl);
  39074. }
  39075. symbolEl.setShape({
  39076. points: data.getLayout('points')
  39077. });
  39078. this._setCommon(symbolEl, data, !!this._incremental, opt);
  39079. };
  39080. LargeSymbolDraw.prototype._setCommon = function (symbolEl, data, isIncremental, opt) {
  39081. var hostModel = data.hostModel;
  39082. opt = opt || {};
  39083. var size = data.getVisual('symbolSize');
  39084. symbolEl.setShape('size', size instanceof Array ? size : [size, size]);
  39085. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  39086. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  39087. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  39088. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  39089. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  39090. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  39091. var globalStyle = data.getVisual('style');
  39092. var visualColor = globalStyle && globalStyle.fill;
  39093. if (visualColor) {
  39094. symbolEl.setColor(visualColor);
  39095. }
  39096. if (!isIncremental) {
  39097. var ecData_1 = getECData(symbolEl); // Enable tooltip
  39098. // PENDING May have performance issue when path is extremely large
  39099. ecData_1.seriesIndex = hostModel.seriesIndex;
  39100. symbolEl.on('mousemove', function (e) {
  39101. ecData_1.dataIndex = null;
  39102. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  39103. if (dataIndex >= 0) {
  39104. // Provide dataIndex for tooltip
  39105. ecData_1.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  39106. }
  39107. });
  39108. }
  39109. };
  39110. LargeSymbolDraw.prototype.remove = function () {
  39111. this._clearIncremental();
  39112. this._incremental = null;
  39113. this.group.removeAll();
  39114. };
  39115. LargeSymbolDraw.prototype._clearIncremental = function () {
  39116. var incremental = this._incremental;
  39117. if (incremental) {
  39118. incremental.clearDisplaybles();
  39119. }
  39120. };
  39121. return LargeSymbolDraw;
  39122. }();
  39123. var ScatterView =
  39124. /** @class */
  39125. function (_super) {
  39126. __extends(ScatterView, _super);
  39127. function ScatterView() {
  39128. var _this = _super !== null && _super.apply(this, arguments) || this;
  39129. _this.type = ScatterView.type;
  39130. return _this;
  39131. }
  39132. ScatterView.prototype.render = function (seriesModel, ecModel, api) {
  39133. var data = seriesModel.getData();
  39134. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39135. symbolDraw.updateData(data, {
  39136. // TODO
  39137. // If this parameter should be a shape or a bounding volume
  39138. // shape will be more general.
  39139. // But bounding volume like bounding rect will be much faster in the contain calculation
  39140. clipShape: this._getClipShape(seriesModel)
  39141. });
  39142. this._finished = true;
  39143. };
  39144. ScatterView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  39145. var data = seriesModel.getData();
  39146. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  39147. symbolDraw.incrementalPrepareUpdate(data);
  39148. this._finished = false;
  39149. };
  39150. ScatterView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  39151. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  39152. clipShape: this._getClipShape(seriesModel)
  39153. });
  39154. this._finished = taskParams.end === seriesModel.getData().count();
  39155. };
  39156. ScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  39157. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  39158. // PENDING
  39159. this.group.dirty();
  39160. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  39161. return {
  39162. update: true
  39163. };
  39164. } else {
  39165. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  39166. if (res.progress) {
  39167. res.progress({
  39168. start: 0,
  39169. end: data.count(),
  39170. count: data.count()
  39171. }, data);
  39172. }
  39173. this._symbolDraw.updateLayout(data);
  39174. }
  39175. };
  39176. ScatterView.prototype._getClipShape = function (seriesModel) {
  39177. var coordSys = seriesModel.coordinateSystem;
  39178. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  39179. return seriesModel.get('clip', true) ? clipArea : null;
  39180. };
  39181. ScatterView.prototype._updateSymbolDraw = function (data, seriesModel) {
  39182. var symbolDraw = this._symbolDraw;
  39183. var pipelineContext = seriesModel.pipelineContext;
  39184. var isLargeDraw = pipelineContext.large;
  39185. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  39186. symbolDraw && symbolDraw.remove();
  39187. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  39188. this._isLargeDraw = isLargeDraw;
  39189. this.group.removeAll();
  39190. }
  39191. this.group.add(symbolDraw.group);
  39192. return symbolDraw;
  39193. };
  39194. ScatterView.prototype.remove = function (ecModel, api) {
  39195. this._symbolDraw && this._symbolDraw.remove(true);
  39196. this._symbolDraw = null;
  39197. };
  39198. ScatterView.prototype.dispose = function () {};
  39199. ScatterView.type = 'scatter';
  39200. return ScatterView;
  39201. }(ChartView);
  39202. var GridModel =
  39203. /** @class */
  39204. function (_super) {
  39205. __extends(GridModel, _super);
  39206. function GridModel() {
  39207. return _super !== null && _super.apply(this, arguments) || this;
  39208. }
  39209. GridModel.type = 'grid';
  39210. GridModel.dependencies = ['xAxis', 'yAxis'];
  39211. GridModel.layoutMode = 'box';
  39212. GridModel.defaultOption = {
  39213. show: false,
  39214. zlevel: 0,
  39215. z: 0,
  39216. left: '10%',
  39217. top: 60,
  39218. right: '10%',
  39219. bottom: 70,
  39220. // If grid size contain label
  39221. containLabel: false,
  39222. // width: {totalWidth} - left - right,
  39223. // height: {totalHeight} - top - bottom,
  39224. backgroundColor: 'rgba(0,0,0,0)',
  39225. borderWidth: 1,
  39226. borderColor: '#ccc'
  39227. };
  39228. return GridModel;
  39229. }(ComponentModel);
  39230. var CartesianAxisModel =
  39231. /** @class */
  39232. function (_super) {
  39233. __extends(CartesianAxisModel, _super);
  39234. function CartesianAxisModel() {
  39235. return _super !== null && _super.apply(this, arguments) || this;
  39236. }
  39237. CartesianAxisModel.prototype.getCoordSysModel = function () {
  39238. return this.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  39239. };
  39240. CartesianAxisModel.type = 'cartesian2dAxis';
  39241. return CartesianAxisModel;
  39242. }(ComponentModel);
  39243. mixin(CartesianAxisModel, AxisModelCommonMixin);
  39244. var defaultOption = {
  39245. show: true,
  39246. zlevel: 0,
  39247. z: 0,
  39248. // Inverse the axis.
  39249. inverse: false,
  39250. // Axis name displayed.
  39251. name: '',
  39252. // 'start' | 'middle' | 'end'
  39253. nameLocation: 'end',
  39254. // By degree. By default auto rotate by nameLocation.
  39255. nameRotate: null,
  39256. nameTruncate: {
  39257. maxWidth: null,
  39258. ellipsis: '...',
  39259. placeholder: '.'
  39260. },
  39261. // Use global text style by default.
  39262. nameTextStyle: {},
  39263. // The gap between axisName and axisLine.
  39264. nameGap: 15,
  39265. // Default `false` to support tooltip.
  39266. silent: false,
  39267. // Default `false` to avoid legacy user event listener fail.
  39268. triggerEvent: false,
  39269. tooltip: {
  39270. show: false
  39271. },
  39272. axisPointer: {},
  39273. axisLine: {
  39274. show: true,
  39275. onZero: true,
  39276. onZeroAxisIndex: null,
  39277. lineStyle: {
  39278. color: '#6E7079',
  39279. width: 1,
  39280. type: 'solid'
  39281. },
  39282. // The arrow at both ends the the axis.
  39283. symbol: ['none', 'none'],
  39284. symbolSize: [10, 15]
  39285. },
  39286. axisTick: {
  39287. show: true,
  39288. // Whether axisTick is inside the grid or outside the grid.
  39289. inside: false,
  39290. // The length of axisTick.
  39291. length: 5,
  39292. lineStyle: {
  39293. width: 1
  39294. }
  39295. },
  39296. axisLabel: {
  39297. show: true,
  39298. // Whether axisLabel is inside the grid or outside the grid.
  39299. inside: false,
  39300. rotate: 0,
  39301. // true | false | null/undefined (auto)
  39302. showMinLabel: null,
  39303. // true | false | null/undefined (auto)
  39304. showMaxLabel: null,
  39305. margin: 8,
  39306. // formatter: null,
  39307. fontSize: 12
  39308. },
  39309. splitLine: {
  39310. show: true,
  39311. lineStyle: {
  39312. color: ['#E0E6F1'],
  39313. width: 1,
  39314. type: 'solid'
  39315. }
  39316. },
  39317. splitArea: {
  39318. show: false,
  39319. areaStyle: {
  39320. color: ['rgba(250,250,250,0.2)', 'rgba(210,219,238,0.2)']
  39321. }
  39322. }
  39323. };
  39324. var categoryAxis = merge({
  39325. // The gap at both ends of the axis. For categoryAxis, boolean.
  39326. boundaryGap: true,
  39327. // Set false to faster category collection.
  39328. deduplication: null,
  39329. // splitArea: {
  39330. // show: false
  39331. // },
  39332. splitLine: {
  39333. show: false
  39334. },
  39335. axisTick: {
  39336. // If tick is align with label when boundaryGap is true
  39337. alignWithLabel: false,
  39338. interval: 'auto'
  39339. },
  39340. axisLabel: {
  39341. interval: 'auto'
  39342. }
  39343. }, defaultOption);
  39344. var valueAxis = merge({
  39345. boundaryGap: [0, 0],
  39346. axisLine: {
  39347. // Not shown when other axis is categoryAxis in cartesian
  39348. show: 'auto'
  39349. },
  39350. axisTick: {
  39351. // Not shown when other axis is categoryAxis in cartesian
  39352. show: 'auto'
  39353. },
  39354. // TODO
  39355. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  39356. splitNumber: 5,
  39357. minorTick: {
  39358. // Minor tick, not available for cateogry axis.
  39359. show: false,
  39360. // Split number of minor ticks. The value should be in range of (0, 100)
  39361. splitNumber: 5,
  39362. // Lenght of minor tick
  39363. length: 3,
  39364. // Line style
  39365. lineStyle: {// Default to be same with axisTick
  39366. }
  39367. },
  39368. minorSplitLine: {
  39369. show: false,
  39370. lineStyle: {
  39371. color: '#F4F7FD',
  39372. width: 1
  39373. }
  39374. }
  39375. }, defaultOption);
  39376. var timeAxis = merge({
  39377. scale: true,
  39378. splitNumber: 6,
  39379. axisLabel: {
  39380. // To eliminate labels that are not nice
  39381. showMinLabel: false,
  39382. showMaxLabel: false,
  39383. rich: {
  39384. primary: {
  39385. fontWeight: 'bold'
  39386. }
  39387. }
  39388. },
  39389. splitLine: {
  39390. show: false
  39391. }
  39392. }, valueAxis);
  39393. var logAxis = defaults({
  39394. scale: true,
  39395. logBase: 10
  39396. }, valueAxis);
  39397. var axisDefault = {
  39398. category: categoryAxis,
  39399. value: valueAxis,
  39400. time: timeAxis,
  39401. log: logAxis
  39402. };
  39403. /*
  39404. * Licensed to the Apache Software Foundation (ASF) under one
  39405. * or more contributor license agreements. See the NOTICE file
  39406. * distributed with this work for additional information
  39407. * regarding copyright ownership. The ASF licenses this file
  39408. * to you under the Apache License, Version 2.0 (the
  39409. * "License"); you may not use this file except in compliance
  39410. * with the License. You may obtain a copy of the License at
  39411. *
  39412. * http://www.apache.org/licenses/LICENSE-2.0
  39413. *
  39414. * Unless required by applicable law or agreed to in writing,
  39415. * software distributed under the License is distributed on an
  39416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39417. * KIND, either express or implied. See the License for the
  39418. * specific language governing permissions and limitations
  39419. * under the License.
  39420. */
  39421. /**
  39422. * AUTO-GENERATED FILE. DO NOT MODIFY.
  39423. */
  39424. /*
  39425. * Licensed to the Apache Software Foundation (ASF) under one
  39426. * or more contributor license agreements. See the NOTICE file
  39427. * distributed with this work for additional information
  39428. * regarding copyright ownership. The ASF licenses this file
  39429. * to you under the Apache License, Version 2.0 (the
  39430. * "License"); you may not use this file except in compliance
  39431. * with the License. You may obtain a copy of the License at
  39432. *
  39433. * http://www.apache.org/licenses/LICENSE-2.0
  39434. *
  39435. * Unless required by applicable law or agreed to in writing,
  39436. * software distributed under the License is distributed on an
  39437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39438. * KIND, either express or implied. See the License for the
  39439. * specific language governing permissions and limitations
  39440. * under the License.
  39441. */
  39442. var AXIS_TYPES = {
  39443. value: 1,
  39444. category: 1,
  39445. time: 1,
  39446. log: 1
  39447. };
  39448. /**
  39449. * Generate sub axis model class
  39450. * @param axisName 'x' 'y' 'radius' 'angle' 'parallel' ...
  39451. */
  39452. function axisModelCreator(registers, axisName, BaseAxisModelClass, extraDefaultOption) {
  39453. each(AXIS_TYPES, function (v, axisType) {
  39454. var defaultOption = merge(merge({}, axisDefault[axisType], true), extraDefaultOption, true);
  39455. var AxisModel =
  39456. /** @class */
  39457. function (_super) {
  39458. __extends(AxisModel, _super);
  39459. function AxisModel() {
  39460. var args = [];
  39461. for (var _i = 0; _i < arguments.length; _i++) {
  39462. args[_i] = arguments[_i];
  39463. }
  39464. var _this = _super.apply(this, args) || this;
  39465. _this.type = axisName + 'Axis.' + axisType;
  39466. return _this;
  39467. }
  39468. AxisModel.prototype.mergeDefaultAndTheme = function (option, ecModel) {
  39469. var layoutMode = fetchLayoutMode(this);
  39470. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  39471. var themeModel = ecModel.getTheme();
  39472. merge(option, themeModel.get(axisType + 'Axis'));
  39473. merge(option, this.getDefaultOption());
  39474. option.type = getAxisType(option);
  39475. if (layoutMode) {
  39476. mergeLayoutParam(option, inputPositionParams, layoutMode);
  39477. }
  39478. };
  39479. AxisModel.prototype.optionUpdated = function () {
  39480. var thisOption = this.option;
  39481. if (thisOption.type === 'category') {
  39482. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  39483. }
  39484. };
  39485. /**
  39486. * Should not be called before all of 'getInitailData' finished.
  39487. * Because categories are collected during initializing data.
  39488. */
  39489. AxisModel.prototype.getCategories = function (rawData) {
  39490. var option = this.option; // FIXME
  39491. // warning if called before all of 'getInitailData' finished.
  39492. if (option.type === 'category') {
  39493. if (rawData) {
  39494. return option.data;
  39495. }
  39496. return this.__ordinalMeta.categories;
  39497. }
  39498. };
  39499. AxisModel.prototype.getOrdinalMeta = function () {
  39500. return this.__ordinalMeta;
  39501. };
  39502. AxisModel.type = axisName + 'Axis.' + axisType;
  39503. AxisModel.defaultOption = defaultOption;
  39504. return AxisModel;
  39505. }(BaseAxisModelClass);
  39506. registers.registerComponentModel(AxisModel);
  39507. });
  39508. registers.registerSubTypeDefaulter(axisName + 'Axis', getAxisType);
  39509. }
  39510. function getAxisType(option) {
  39511. // Default axis with data is category axis
  39512. return option.type || (option.data ? 'category' : 'value');
  39513. }
  39514. var Cartesian =
  39515. /** @class */
  39516. function () {
  39517. function Cartesian(name) {
  39518. this.type = 'cartesian';
  39519. this._dimList = [];
  39520. this._axes = {};
  39521. this.name = name || '';
  39522. }
  39523. Cartesian.prototype.getAxis = function (dim) {
  39524. return this._axes[dim];
  39525. };
  39526. Cartesian.prototype.getAxes = function () {
  39527. return map(this._dimList, function (dim) {
  39528. return this._axes[dim];
  39529. }, this);
  39530. };
  39531. Cartesian.prototype.getAxesByScale = function (scaleType) {
  39532. scaleType = scaleType.toLowerCase();
  39533. return filter(this.getAxes(), function (axis) {
  39534. return axis.scale.type === scaleType;
  39535. });
  39536. };
  39537. Cartesian.prototype.addAxis = function (axis) {
  39538. var dim = axis.dim;
  39539. this._axes[dim] = axis;
  39540. this._dimList.push(dim);
  39541. };
  39542. return Cartesian;
  39543. }();
  39544. var cartesian2DDimensions = ['x', 'y'];
  39545. function canCalculateAffineTransform(scale) {
  39546. return scale.type === 'interval' || scale.type === 'time';
  39547. }
  39548. var Cartesian2D =
  39549. /** @class */
  39550. function (_super) {
  39551. __extends(Cartesian2D, _super);
  39552. function Cartesian2D() {
  39553. var _this = _super !== null && _super.apply(this, arguments) || this;
  39554. _this.type = 'cartesian2d';
  39555. _this.dimensions = cartesian2DDimensions;
  39556. return _this;
  39557. }
  39558. /**
  39559. * Calculate an affine transform matrix if two axes are time or value.
  39560. * It's mainly for accelartion on the large time series data.
  39561. */
  39562. Cartesian2D.prototype.calcAffineTransform = function () {
  39563. this._transform = this._invTransform = null;
  39564. var xAxisScale = this.getAxis('x').scale;
  39565. var yAxisScale = this.getAxis('y').scale;
  39566. if (!canCalculateAffineTransform(xAxisScale) || !canCalculateAffineTransform(yAxisScale)) {
  39567. return;
  39568. }
  39569. var xScaleExtent = xAxisScale.getExtent();
  39570. var yScaleExtent = yAxisScale.getExtent();
  39571. var start = this.dataToPoint([xScaleExtent[0], yScaleExtent[0]]);
  39572. var end = this.dataToPoint([xScaleExtent[1], yScaleExtent[1]]);
  39573. var xScaleSpan = xScaleExtent[1] - xScaleExtent[0];
  39574. var yScaleSpan = yScaleExtent[1] - yScaleExtent[0];
  39575. if (!xScaleSpan || !yScaleSpan) {
  39576. return;
  39577. } // Accelerate data to point calculation on the special large time series data.
  39578. var scaleX = (end[0] - start[0]) / xScaleSpan;
  39579. var scaleY = (end[1] - start[1]) / yScaleSpan;
  39580. var translateX = start[0] - xScaleExtent[0] * scaleX;
  39581. var translateY = start[1] - yScaleExtent[0] * scaleY;
  39582. var m = this._transform = [scaleX, 0, 0, scaleY, translateX, translateY];
  39583. this._invTransform = invert([], m);
  39584. };
  39585. /**
  39586. * Base axis will be used on stacking.
  39587. */
  39588. Cartesian2D.prototype.getBaseAxis = function () {
  39589. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  39590. };
  39591. Cartesian2D.prototype.containPoint = function (point) {
  39592. var axisX = this.getAxis('x');
  39593. var axisY = this.getAxis('y');
  39594. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  39595. };
  39596. Cartesian2D.prototype.containData = function (data) {
  39597. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  39598. };
  39599. Cartesian2D.prototype.dataToPoint = function (data, reserved, out) {
  39600. out = out || [];
  39601. var xVal = data[0];
  39602. var yVal = data[1]; // Fast path
  39603. if (this._transform // It's supported that if data is like `[Inifity, 123]`, where only Y pixel calculated.
  39604. && xVal != null && isFinite(xVal) && yVal != null && isFinite(yVal)) {
  39605. return applyTransform(out, data, this._transform);
  39606. }
  39607. var xAxis = this.getAxis('x');
  39608. var yAxis = this.getAxis('y');
  39609. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(xVal));
  39610. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(yVal));
  39611. return out;
  39612. };
  39613. Cartesian2D.prototype.clampData = function (data, out) {
  39614. var xScale = this.getAxis('x').scale;
  39615. var yScale = this.getAxis('y').scale;
  39616. var xAxisExtent = xScale.getExtent();
  39617. var yAxisExtent = yScale.getExtent();
  39618. var x = xScale.parse(data[0]);
  39619. var y = yScale.parse(data[1]);
  39620. out = out || [];
  39621. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  39622. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  39623. return out;
  39624. };
  39625. Cartesian2D.prototype.pointToData = function (point, out) {
  39626. out = out || [];
  39627. if (this._invTransform) {
  39628. return applyTransform(out, point, this._invTransform);
  39629. }
  39630. var xAxis = this.getAxis('x');
  39631. var yAxis = this.getAxis('y');
  39632. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  39633. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  39634. return out;
  39635. };
  39636. Cartesian2D.prototype.getOtherAxis = function (axis) {
  39637. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  39638. };
  39639. /**
  39640. * Get rect area of cartesian.
  39641. * Area will have a contain function to determine if a point is in the coordinate system.
  39642. */
  39643. Cartesian2D.prototype.getArea = function () {
  39644. var xExtent = this.getAxis('x').getGlobalExtent();
  39645. var yExtent = this.getAxis('y').getGlobalExtent();
  39646. var x = Math.min(xExtent[0], xExtent[1]);
  39647. var y = Math.min(yExtent[0], yExtent[1]);
  39648. var width = Math.max(xExtent[0], xExtent[1]) - x;
  39649. var height = Math.max(yExtent[0], yExtent[1]) - y;
  39650. return new BoundingRect(x, y, width, height);
  39651. };
  39652. return Cartesian2D;
  39653. }(Cartesian);
  39654. var Axis2D =
  39655. /** @class */
  39656. function (_super) {
  39657. __extends(Axis2D, _super);
  39658. function Axis2D(dim, scale, coordExtent, axisType, position) {
  39659. var _this = _super.call(this, dim, scale, coordExtent) || this;
  39660. /**
  39661. * Index of axis, can be used as key
  39662. * Injected outside.
  39663. */
  39664. _this.index = 0;
  39665. _this.type = axisType || 'value';
  39666. _this.position = position || 'bottom';
  39667. return _this;
  39668. }
  39669. Axis2D.prototype.isHorizontal = function () {
  39670. var position = this.position;
  39671. return position === 'top' || position === 'bottom';
  39672. };
  39673. /**
  39674. * Each item cooresponds to this.getExtent(), which
  39675. * means globalExtent[0] may greater than globalExtent[1],
  39676. * unless `asc` is input.
  39677. *
  39678. * @param {boolean} [asc]
  39679. * @return {Array.<number>}
  39680. */
  39681. Axis2D.prototype.getGlobalExtent = function (asc) {
  39682. var ret = this.getExtent();
  39683. ret[0] = this.toGlobalCoord(ret[0]);
  39684. ret[1] = this.toGlobalCoord(ret[1]);
  39685. asc && ret[0] > ret[1] && ret.reverse();
  39686. return ret;
  39687. };
  39688. Axis2D.prototype.pointToData = function (point, clamp) {
  39689. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  39690. };
  39691. /**
  39692. * Set ordinalSortInfo
  39693. * @param info new OrdinalSortInfo
  39694. */
  39695. Axis2D.prototype.setCategorySortInfo = function (info) {
  39696. if (this.type !== 'category') {
  39697. return false;
  39698. }
  39699. this.model.option.categorySortInfo = info;
  39700. this.scale.setSortInfo(info);
  39701. };
  39702. return Axis2D;
  39703. }(Axis);
  39704. /**
  39705. * Can only be called after coordinate system creation stage.
  39706. * (Can be called before coordinate system update stage).
  39707. */
  39708. function layout$1(gridModel, axisModel, opt) {
  39709. opt = opt || {};
  39710. var grid = gridModel.coordinateSystem;
  39711. var axis = axisModel.axis;
  39712. var layout = {};
  39713. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  39714. var rawAxisPosition = axis.position;
  39715. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  39716. var axisDim = axis.dim;
  39717. var rect = grid.getRect();
  39718. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  39719. var idx = {
  39720. left: 0,
  39721. right: 1,
  39722. top: 0,
  39723. bottom: 1,
  39724. onZero: 2
  39725. };
  39726. var axisOffset = axisModel.get('offset') || 0;
  39727. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  39728. if (otherAxisOnZeroOf) {
  39729. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  39730. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  39731. } // Axis position
  39732. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  39733. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  39734. var dirMap = {
  39735. top: -1,
  39736. bottom: 1,
  39737. left: -1,
  39738. right: 1
  39739. };
  39740. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  39741. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  39742. if (axisModel.get(['axisTick', 'inside'])) {
  39743. layout.tickDirection = -layout.tickDirection;
  39744. }
  39745. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  39746. layout.labelDirection = -layout.labelDirection;
  39747. } // Special label rotation
  39748. var labelRotate = axisModel.get(['axisLabel', 'rotate']);
  39749. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  39750. layout.z2 = 1;
  39751. return layout;
  39752. }
  39753. function isCartesian2DSeries(seriesModel) {
  39754. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  39755. }
  39756. function findAxisModels(seriesModel) {
  39757. var axisModelMap = {
  39758. xAxisModel: null,
  39759. yAxisModel: null
  39760. };
  39761. each(axisModelMap, function (v, key) {
  39762. var axisType = key.replace(/Model$/, '');
  39763. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  39764. if ("development" !== 'production') {
  39765. if (!axisModel) {
  39766. throw new Error(axisType + ' "' + retrieve3(seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0) + '" not found');
  39767. }
  39768. }
  39769. axisModelMap[key] = axisModel;
  39770. });
  39771. return axisModelMap;
  39772. }
  39773. var Grid =
  39774. /** @class */
  39775. function () {
  39776. function Grid(gridModel, ecModel, api) {
  39777. // FIXME:TS where used (different from registered type 'cartesian2d')?
  39778. this.type = 'grid';
  39779. this._coordsMap = {};
  39780. this._coordsList = [];
  39781. this._axesMap = {};
  39782. this._axesList = [];
  39783. this.axisPointerEnabled = true;
  39784. this.dimensions = cartesian2DDimensions;
  39785. this._initCartesian(gridModel, ecModel, api);
  39786. this.model = gridModel;
  39787. }
  39788. Grid.prototype.getRect = function () {
  39789. return this._rect;
  39790. };
  39791. Grid.prototype.update = function (ecModel, api) {
  39792. var axesMap = this._axesMap;
  39793. this._updateScale(ecModel, this.model);
  39794. each(axesMap.x, function (xAxis) {
  39795. niceScaleExtent(xAxis.scale, xAxis.model);
  39796. });
  39797. each(axesMap.y, function (yAxis) {
  39798. niceScaleExtent(yAxis.scale, yAxis.model);
  39799. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  39800. var onZeroRecords = {};
  39801. each(axesMap.x, function (xAxis) {
  39802. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  39803. });
  39804. each(axesMap.y, function (yAxis) {
  39805. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  39806. }); // Resize again if containLabel is enabled
  39807. // FIXME It may cause getting wrong grid size in data processing stage
  39808. this.resize(this.model, api);
  39809. };
  39810. /**
  39811. * Resize the grid
  39812. */
  39813. Grid.prototype.resize = function (gridModel, api, ignoreContainLabel) {
  39814. var boxLayoutParams = gridModel.getBoxLayoutParams();
  39815. var isContainLabel = !ignoreContainLabel && gridModel.get('containLabel');
  39816. var gridRect = getLayoutRect(boxLayoutParams, {
  39817. width: api.getWidth(),
  39818. height: api.getHeight()
  39819. });
  39820. this._rect = gridRect;
  39821. var axesList = this._axesList;
  39822. adjustAxes(); // Minus label size
  39823. if (isContainLabel) {
  39824. each(axesList, function (axis) {
  39825. if (!axis.model.get(['axisLabel', 'inside'])) {
  39826. var labelUnionRect = estimateLabelUnionRect(axis);
  39827. if (labelUnionRect) {
  39828. var dim = axis.isHorizontal() ? 'height' : 'width';
  39829. var margin = axis.model.get(['axisLabel', 'margin']);
  39830. gridRect[dim] -= labelUnionRect[dim] + margin;
  39831. if (axis.position === 'top') {
  39832. gridRect.y += labelUnionRect.height + margin;
  39833. } else if (axis.position === 'left') {
  39834. gridRect.x += labelUnionRect.width + margin;
  39835. }
  39836. }
  39837. }
  39838. });
  39839. adjustAxes();
  39840. }
  39841. each(this._coordsList, function (coord) {
  39842. // Calculate affine matrix to accelerate the data to point transform.
  39843. // If all the axes scales are time or value.
  39844. coord.calcAffineTransform();
  39845. });
  39846. function adjustAxes() {
  39847. each(axesList, function (axis) {
  39848. var isHorizontal = axis.isHorizontal();
  39849. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  39850. var idx = axis.inverse ? 1 : 0;
  39851. axis.setExtent(extent[idx], extent[1 - idx]);
  39852. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  39853. });
  39854. }
  39855. };
  39856. Grid.prototype.getAxis = function (dim, axisIndex) {
  39857. var axesMapOnDim = this._axesMap[dim];
  39858. if (axesMapOnDim != null) {
  39859. return axesMapOnDim[axisIndex || 0]; // if (axisIndex == null) {
  39860. // Find first axis
  39861. // for (let name in axesMapOnDim) {
  39862. // if (axesMapOnDim.hasOwnProperty(name)) {
  39863. // return axesMapOnDim[name];
  39864. // }
  39865. // }
  39866. // }
  39867. // return axesMapOnDim[axisIndex];
  39868. }
  39869. };
  39870. Grid.prototype.getAxes = function () {
  39871. return this._axesList.slice();
  39872. };
  39873. Grid.prototype.getCartesian = function (xAxisIndex, yAxisIndex) {
  39874. if (xAxisIndex != null && yAxisIndex != null) {
  39875. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39876. return this._coordsMap[key];
  39877. }
  39878. if (isObject(xAxisIndex)) {
  39879. yAxisIndex = xAxisIndex.yAxisIndex;
  39880. xAxisIndex = xAxisIndex.xAxisIndex;
  39881. }
  39882. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  39883. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  39884. return coordList[i];
  39885. }
  39886. }
  39887. };
  39888. Grid.prototype.getCartesians = function () {
  39889. return this._coordsList.slice();
  39890. };
  39891. /**
  39892. * @implements
  39893. */
  39894. Grid.prototype.convertToPixel = function (ecModel, finder, value) {
  39895. var target = this._findConvertTarget(finder);
  39896. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  39897. };
  39898. /**
  39899. * @implements
  39900. */
  39901. Grid.prototype.convertFromPixel = function (ecModel, finder, value) {
  39902. var target = this._findConvertTarget(finder);
  39903. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  39904. };
  39905. Grid.prototype._findConvertTarget = function (finder) {
  39906. var seriesModel = finder.seriesModel;
  39907. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis', SINGLE_REFERRING).models[0];
  39908. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis', SINGLE_REFERRING).models[0];
  39909. var gridModel = finder.gridModel;
  39910. var coordsList = this._coordsList;
  39911. var cartesian;
  39912. var axis;
  39913. if (seriesModel) {
  39914. cartesian = seriesModel.coordinateSystem;
  39915. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  39916. } else if (xAxisModel && yAxisModel) {
  39917. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  39918. } else if (xAxisModel) {
  39919. axis = this.getAxis('x', xAxisModel.componentIndex);
  39920. } else if (yAxisModel) {
  39921. axis = this.getAxis('y', yAxisModel.componentIndex);
  39922. } // Lowest priority.
  39923. else if (gridModel) {
  39924. var grid = gridModel.coordinateSystem;
  39925. if (grid === this) {
  39926. cartesian = this._coordsList[0];
  39927. }
  39928. }
  39929. return {
  39930. cartesian: cartesian,
  39931. axis: axis
  39932. };
  39933. };
  39934. /**
  39935. * @implements
  39936. */
  39937. Grid.prototype.containPoint = function (point) {
  39938. var coord = this._coordsList[0];
  39939. if (coord) {
  39940. return coord.containPoint(point);
  39941. }
  39942. };
  39943. /**
  39944. * Initialize cartesian coordinate systems
  39945. */
  39946. Grid.prototype._initCartesian = function (gridModel, ecModel, api) {
  39947. var _this = this;
  39948. var grid = this;
  39949. var axisPositionUsed = {
  39950. left: false,
  39951. right: false,
  39952. top: false,
  39953. bottom: false
  39954. };
  39955. var axesMap = {
  39956. x: {},
  39957. y: {}
  39958. };
  39959. var axesCount = {
  39960. x: 0,
  39961. y: 0
  39962. }; /// Create axis
  39963. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  39964. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  39965. if (!axesCount.x || !axesCount.y) {
  39966. // Roll back when there no either x or y axis
  39967. this._axesMap = {};
  39968. this._axesList = [];
  39969. return;
  39970. }
  39971. this._axesMap = axesMap; /// Create cartesian2d
  39972. each(axesMap.x, function (xAxis, xAxisIndex) {
  39973. each(axesMap.y, function (yAxis, yAxisIndex) {
  39974. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  39975. var cartesian = new Cartesian2D(key);
  39976. cartesian.master = _this;
  39977. cartesian.model = gridModel;
  39978. _this._coordsMap[key] = cartesian;
  39979. _this._coordsList.push(cartesian);
  39980. cartesian.addAxis(xAxis);
  39981. cartesian.addAxis(yAxis);
  39982. });
  39983. });
  39984. function createAxisCreator(dimName) {
  39985. return function (axisModel, idx) {
  39986. if (!isAxisUsedInTheGrid(axisModel, gridModel)) {
  39987. return;
  39988. }
  39989. var axisPosition = axisModel.get('position');
  39990. if (dimName === 'x') {
  39991. // Fix position
  39992. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  39993. // Default bottom of X
  39994. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  39995. }
  39996. } else {
  39997. // Fix position
  39998. if (axisPosition !== 'left' && axisPosition !== 'right') {
  39999. // Default left of Y
  40000. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  40001. }
  40002. }
  40003. axisPositionUsed[axisPosition] = true;
  40004. var axis = new Axis2D(dimName, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  40005. var isCategory = axis.type === 'category';
  40006. axis.onBand = isCategory && axisModel.get('boundaryGap');
  40007. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  40008. axisModel.axis = axis; // Inject axisModel into axis
  40009. axis.model = axisModel; // Inject grid info axis
  40010. axis.grid = grid; // Index of axis, can be used as key
  40011. axis.index = idx;
  40012. grid._axesList.push(axis);
  40013. axesMap[dimName][idx] = axis;
  40014. axesCount[dimName]++;
  40015. };
  40016. }
  40017. };
  40018. /**
  40019. * Update cartesian properties from series.
  40020. */
  40021. Grid.prototype._updateScale = function (ecModel, gridModel) {
  40022. // Reset scale
  40023. each(this._axesList, function (axis) {
  40024. axis.scale.setExtent(Infinity, -Infinity);
  40025. if (axis.type === 'category') {
  40026. var categorySortInfo = axis.model.get('categorySortInfo');
  40027. axis.scale.setSortInfo(categorySortInfo);
  40028. }
  40029. });
  40030. ecModel.eachSeries(function (seriesModel) {
  40031. if (isCartesian2DSeries(seriesModel)) {
  40032. var axesModelMap = findAxisModels(seriesModel);
  40033. var xAxisModel = axesModelMap.xAxisModel;
  40034. var yAxisModel = axesModelMap.yAxisModel;
  40035. if (!isAxisUsedInTheGrid(xAxisModel, gridModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel)) {
  40036. return;
  40037. }
  40038. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  40039. var data = seriesModel.getData();
  40040. var xAxis = cartesian.getAxis('x');
  40041. var yAxis = cartesian.getAxis('y');
  40042. if (data.type === 'list') {
  40043. unionExtent(data, xAxis);
  40044. unionExtent(data, yAxis);
  40045. }
  40046. }
  40047. }, this);
  40048. function unionExtent(data, axis) {
  40049. each(getDataDimensionsOnAxis(data, axis.dim), function (dim) {
  40050. axis.scale.unionExtentFromData(data, dim);
  40051. });
  40052. }
  40053. };
  40054. /**
  40055. * @param dim 'x' or 'y' or 'auto' or null/undefined
  40056. */
  40057. Grid.prototype.getTooltipAxes = function (dim) {
  40058. var baseAxes = [];
  40059. var otherAxes = [];
  40060. each(this.getCartesians(), function (cartesian) {
  40061. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  40062. var otherAxis = cartesian.getOtherAxis(baseAxis);
  40063. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  40064. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  40065. });
  40066. return {
  40067. baseAxes: baseAxes,
  40068. otherAxes: otherAxes
  40069. };
  40070. };
  40071. Grid.create = function (ecModel, api) {
  40072. var grids = [];
  40073. ecModel.eachComponent('grid', function (gridModel, idx) {
  40074. var grid = new Grid(gridModel, ecModel, api);
  40075. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  40076. // should be performed in create stage.
  40077. grid.resize(gridModel, api, true);
  40078. gridModel.coordinateSystem = grid;
  40079. grids.push(grid);
  40080. }); // Inject the coordinateSystems into seriesModel
  40081. ecModel.eachSeries(function (seriesModel) {
  40082. if (!isCartesian2DSeries(seriesModel)) {
  40083. return;
  40084. }
  40085. var axesModelMap = findAxisModels(seriesModel);
  40086. var xAxisModel = axesModelMap.xAxisModel;
  40087. var yAxisModel = axesModelMap.yAxisModel;
  40088. var gridModel = xAxisModel.getCoordSysModel();
  40089. if ("development" !== 'production') {
  40090. if (!gridModel) {
  40091. throw new Error('Grid "' + retrieve3(xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0) + '" not found');
  40092. }
  40093. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  40094. throw new Error('xAxis and yAxis must use the same grid');
  40095. }
  40096. }
  40097. var grid = gridModel.coordinateSystem;
  40098. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  40099. });
  40100. return grids;
  40101. }; // For deciding which dimensions to use when creating list data
  40102. Grid.dimensions = cartesian2DDimensions;
  40103. return Grid;
  40104. }();
  40105. /**
  40106. * Check if the axis is used in the specified grid.
  40107. */
  40108. function isAxisUsedInTheGrid(axisModel, gridModel) {
  40109. return axisModel.getCoordSysModel() === gridModel;
  40110. }
  40111. function fixAxisOnZero(axesMap, otherAxisDim, axis, // Key: see `getOnZeroRecordKey`
  40112. onZeroRecords) {
  40113. axis.getAxesOnZeroOf = function () {
  40114. // TODO: onZero of multiple axes.
  40115. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  40116. }; // onZero can not be enabled in these two situations:
  40117. // 1. When any other axis is a category axis.
  40118. // 2. When no axis is cross 0 point.
  40119. var otherAxes = axesMap[otherAxisDim];
  40120. var otherAxisOnZeroOf;
  40121. var axisModel = axis.model;
  40122. var onZero = axisModel.get(['axisLine', 'onZero']);
  40123. var onZeroAxisIndex = axisModel.get(['axisLine', 'onZeroAxisIndex']);
  40124. if (!onZero) {
  40125. return;
  40126. } // If target axis is specified.
  40127. if (onZeroAxisIndex != null) {
  40128. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  40129. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  40130. }
  40131. } else {
  40132. // Find the first available other axis.
  40133. for (var idx in otherAxes) {
  40134. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  40135. // if both onZero, the two Y axes overlap.
  40136. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  40137. otherAxisOnZeroOf = otherAxes[idx];
  40138. break;
  40139. }
  40140. }
  40141. }
  40142. if (otherAxisOnZeroOf) {
  40143. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  40144. }
  40145. function getOnZeroRecordKey(axis) {
  40146. return axis.dim + '_' + axis.index;
  40147. }
  40148. }
  40149. function canOnZeroToAxis(axis) {
  40150. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  40151. }
  40152. function updateAxisTransform(axis, coordBase) {
  40153. var axisExtent = axis.getExtent();
  40154. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  40155. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  40156. return coord + coordBase;
  40157. } : function (coord) {
  40158. return axisExtentSum - coord + coordBase;
  40159. };
  40160. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  40161. return coord - coordBase;
  40162. } : function (coord) {
  40163. return axisExtentSum - coord + coordBase;
  40164. };
  40165. }
  40166. var PI$5 = Math.PI;
  40167. /**
  40168. * A final axis is translated and rotated from a "standard axis".
  40169. * So opt.position and opt.rotation is required.
  40170. *
  40171. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  40172. * for example: (0, 0) ------------> (0, 50)
  40173. *
  40174. * nameDirection or tickDirection or labelDirection is 1 means tick
  40175. * or label is below the standard axis, whereas is -1 means above
  40176. * the standard axis. labelOffset means offset between label and axis,
  40177. * which is useful when 'onZero', where axisLabel is in the grid and
  40178. * label in outside grid.
  40179. *
  40180. * Tips: like always,
  40181. * positive rotation represents anticlockwise, and negative rotation
  40182. * represents clockwise.
  40183. * The direction of position coordinate is the same as the direction
  40184. * of screen coordinate.
  40185. *
  40186. * Do not need to consider axis 'inverse', which is auto processed by
  40187. * axis extent.
  40188. */
  40189. var AxisBuilder =
  40190. /** @class */
  40191. function () {
  40192. function AxisBuilder(axisModel, opt) {
  40193. this.group = new Group();
  40194. this.opt = opt;
  40195. this.axisModel = axisModel; // Default value
  40196. defaults(opt, {
  40197. labelOffset: 0,
  40198. nameDirection: 1,
  40199. tickDirection: 1,
  40200. labelDirection: 1,
  40201. silent: true,
  40202. handleAutoShown: function () {
  40203. return true;
  40204. }
  40205. }); // FIXME Not use a seperate text group?
  40206. var transformGroup = new Group({
  40207. x: opt.position[0],
  40208. y: opt.position[1],
  40209. rotation: opt.rotation
  40210. }); // this.group.add(transformGroup);
  40211. // this._transformGroup = transformGroup;
  40212. transformGroup.updateTransform();
  40213. this._transformGroup = transformGroup;
  40214. }
  40215. AxisBuilder.prototype.hasBuilder = function (name) {
  40216. return !!builders[name];
  40217. };
  40218. AxisBuilder.prototype.add = function (name) {
  40219. builders[name](this.opt, this.axisModel, this.group, this._transformGroup);
  40220. };
  40221. AxisBuilder.prototype.getGroup = function () {
  40222. return this.group;
  40223. };
  40224. AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  40225. var rotationDiff = remRadian(textRotation - axisRotation);
  40226. var textAlign;
  40227. var textVerticalAlign;
  40228. if (isRadianAroundZero(rotationDiff)) {
  40229. // Label is parallel with axis line.
  40230. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  40231. textAlign = 'center';
  40232. } else if (isRadianAroundZero(rotationDiff - PI$5)) {
  40233. // Label is inverse parallel with axis line.
  40234. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  40235. textAlign = 'center';
  40236. } else {
  40237. textVerticalAlign = 'middle';
  40238. if (rotationDiff > 0 && rotationDiff < PI$5) {
  40239. textAlign = direction > 0 ? 'right' : 'left';
  40240. } else {
  40241. textAlign = direction > 0 ? 'left' : 'right';
  40242. }
  40243. }
  40244. return {
  40245. rotation: rotationDiff,
  40246. textAlign: textAlign,
  40247. textVerticalAlign: textVerticalAlign
  40248. };
  40249. };
  40250. AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  40251. var eventData = {
  40252. componentType: axisModel.mainType,
  40253. componentIndex: axisModel.componentIndex
  40254. };
  40255. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  40256. return eventData;
  40257. };
  40258. AxisBuilder.isLabelSilent = function (axisModel) {
  40259. var tooltipOpt = axisModel.get('tooltip');
  40260. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  40261. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  40262. };
  40263. return AxisBuilder;
  40264. }();
  40265. var builders = {
  40266. axisLine: function (opt, axisModel, group, transformGroup) {
  40267. var shown = axisModel.get(['axisLine', 'show']);
  40268. if (shown === 'auto' && opt.handleAutoShown) {
  40269. shown = opt.handleAutoShown('axisLine');
  40270. }
  40271. if (!shown) {
  40272. return;
  40273. }
  40274. var extent = axisModel.axis.getExtent();
  40275. var matrix = transformGroup.transform;
  40276. var pt1 = [extent[0], 0];
  40277. var pt2 = [extent[1], 0];
  40278. if (matrix) {
  40279. applyTransform(pt1, pt1, matrix);
  40280. applyTransform(pt2, pt2, matrix);
  40281. }
  40282. var lineStyle = extend({
  40283. lineCap: 'round'
  40284. }, axisModel.getModel(['axisLine', 'lineStyle']).getLineStyle());
  40285. var line = new Line({
  40286. // Id for animation
  40287. subPixelOptimize: true,
  40288. shape: {
  40289. x1: pt1[0],
  40290. y1: pt1[1],
  40291. x2: pt2[0],
  40292. y2: pt2[1]
  40293. },
  40294. style: lineStyle,
  40295. strokeContainThreshold: opt.strokeContainThreshold || 5,
  40296. silent: true,
  40297. z2: 1
  40298. });
  40299. line.anid = 'line';
  40300. group.add(line);
  40301. var arrows = axisModel.get(['axisLine', 'symbol']);
  40302. var arrowSize = axisModel.get(['axisLine', 'symbolSize']);
  40303. var arrowOffset = axisModel.get(['axisLine', 'symbolOffset']) || 0;
  40304. if (typeof arrowOffset === 'number') {
  40305. arrowOffset = [arrowOffset, arrowOffset];
  40306. }
  40307. if (arrows != null) {
  40308. if (typeof arrows === 'string') {
  40309. // Use the same arrow for start and end point
  40310. arrows = [arrows, arrows];
  40311. }
  40312. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  40313. // Use the same size for width and height
  40314. arrowSize = [arrowSize, arrowSize];
  40315. }
  40316. var symbolWidth_1 = arrowSize[0];
  40317. var symbolHeight_1 = arrowSize[1];
  40318. each([{
  40319. rotate: opt.rotation + Math.PI / 2,
  40320. offset: arrowOffset[0],
  40321. r: 0
  40322. }, {
  40323. rotate: opt.rotation - Math.PI / 2,
  40324. offset: arrowOffset[1],
  40325. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  40326. }], function (point, index) {
  40327. if (arrows[index] !== 'none' && arrows[index] != null) {
  40328. var symbol = createSymbol(arrows[index], -symbolWidth_1 / 2, -symbolHeight_1 / 2, symbolWidth_1, symbolHeight_1, lineStyle.stroke, true); // Calculate arrow position with offset
  40329. var r = point.r + point.offset;
  40330. symbol.attr({
  40331. rotation: point.rotate,
  40332. x: pt1[0] + r * Math.cos(opt.rotation),
  40333. y: pt1[1] - r * Math.sin(opt.rotation),
  40334. silent: true,
  40335. z2: 11
  40336. });
  40337. group.add(symbol);
  40338. }
  40339. });
  40340. }
  40341. },
  40342. axisTickLabel: function (opt, axisModel, group, transformGroup) {
  40343. var ticksEls = buildAxisMajorTicks(group, transformGroup, axisModel, opt);
  40344. var labelEls = buildAxisLabel(group, transformGroup, axisModel, opt);
  40345. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  40346. buildAxisMinorTicks(group, transformGroup, axisModel, opt.tickDirection);
  40347. },
  40348. axisName: function (opt, axisModel, group, transformGroup) {
  40349. var name = retrieve(opt.axisName, axisModel.get('name'));
  40350. if (!name) {
  40351. return;
  40352. }
  40353. var nameLocation = axisModel.get('nameLocation');
  40354. var nameDirection = opt.nameDirection;
  40355. var textStyleModel = axisModel.getModel('nameTextStyle');
  40356. var gap = axisModel.get('nameGap') || 0;
  40357. var extent = axisModel.axis.getExtent();
  40358. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  40359. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // Reuse labelOffset.
  40360. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  40361. var labelLayout;
  40362. var nameRotation = axisModel.get('nameRotate');
  40363. if (nameRotation != null) {
  40364. nameRotation = nameRotation * PI$5 / 180; // To radian.
  40365. }
  40366. var axisNameAvailableWidth;
  40367. if (isNameLocationCenter(nameLocation)) {
  40368. labelLayout = AxisBuilder.innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  40369. nameDirection);
  40370. } else {
  40371. labelLayout = endTextLayout(opt.rotation, nameLocation, nameRotation || 0, extent);
  40372. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  40373. if (axisNameAvailableWidth != null) {
  40374. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  40375. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  40376. }
  40377. }
  40378. var textFont = textStyleModel.getFont();
  40379. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  40380. var ellipsis = truncateOpt.ellipsis;
  40381. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth);
  40382. var tooltipOpt = axisModel.get('tooltip', true);
  40383. var mainType = axisModel.mainType;
  40384. var formatterParams = {
  40385. componentType: mainType,
  40386. name: name,
  40387. $vars: ['name']
  40388. };
  40389. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  40390. var textEl = new ZRText({
  40391. x: pos[0],
  40392. y: pos[1],
  40393. rotation: labelLayout.rotation,
  40394. silent: AxisBuilder.isLabelSilent(axisModel),
  40395. style: createTextStyle(textStyleModel, {
  40396. text: name,
  40397. font: textFont,
  40398. overflow: 'truncate',
  40399. width: maxWidth,
  40400. ellipsis: ellipsis,
  40401. fill: textStyleModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']),
  40402. align: textStyleModel.get('align') || labelLayout.textAlign,
  40403. verticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  40404. }),
  40405. z2: 1
  40406. });
  40407. textEl.tooltip = tooltipOpt && tooltipOpt.show ? extend({
  40408. content: name,
  40409. formatter: function () {
  40410. return name;
  40411. },
  40412. formatterParams: formatterParams
  40413. }, tooltipOpt) : null;
  40414. textEl.__fullText = name; // Id for animation
  40415. textEl.anid = 'name';
  40416. if (axisModel.get('triggerEvent')) {
  40417. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40418. eventData.targetType = 'axisName';
  40419. eventData.name = name;
  40420. getECData(textEl).eventData = eventData;
  40421. } // FIXME
  40422. transformGroup.add(textEl);
  40423. textEl.updateTransform();
  40424. group.add(textEl);
  40425. textEl.decomposeTransform();
  40426. }
  40427. };
  40428. function endTextLayout(rotation, textPosition, textRotate, extent) {
  40429. var rotationDiff = remRadian(textRotate - rotation);
  40430. var textAlign;
  40431. var textVerticalAlign;
  40432. var inverse = extent[0] > extent[1];
  40433. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  40434. if (isRadianAroundZero(rotationDiff - PI$5 / 2)) {
  40435. textVerticalAlign = onLeft ? 'bottom' : 'top';
  40436. textAlign = 'center';
  40437. } else if (isRadianAroundZero(rotationDiff - PI$5 * 1.5)) {
  40438. textVerticalAlign = onLeft ? 'top' : 'bottom';
  40439. textAlign = 'center';
  40440. } else {
  40441. textVerticalAlign = 'middle';
  40442. if (rotationDiff < PI$5 * 1.5 && rotationDiff > PI$5 / 2) {
  40443. textAlign = onLeft ? 'left' : 'right';
  40444. } else {
  40445. textAlign = onLeft ? 'right' : 'left';
  40446. }
  40447. }
  40448. return {
  40449. rotation: rotationDiff,
  40450. textAlign: textAlign,
  40451. textVerticalAlign: textVerticalAlign
  40452. };
  40453. }
  40454. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  40455. if (shouldShowAllLabels(axisModel.axis)) {
  40456. return;
  40457. } // If min or max are user set, we need to check
  40458. // If the tick on min(max) are overlap on their neighbour tick
  40459. // If they are overlapped, we need to hide the min(max) tick label
  40460. var showMinLabel = axisModel.get(['axisLabel', 'showMinLabel']);
  40461. var showMaxLabel = axisModel.get(['axisLabel', 'showMaxLabel']); // FIXME
  40462. // Have not consider onBand yet, where tick els is more than label els.
  40463. labelEls = labelEls || [];
  40464. tickEls = tickEls || [];
  40465. var firstLabel = labelEls[0];
  40466. var nextLabel = labelEls[1];
  40467. var lastLabel = labelEls[labelEls.length - 1];
  40468. var prevLabel = labelEls[labelEls.length - 2];
  40469. var firstTick = tickEls[0];
  40470. var nextTick = tickEls[1];
  40471. var lastTick = tickEls[tickEls.length - 1];
  40472. var prevTick = tickEls[tickEls.length - 2];
  40473. if (showMinLabel === false) {
  40474. ignoreEl(firstLabel);
  40475. ignoreEl(firstTick);
  40476. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  40477. if (showMinLabel) {
  40478. ignoreEl(nextLabel);
  40479. ignoreEl(nextTick);
  40480. } else {
  40481. ignoreEl(firstLabel);
  40482. ignoreEl(firstTick);
  40483. }
  40484. }
  40485. if (showMaxLabel === false) {
  40486. ignoreEl(lastLabel);
  40487. ignoreEl(lastTick);
  40488. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  40489. if (showMaxLabel) {
  40490. ignoreEl(prevLabel);
  40491. ignoreEl(prevTick);
  40492. } else {
  40493. ignoreEl(lastLabel);
  40494. ignoreEl(lastTick);
  40495. }
  40496. }
  40497. }
  40498. function ignoreEl(el) {
  40499. el && (el.ignore = true);
  40500. }
  40501. function isTwoLabelOverlapped(current, next) {
  40502. // current and next has the same rotation.
  40503. var firstRect = current && current.getBoundingRect().clone();
  40504. var nextRect = next && next.getBoundingRect().clone();
  40505. if (!firstRect || !nextRect) {
  40506. return;
  40507. } // When checking intersect of two rotated labels, we use mRotationBack
  40508. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  40509. var mRotationBack = identity([]);
  40510. rotate(mRotationBack, mRotationBack, -current.rotation);
  40511. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  40512. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  40513. return firstRect.intersect(nextRect);
  40514. }
  40515. function isNameLocationCenter(nameLocation) {
  40516. return nameLocation === 'middle' || nameLocation === 'center';
  40517. }
  40518. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, anidPrefix) {
  40519. var tickEls = [];
  40520. var pt1 = [];
  40521. var pt2 = [];
  40522. for (var i = 0; i < ticksCoords.length; i++) {
  40523. var tickCoord = ticksCoords[i].coord;
  40524. pt1[0] = tickCoord;
  40525. pt1[1] = 0;
  40526. pt2[0] = tickCoord;
  40527. pt2[1] = tickEndCoord;
  40528. if (tickTransform) {
  40529. applyTransform(pt1, pt1, tickTransform);
  40530. applyTransform(pt2, pt2, tickTransform);
  40531. } // Tick line, Not use group transform to have better line draw
  40532. var tickEl = new Line({
  40533. subPixelOptimize: true,
  40534. shape: {
  40535. x1: pt1[0],
  40536. y1: pt1[1],
  40537. x2: pt2[0],
  40538. y2: pt2[1]
  40539. },
  40540. style: tickLineStyle,
  40541. z2: 2,
  40542. autoBatch: true,
  40543. silent: true
  40544. });
  40545. tickEl.anid = anidPrefix + '_' + ticksCoords[i].tickValue;
  40546. tickEls.push(tickEl);
  40547. }
  40548. return tickEls;
  40549. }
  40550. function buildAxisMajorTicks(group, transformGroup, axisModel, opt) {
  40551. var axis = axisModel.axis;
  40552. var tickModel = axisModel.getModel('axisTick');
  40553. var shown = tickModel.get('show');
  40554. if (shown === 'auto' && opt.handleAutoShown) {
  40555. shown = opt.handleAutoShown('axisTick');
  40556. }
  40557. if (!shown || axis.scale.isBlank()) {
  40558. return;
  40559. }
  40560. var lineStyleModel = tickModel.getModel('lineStyle');
  40561. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  40562. var ticksCoords = axis.getTicksCoords();
  40563. var ticksEls = createTicks(ticksCoords, transformGroup.transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  40564. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40565. }), 'ticks');
  40566. for (var i = 0; i < ticksEls.length; i++) {
  40567. group.add(ticksEls[i]);
  40568. }
  40569. return ticksEls;
  40570. }
  40571. function buildAxisMinorTicks(group, transformGroup, axisModel, tickDirection) {
  40572. var axis = axisModel.axis;
  40573. var minorTickModel = axisModel.getModel('minorTick');
  40574. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  40575. return;
  40576. }
  40577. var minorTicksCoords = axis.getMinorTicksCoords();
  40578. if (!minorTicksCoords.length) {
  40579. return;
  40580. }
  40581. var lineStyleModel = minorTickModel.getModel('lineStyle');
  40582. var tickEndCoord = tickDirection * minorTickModel.get('length');
  40583. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  40584. stroke: axisModel.get(['axisLine', 'lineStyle', 'color'])
  40585. }));
  40586. for (var i = 0; i < minorTicksCoords.length; i++) {
  40587. var minorTicksEls = createTicks(minorTicksCoords[i], transformGroup.transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  40588. for (var k = 0; k < minorTicksEls.length; k++) {
  40589. group.add(minorTicksEls[k]);
  40590. }
  40591. }
  40592. }
  40593. function buildAxisLabel(group, transformGroup, axisModel, opt) {
  40594. var axis = axisModel.axis;
  40595. var show = retrieve(opt.axisLabelShow, axisModel.get(['axisLabel', 'show']));
  40596. if (!show || axis.scale.isBlank()) {
  40597. return;
  40598. }
  40599. var labelModel = axisModel.getModel('axisLabel');
  40600. var labelMargin = labelModel.get('margin');
  40601. var labels = axis.getViewLabels(); // Special label rotate.
  40602. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$5 / 180;
  40603. var labelLayout = AxisBuilder.innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  40604. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  40605. var labelEls = [];
  40606. var silent = AxisBuilder.isLabelSilent(axisModel);
  40607. var triggerEvent = axisModel.get('triggerEvent');
  40608. each(labels, function (labelItem, index) {
  40609. var tickValue = axis.scale.type === 'ordinal' ? axis.scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  40610. var formattedLabel = labelItem.formattedLabel;
  40611. var rawLabel = labelItem.rawLabel;
  40612. var itemLabelModel = labelModel;
  40613. if (rawCategoryData && rawCategoryData[tickValue]) {
  40614. var rawCategoryItem = rawCategoryData[tickValue];
  40615. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  40616. itemLabelModel = new Model(rawCategoryItem.textStyle, labelModel, axisModel.ecModel);
  40617. }
  40618. }
  40619. var textColor = itemLabelModel.getTextColor() || axisModel.get(['axisLine', 'lineStyle', 'color']);
  40620. var tickCoord = axis.dataToCoord(tickValue);
  40621. var textEl = new ZRText({
  40622. x: tickCoord,
  40623. y: opt.labelOffset + opt.labelDirection * labelMargin,
  40624. rotation: labelLayout.rotation,
  40625. silent: silent,
  40626. z2: 10,
  40627. style: createTextStyle(itemLabelModel, {
  40628. text: formattedLabel,
  40629. align: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  40630. verticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  40631. fill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  40632. // index of axis.data. So tick should not be exposed to user
  40633. // in category axis.
  40634. // (2) Compatible with previous version, which always use formatted label as
  40635. // input. But in interval scale the formatted label is like '223,445', which
  40636. // maked user repalce ','. So we modify it to return original val but remain
  40637. // it as 'string' to avoid error in replacing.
  40638. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  40639. })
  40640. });
  40641. textEl.anid = 'label_' + tickValue; // Pack data for mouse event
  40642. if (triggerEvent) {
  40643. var eventData = AxisBuilder.makeAxisEventDataBase(axisModel);
  40644. eventData.targetType = 'axisLabel';
  40645. eventData.value = rawLabel;
  40646. getECData(textEl).eventData = eventData;
  40647. } // FIXME
  40648. transformGroup.add(textEl);
  40649. textEl.updateTransform();
  40650. labelEls.push(textEl);
  40651. group.add(textEl);
  40652. textEl.decomposeTransform();
  40653. });
  40654. return labelEls;
  40655. }
  40656. // allAxesInfo should be updated when setOption performed.
  40657. function collect(ecModel, api) {
  40658. var result = {
  40659. /**
  40660. * key: makeKey(axis.model)
  40661. * value: {
  40662. * axis,
  40663. * coordSys,
  40664. * axisPointerModel,
  40665. * triggerTooltip,
  40666. * involveSeries,
  40667. * snap,
  40668. * seriesModels,
  40669. * seriesDataCount
  40670. * }
  40671. */
  40672. axesInfo: {},
  40673. seriesInvolved: false,
  40674. /**
  40675. * key: makeKey(coordSys.model)
  40676. * value: Object: key makeKey(axis.model), value: axisInfo
  40677. */
  40678. coordSysAxesInfo: {},
  40679. coordSysMap: {}
  40680. };
  40681. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  40682. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  40683. return result;
  40684. }
  40685. function collectAxesInfo(result, ecModel, api) {
  40686. var globalTooltipModel = ecModel.getComponent('tooltip');
  40687. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  40688. var linksOption = globalAxisPointerModel.get('link', true) || [];
  40689. var linkGroups = []; // Collect axes info.
  40690. each(api.getCoordinateSystems(), function (coordSys) {
  40691. // Some coordinate system do not support axes, like geo.
  40692. if (!coordSys.axisPointerEnabled) {
  40693. return;
  40694. }
  40695. var coordSysKey = makeKey(coordSys.model);
  40696. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  40697. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  40698. // for user. So we enable seting tooltip on coordSys model.
  40699. var coordSysModel = coordSys.model;
  40700. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  40701. each(coordSys.getAxes(), curry(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  40702. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  40703. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  40704. // show but axisPointer will show as normal.
  40705. && baseTooltipModel.get('show')) {
  40706. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  40707. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  40708. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  40709. var cross = baseTooltipModel.get(['axisPointer', 'type']) === 'cross';
  40710. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get(['axisPointer', 'axis']));
  40711. if (triggerAxis || cross) {
  40712. each(tooltipAxes.baseAxes, curry(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  40713. }
  40714. if (cross) {
  40715. each(tooltipAxes.otherAxes, curry(saveTooltipAxisInfo, 'cross', false));
  40716. }
  40717. } // fromTooltip: true | false | 'cross'
  40718. // triggerTooltip: true | false | null
  40719. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  40720. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  40721. var axisPointerShow = axisPointerModel.get('show');
  40722. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  40723. return;
  40724. }
  40725. if (triggerTooltip == null) {
  40726. triggerTooltip = axisPointerModel.get('triggerTooltip');
  40727. }
  40728. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  40729. var snap = axisPointerModel.get('snap');
  40730. var axisKey = makeKey(axis.model);
  40731. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  40732. var axisInfo = result.axesInfo[axisKey] = {
  40733. key: axisKey,
  40734. axis: axis,
  40735. coordSys: coordSys,
  40736. axisPointerModel: axisPointerModel,
  40737. triggerTooltip: triggerTooltip,
  40738. involveSeries: involveSeries,
  40739. snap: snap,
  40740. useHandle: isHandleTrigger(axisPointerModel),
  40741. seriesModels: [],
  40742. linkGroup: null
  40743. };
  40744. axesInfoInCoordSys[axisKey] = axisInfo;
  40745. result.seriesInvolved = result.seriesInvolved || involveSeries;
  40746. var groupIndex = getLinkGroupIndex(linksOption, axis);
  40747. if (groupIndex != null) {
  40748. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  40749. axesInfo: {}
  40750. });
  40751. linkGroup.axesInfo[axisKey] = axisInfo;
  40752. linkGroup.mapper = linksOption[groupIndex].mapper;
  40753. axisInfo.linkGroup = linkGroup;
  40754. }
  40755. }
  40756. });
  40757. }
  40758. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  40759. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  40760. var fields = ['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'];
  40761. var volatileOption = {};
  40762. each(fields, function (field) {
  40763. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  40764. }); // category axis do not auto snap, otherwise some tick that do not
  40765. // has value can not be hovered. value/time/log axis default snap if
  40766. // triggered from tooltip and trigger tooltip.
  40767. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  40768. // Only these properties can be overrided from tooltip to axisPointer.
  40769. if (tooltipAxisPointerModel.get('type') === 'cross') {
  40770. volatileOption.type = 'line';
  40771. }
  40772. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  40773. labelOption.show == null && (labelOption.show = false);
  40774. if (fromTooltip === 'cross') {
  40775. // When 'cross', both axes show labels.
  40776. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get(['label', 'show']);
  40777. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  40778. // (cross style is dashed by default)
  40779. if (!triggerTooltip) {
  40780. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  40781. crossStyle && defaults(labelOption, crossStyle.textStyle);
  40782. }
  40783. }
  40784. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  40785. }
  40786. function collectSeriesInfo(result, ecModel) {
  40787. // Prepare data for axis trigger
  40788. ecModel.eachSeries(function (seriesModel) {
  40789. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  40790. var coordSys = seriesModel.coordinateSystem;
  40791. var seriesTooltipTrigger = seriesModel.get(['tooltip', 'trigger'], true);
  40792. var seriesTooltipShow = seriesModel.get(['tooltip', 'show'], true);
  40793. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get(['axisPointer', 'show'], true) === false) {
  40794. return;
  40795. }
  40796. each(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  40797. var axis = axisInfo.axis;
  40798. if (coordSys.getAxis(axis.dim) === axis) {
  40799. axisInfo.seriesModels.push(seriesModel);
  40800. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  40801. axisInfo.seriesDataCount += seriesModel.getData().count();
  40802. }
  40803. });
  40804. });
  40805. }
  40806. /**
  40807. * For example:
  40808. * {
  40809. * axisPointer: {
  40810. * links: [{
  40811. * xAxisIndex: [2, 4],
  40812. * yAxisIndex: 'all'
  40813. * }, {
  40814. * xAxisId: ['a5', 'a7'],
  40815. * xAxisName: 'xxx'
  40816. * }]
  40817. * }
  40818. * }
  40819. */
  40820. function getLinkGroupIndex(linksOption, axis) {
  40821. var axisModel = axis.model;
  40822. var dim = axis.dim;
  40823. for (var i = 0; i < linksOption.length; i++) {
  40824. var linkOption = linksOption[i] || {};
  40825. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  40826. return i;
  40827. }
  40828. }
  40829. }
  40830. function checkPropInLink(linkPropValue, axisPropValue) {
  40831. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  40832. }
  40833. function fixValue(axisModel) {
  40834. var axisInfo = getAxisInfo(axisModel);
  40835. if (!axisInfo) {
  40836. return;
  40837. }
  40838. var axisPointerModel = axisInfo.axisPointerModel;
  40839. var scale = axisInfo.axis.scale;
  40840. var option = axisPointerModel.option;
  40841. var status = axisPointerModel.get('status');
  40842. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  40843. if (value != null) {
  40844. value = scale.parse(value);
  40845. }
  40846. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  40847. // and status should be initialized.
  40848. if (status == null) {
  40849. option.status = useHandle ? 'show' : 'hide';
  40850. }
  40851. var extent = scale.getExtent().slice();
  40852. extent[0] > extent[1] && extent.reverse();
  40853. if ( // Pick a value on axis when initializing.
  40854. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  40855. // where we should re-pick a value to keep `handle` displaying normally.
  40856. || value > extent[1]) {
  40857. // Make handle displayed on the end of the axis when init, which looks better.
  40858. value = extent[1];
  40859. }
  40860. if (value < extent[0]) {
  40861. value = extent[0];
  40862. }
  40863. option.value = value;
  40864. if (useHandle) {
  40865. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  40866. }
  40867. }
  40868. function getAxisInfo(axisModel) {
  40869. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  40870. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  40871. }
  40872. function getAxisPointerModel(axisModel) {
  40873. var axisInfo = getAxisInfo(axisModel);
  40874. return axisInfo && axisInfo.axisPointerModel;
  40875. }
  40876. function isHandleTrigger(axisPointerModel) {
  40877. return !!axisPointerModel.get(['handle', 'show']);
  40878. }
  40879. /**
  40880. * @param {module:echarts/model/Model} model
  40881. * @return {string} unique key
  40882. */
  40883. function makeKey(model) {
  40884. return model.type + '||' + model.id;
  40885. }
  40886. var axisPointerClazz = {};
  40887. /**
  40888. * Base class of AxisView.
  40889. */
  40890. var AxisView =
  40891. /** @class */
  40892. function (_super) {
  40893. __extends(AxisView, _super);
  40894. function AxisView() {
  40895. var _this = _super !== null && _super.apply(this, arguments) || this;
  40896. _this.type = AxisView.type;
  40897. return _this;
  40898. }
  40899. /**
  40900. * @override
  40901. */
  40902. AxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  40903. // FIXME
  40904. // This process should proformed after coordinate systems updated
  40905. // (axis scale updated), and should be performed each time update.
  40906. // So put it here temporarily, although it is not appropriate to
  40907. // put a model-writing procedure in `view`.
  40908. this.axisPointerClass && fixValue(axisModel);
  40909. _super.prototype.render.apply(this, arguments);
  40910. this._doUpdateAxisPointerClass(axisModel, api, true);
  40911. };
  40912. /**
  40913. * Action handler.
  40914. */
  40915. AxisView.prototype.updateAxisPointer = function (axisModel, ecModel, api, payload) {
  40916. this._doUpdateAxisPointerClass(axisModel, api, false);
  40917. };
  40918. /**
  40919. * @override
  40920. */
  40921. AxisView.prototype.remove = function (ecModel, api) {
  40922. var axisPointer = this._axisPointer;
  40923. axisPointer && axisPointer.remove(api);
  40924. };
  40925. /**
  40926. * @override
  40927. */
  40928. AxisView.prototype.dispose = function (ecModel, api) {
  40929. this._disposeAxisPointer(api);
  40930. _super.prototype.dispose.apply(this, arguments);
  40931. };
  40932. AxisView.prototype._doUpdateAxisPointerClass = function (axisModel, api, forceRender) {
  40933. var Clazz = AxisView.getAxisPointerClass(this.axisPointerClass);
  40934. if (!Clazz) {
  40935. return;
  40936. }
  40937. var axisPointerModel = getAxisPointerModel(axisModel);
  40938. axisPointerModel ? (this._axisPointer || (this._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : this._disposeAxisPointer(api);
  40939. };
  40940. AxisView.prototype._disposeAxisPointer = function (api) {
  40941. this._axisPointer && this._axisPointer.dispose(api);
  40942. this._axisPointer = null;
  40943. };
  40944. AxisView.registerAxisPointerClass = function (type, clazz) {
  40945. if ("development" !== 'production') {
  40946. if (axisPointerClazz[type]) {
  40947. throw new Error('axisPointer ' + type + ' exists');
  40948. }
  40949. }
  40950. axisPointerClazz[type] = clazz;
  40951. };
  40952. AxisView.getAxisPointerClass = function (type) {
  40953. return type && axisPointerClazz[type];
  40954. };
  40955. AxisView.type = 'axis';
  40956. return AxisView;
  40957. }(ComponentView);
  40958. var inner$5 = makeInner();
  40959. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  40960. var axis = axisModel.axis;
  40961. if (axis.scale.isBlank()) {
  40962. return;
  40963. } // TODO: TYPE
  40964. var splitAreaModel = axisModel.getModel('splitArea');
  40965. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  40966. var areaColors = areaStyleModel.get('color');
  40967. var gridRect = gridModel.coordinateSystem.getRect();
  40968. var ticksCoords = axis.getTicksCoords({
  40969. tickModel: splitAreaModel,
  40970. clamp: true
  40971. });
  40972. if (!ticksCoords.length) {
  40973. return;
  40974. } // For Making appropriate splitArea animation, the color and anid
  40975. // should be corresponding to previous one if possible.
  40976. var areaColorsLen = areaColors.length;
  40977. var lastSplitAreaColors = inner$5(axisView).splitAreaColors;
  40978. var newSplitAreaColors = createHashMap();
  40979. var colorIndex = 0;
  40980. if (lastSplitAreaColors) {
  40981. for (var i = 0; i < ticksCoords.length; i++) {
  40982. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  40983. if (cIndex != null) {
  40984. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  40985. break;
  40986. }
  40987. }
  40988. }
  40989. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  40990. var areaStyle = areaStyleModel.getAreaStyle();
  40991. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  40992. for (var i = 1; i < ticksCoords.length; i++) {
  40993. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  40994. var x = void 0;
  40995. var y = void 0;
  40996. var width = void 0;
  40997. var height = void 0;
  40998. if (axis.isHorizontal()) {
  40999. x = prev;
  41000. y = gridRect.y;
  41001. width = tickCoord - x;
  41002. height = gridRect.height;
  41003. prev = x + width;
  41004. } else {
  41005. x = gridRect.x;
  41006. y = prev;
  41007. width = gridRect.width;
  41008. height = tickCoord - y;
  41009. prev = y + height;
  41010. }
  41011. var tickValue = ticksCoords[i - 1].tickValue;
  41012. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  41013. axisGroup.add(new Rect({
  41014. anid: tickValue != null ? 'area_' + tickValue : null,
  41015. shape: {
  41016. x: x,
  41017. y: y,
  41018. width: width,
  41019. height: height
  41020. },
  41021. style: defaults({
  41022. fill: areaColors[colorIndex]
  41023. }, areaStyle),
  41024. autoBatch: true,
  41025. silent: true
  41026. }));
  41027. colorIndex = (colorIndex + 1) % areaColorsLen;
  41028. }
  41029. inner$5(axisView).splitAreaColors = newSplitAreaColors;
  41030. }
  41031. function rectCoordAxisHandleRemove(axisView) {
  41032. inner$5(axisView).splitAreaColors = null;
  41033. }
  41034. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  41035. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  41036. var CartesianAxisView =
  41037. /** @class */
  41038. function (_super) {
  41039. __extends(CartesianAxisView, _super);
  41040. function CartesianAxisView() {
  41041. var _this = _super !== null && _super.apply(this, arguments) || this;
  41042. _this.type = CartesianAxisView.type;
  41043. _this.axisPointerClass = 'CartesianAxisPointer';
  41044. return _this;
  41045. }
  41046. /**
  41047. * @override
  41048. */
  41049. CartesianAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  41050. this.group.removeAll();
  41051. var oldAxisGroup = this._axisGroup;
  41052. this._axisGroup = new Group();
  41053. this.group.add(this._axisGroup);
  41054. if (!axisModel.get('show')) {
  41055. return;
  41056. }
  41057. var gridModel = axisModel.getCoordSysModel();
  41058. var layout = layout$1(gridModel, axisModel);
  41059. var axisBuilder = new AxisBuilder(axisModel, extend({
  41060. handleAutoShown: function (elementType) {
  41061. var cartesians = gridModel.coordinateSystem.getCartesians();
  41062. for (var i = 0; i < cartesians.length; i++) {
  41063. var otherAxisType = cartesians[i].getOtherAxis(axisModel.axis).type;
  41064. if (otherAxisType === 'value' || otherAxisType === 'log') {
  41065. // Still show axis tick or axisLine if other axis is value / log
  41066. return true;
  41067. }
  41068. } // Not show axisTick or axisLine if other axis is category / time
  41069. return false;
  41070. }
  41071. }, layout));
  41072. each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  41073. this._axisGroup.add(axisBuilder.getGroup());
  41074. each(selfBuilderAttrs, function (name) {
  41075. if (axisModel.get([name, 'show'])) {
  41076. axisElementBuilders[name](this, this._axisGroup, axisModel, gridModel);
  41077. }
  41078. }, this);
  41079. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  41080. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  41081. };
  41082. CartesianAxisView.prototype.remove = function () {
  41083. rectCoordAxisHandleRemove(this);
  41084. };
  41085. CartesianAxisView.type = 'cartesianAxis';
  41086. return CartesianAxisView;
  41087. }(AxisView);
  41088. var axisElementBuilders = {
  41089. splitLine: function (axisView, axisGroup, axisModel, gridModel) {
  41090. var axis = axisModel.axis;
  41091. if (axis.scale.isBlank()) {
  41092. return;
  41093. }
  41094. var splitLineModel = axisModel.getModel('splitLine');
  41095. var lineStyleModel = splitLineModel.getModel('lineStyle');
  41096. var lineColors = lineStyleModel.get('color');
  41097. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  41098. var gridRect = gridModel.coordinateSystem.getRect();
  41099. var isHorizontal = axis.isHorizontal();
  41100. var lineCount = 0;
  41101. var ticksCoords = axis.getTicksCoords({
  41102. tickModel: splitLineModel
  41103. });
  41104. var p1 = [];
  41105. var p2 = [];
  41106. var lineStyle = lineStyleModel.getLineStyle();
  41107. for (var i = 0; i < ticksCoords.length; i++) {
  41108. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  41109. if (isHorizontal) {
  41110. p1[0] = tickCoord;
  41111. p1[1] = gridRect.y;
  41112. p2[0] = tickCoord;
  41113. p2[1] = gridRect.y + gridRect.height;
  41114. } else {
  41115. p1[0] = gridRect.x;
  41116. p1[1] = tickCoord;
  41117. p2[0] = gridRect.x + gridRect.width;
  41118. p2[1] = tickCoord;
  41119. }
  41120. var colorIndex = lineCount++ % lineColors.length;
  41121. var tickValue = ticksCoords[i].tickValue;
  41122. axisGroup.add(new Line({
  41123. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  41124. subPixelOptimize: true,
  41125. autoBatch: true,
  41126. shape: {
  41127. x1: p1[0],
  41128. y1: p1[1],
  41129. x2: p2[0],
  41130. y2: p2[1]
  41131. },
  41132. style: defaults({
  41133. stroke: lineColors[colorIndex]
  41134. }, lineStyle),
  41135. silent: true
  41136. }));
  41137. }
  41138. },
  41139. minorSplitLine: function (axisView, axisGroup, axisModel, gridModel) {
  41140. var axis = axisModel.axis;
  41141. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  41142. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  41143. var gridRect = gridModel.coordinateSystem.getRect();
  41144. var isHorizontal = axis.isHorizontal();
  41145. var minorTicksCoords = axis.getMinorTicksCoords();
  41146. if (!minorTicksCoords.length) {
  41147. return;
  41148. }
  41149. var p1 = [];
  41150. var p2 = [];
  41151. var lineStyle = lineStyleModel.getLineStyle();
  41152. for (var i = 0; i < minorTicksCoords.length; i++) {
  41153. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  41154. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  41155. if (isHorizontal) {
  41156. p1[0] = tickCoord;
  41157. p1[1] = gridRect.y;
  41158. p2[0] = tickCoord;
  41159. p2[1] = gridRect.y + gridRect.height;
  41160. } else {
  41161. p1[0] = gridRect.x;
  41162. p1[1] = tickCoord;
  41163. p2[0] = gridRect.x + gridRect.width;
  41164. p2[1] = tickCoord;
  41165. }
  41166. axisGroup.add(new Line({
  41167. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  41168. subPixelOptimize: true,
  41169. autoBatch: true,
  41170. shape: {
  41171. x1: p1[0],
  41172. y1: p1[1],
  41173. x2: p2[0],
  41174. y2: p2[1]
  41175. },
  41176. style: lineStyle,
  41177. silent: true
  41178. }));
  41179. }
  41180. }
  41181. },
  41182. splitArea: function (axisView, axisGroup, axisModel, gridModel) {
  41183. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel);
  41184. }
  41185. };
  41186. var CartesianXAxisView =
  41187. /** @class */
  41188. function (_super) {
  41189. __extends(CartesianXAxisView, _super);
  41190. function CartesianXAxisView() {
  41191. var _this = _super !== null && _super.apply(this, arguments) || this;
  41192. _this.type = CartesianXAxisView.type;
  41193. return _this;
  41194. }
  41195. CartesianXAxisView.type = 'xAxis';
  41196. return CartesianXAxisView;
  41197. }(CartesianAxisView);
  41198. var CartesianYAxisView =
  41199. /** @class */
  41200. function (_super) {
  41201. __extends(CartesianYAxisView, _super);
  41202. function CartesianYAxisView() {
  41203. var _this = _super !== null && _super.apply(this, arguments) || this;
  41204. _this.type = CartesianXAxisView.type;
  41205. return _this;
  41206. }
  41207. CartesianYAxisView.type = 'yAxis';
  41208. return CartesianYAxisView;
  41209. }(CartesianAxisView);
  41210. var GridView =
  41211. /** @class */
  41212. function (_super) {
  41213. __extends(GridView, _super);
  41214. function GridView() {
  41215. var _this = _super !== null && _super.apply(this, arguments) || this;
  41216. _this.type = 'grid';
  41217. return _this;
  41218. }
  41219. GridView.prototype.render = function (gridModel, ecModel) {
  41220. this.group.removeAll();
  41221. if (gridModel.get('show')) {
  41222. this.group.add(new Rect({
  41223. shape: gridModel.coordinateSystem.getRect(),
  41224. style: defaults({
  41225. fill: gridModel.get('backgroundColor')
  41226. }, gridModel.getItemStyle()),
  41227. silent: true,
  41228. z2: -1
  41229. }));
  41230. }
  41231. };
  41232. GridView.type = 'grid';
  41233. return GridView;
  41234. }(ComponentView);
  41235. var extraOption = {
  41236. // gridIndex: 0,
  41237. // gridId: '',
  41238. offset: 0
  41239. };
  41240. function install$5(registers) {
  41241. registers.registerComponentView(GridView);
  41242. registers.registerComponentModel(GridModel);
  41243. registers.registerCoordinateSystem('cartesian2d', Grid);
  41244. axisModelCreator(registers, 'x', CartesianAxisModel, extraOption);
  41245. axisModelCreator(registers, 'y', CartesianAxisModel, extraOption);
  41246. registers.registerComponentView(CartesianXAxisView);
  41247. registers.registerComponentView(CartesianYAxisView);
  41248. registers.registerPreprocessor(function (option) {
  41249. // Only create grid when need
  41250. if (option.xAxis && option.yAxis && !option.grid) {
  41251. option.grid = {};
  41252. }
  41253. });
  41254. }
  41255. function install$6(registers) {
  41256. // In case developer forget to include grid component
  41257. use(install$5);
  41258. registers.registerSeriesModel(ScatterSeriesModel);
  41259. registers.registerChartView(ScatterView);
  41260. registers.registerLayout(pointsLayout('scatter'));
  41261. }
  41262. function radarLayout(ecModel) {
  41263. ecModel.eachSeriesByType('radar', function (seriesModel) {
  41264. var data = seriesModel.getData();
  41265. var points = [];
  41266. var coordSys = seriesModel.coordinateSystem;
  41267. if (!coordSys) {
  41268. return;
  41269. }
  41270. var axes = coordSys.getIndicatorAxes();
  41271. each(axes, function (axis, axisIndex) {
  41272. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  41273. points[dataIndex] = points[dataIndex] || [];
  41274. var point = coordSys.dataToPoint(val, axisIndex);
  41275. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  41276. });
  41277. }); // Close polygon
  41278. data.each(function (idx) {
  41279. // TODO
  41280. // Is it appropriate to connect to the next data when some data is missing?
  41281. // Or, should trade it like `connectNull` in line chart?
  41282. var firstPoint = find(points[idx], function (point) {
  41283. return isValidPoint(point);
  41284. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  41285. points[idx].push(firstPoint.slice());
  41286. data.setItemLayout(idx, points[idx]);
  41287. });
  41288. });
  41289. }
  41290. function isValidPoint(point) {
  41291. return !isNaN(point[0]) && !isNaN(point[1]);
  41292. }
  41293. function getValueMissingPoint(coordSys) {
  41294. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  41295. // (probably cause problem when refreshing or animating)
  41296. return [coordSys.cx, coordSys.cy];
  41297. }
  41298. function radarBackwardCompat(option) {
  41299. var polarOptArr = option.polar;
  41300. if (polarOptArr) {
  41301. if (!isArray(polarOptArr)) {
  41302. polarOptArr = [polarOptArr];
  41303. }
  41304. var polarNotRadar_1 = [];
  41305. each(polarOptArr, function (polarOpt, idx) {
  41306. if (polarOpt.indicator) {
  41307. if (polarOpt.type && !polarOpt.shape) {
  41308. polarOpt.shape = polarOpt.type;
  41309. }
  41310. option.radar = option.radar || [];
  41311. if (!isArray(option.radar)) {
  41312. option.radar = [option.radar];
  41313. }
  41314. option.radar.push(polarOpt);
  41315. } else {
  41316. polarNotRadar_1.push(polarOpt);
  41317. }
  41318. });
  41319. option.polar = polarNotRadar_1;
  41320. }
  41321. each(option.series, function (seriesOpt) {
  41322. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  41323. seriesOpt.radarIndex = seriesOpt.polarIndex;
  41324. }
  41325. });
  41326. }
  41327. function normalizeSymbolSize(symbolSize) {
  41328. if (!isArray(symbolSize)) {
  41329. symbolSize = [+symbolSize, +symbolSize];
  41330. }
  41331. return symbolSize;
  41332. }
  41333. var RadarView =
  41334. /** @class */
  41335. function (_super) {
  41336. __extends(RadarView, _super);
  41337. function RadarView() {
  41338. var _this = _super !== null && _super.apply(this, arguments) || this;
  41339. _this.type = RadarView.type;
  41340. return _this;
  41341. }
  41342. RadarView.prototype.render = function (seriesModel, ecModel, api) {
  41343. var polar = seriesModel.coordinateSystem;
  41344. var group = this.group;
  41345. var data = seriesModel.getData();
  41346. var oldData = this._data;
  41347. function createSymbol$1(data, idx) {
  41348. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  41349. if (symbolType === 'none') {
  41350. return;
  41351. }
  41352. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  41353. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2);
  41354. var symbolRotate = data.getItemVisual(idx, 'symbolRotate') || 0;
  41355. symbolPath.attr({
  41356. style: {
  41357. strokeNoScale: true
  41358. },
  41359. z2: 100,
  41360. scaleX: symbolSize[0] / 2,
  41361. scaleY: symbolSize[1] / 2,
  41362. rotation: symbolRotate * Math.PI / 180 || 0
  41363. });
  41364. return symbolPath;
  41365. }
  41366. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  41367. // Simply rerender all
  41368. symbolGroup.removeAll();
  41369. for (var i = 0; i < newPoints.length - 1; i++) {
  41370. var symbolPath = createSymbol$1(data, idx);
  41371. if (symbolPath) {
  41372. symbolPath.__dimIdx = i;
  41373. if (oldPoints[i]) {
  41374. symbolPath.setPosition(oldPoints[i]);
  41375. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  41376. x: newPoints[i][0],
  41377. y: newPoints[i][1]
  41378. }, seriesModel, idx);
  41379. } else {
  41380. symbolPath.setPosition(newPoints[i]);
  41381. }
  41382. symbolGroup.add(symbolPath);
  41383. }
  41384. }
  41385. }
  41386. function getInitialPoints(points) {
  41387. return map(points, function (pt) {
  41388. return [polar.cx, polar.cy];
  41389. });
  41390. }
  41391. data.diff(oldData).add(function (idx) {
  41392. var points = data.getItemLayout(idx);
  41393. if (!points) {
  41394. return;
  41395. }
  41396. var polygon = new Polygon();
  41397. var polyline = new Polyline();
  41398. var target = {
  41399. shape: {
  41400. points: points
  41401. }
  41402. };
  41403. polygon.shape.points = getInitialPoints(points);
  41404. polyline.shape.points = getInitialPoints(points);
  41405. initProps(polygon, target, seriesModel, idx);
  41406. initProps(polyline, target, seriesModel, idx);
  41407. var itemGroup = new Group();
  41408. var symbolGroup = new Group();
  41409. itemGroup.add(polyline);
  41410. itemGroup.add(polygon);
  41411. itemGroup.add(symbolGroup);
  41412. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  41413. data.setItemGraphicEl(idx, itemGroup);
  41414. }).update(function (newIdx, oldIdx) {
  41415. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  41416. var polyline = itemGroup.childAt(0);
  41417. var polygon = itemGroup.childAt(1);
  41418. var symbolGroup = itemGroup.childAt(2);
  41419. var target = {
  41420. shape: {
  41421. points: data.getItemLayout(newIdx)
  41422. }
  41423. };
  41424. if (!target.shape.points) {
  41425. return;
  41426. }
  41427. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  41428. updateProps(polyline, target, seriesModel);
  41429. updateProps(polygon, target, seriesModel);
  41430. data.setItemGraphicEl(newIdx, itemGroup);
  41431. }).remove(function (idx) {
  41432. group.remove(oldData.getItemGraphicEl(idx));
  41433. }).execute();
  41434. data.eachItemGraphicEl(function (itemGroup, idx) {
  41435. var itemModel = data.getItemModel(idx);
  41436. var polyline = itemGroup.childAt(0);
  41437. var polygon = itemGroup.childAt(1);
  41438. var symbolGroup = itemGroup.childAt(2); // Radar uses the visual encoded from itemStyle.
  41439. var itemStyle = data.getItemVisual(idx, 'style');
  41440. var color = itemStyle.fill;
  41441. group.add(itemGroup);
  41442. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  41443. fill: 'none',
  41444. stroke: color
  41445. }));
  41446. setStatesStylesFromModel(polyline, itemModel, 'lineStyle');
  41447. setStatesStylesFromModel(polygon, itemModel, 'areaStyle');
  41448. var areaStyleModel = itemModel.getModel('areaStyle');
  41449. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  41450. polygon.ignore = polygonIgnore;
  41451. each(['emphasis', 'select', 'blur'], function (stateName) {
  41452. var stateModel = itemModel.getModel([stateName, 'areaStyle']);
  41453. var stateIgnore = stateModel.isEmpty() && stateModel.parentModel.isEmpty(); // Won't be ignore if normal state is not ignore.
  41454. polygon.ensureState(stateName).ignore = stateIgnore && polygonIgnore;
  41455. });
  41456. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  41457. fill: color,
  41458. opacity: 0.7,
  41459. decal: itemStyle.decal
  41460. }));
  41461. var emphasisModel = itemModel.getModel('emphasis');
  41462. var itemHoverStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  41463. symbolGroup.eachChild(function (symbolPath) {
  41464. if (symbolPath instanceof ZRImage) {
  41465. var pathStyle = symbolPath.style;
  41466. symbolPath.useStyle(extend({
  41467. // TODO other properties like x, y ?
  41468. image: pathStyle.image,
  41469. x: pathStyle.x,
  41470. y: pathStyle.y,
  41471. width: pathStyle.width,
  41472. height: pathStyle.height
  41473. }, itemStyle));
  41474. } else {
  41475. symbolPath.useStyle(itemStyle);
  41476. symbolPath.setColor(color);
  41477. }
  41478. var pathEmphasisState = symbolPath.ensureState('emphasis');
  41479. pathEmphasisState.style = clone(itemHoverStyle);
  41480. var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx);
  41481. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  41482. setLabelStyle(symbolPath, getLabelStatesModels(itemModel), {
  41483. labelFetcher: data.hostModel,
  41484. labelDataIndex: idx,
  41485. labelDimIndex: symbolPath.__dimIdx,
  41486. defaultText: defaultText,
  41487. inheritColor: color,
  41488. defaultOpacity: itemStyle.opacity
  41489. });
  41490. });
  41491. enableHoverEmphasis(itemGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  41492. });
  41493. this._data = data;
  41494. };
  41495. RadarView.prototype.remove = function () {
  41496. this.group.removeAll();
  41497. this._data = null;
  41498. };
  41499. RadarView.type = 'radar';
  41500. return RadarView;
  41501. }(ChartView);
  41502. var RadarSeriesModel =
  41503. /** @class */
  41504. function (_super) {
  41505. __extends(RadarSeriesModel, _super);
  41506. function RadarSeriesModel() {
  41507. var _this = _super !== null && _super.apply(this, arguments) || this;
  41508. _this.type = RadarSeriesModel.type;
  41509. _this.useColorPaletteOnData = true;
  41510. _this.hasSymbolVisual = true;
  41511. return _this;
  41512. } // Overwrite
  41513. RadarSeriesModel.prototype.init = function (option) {
  41514. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  41515. // Use a function instead of direct access because data reference may changed
  41516. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  41517. };
  41518. RadarSeriesModel.prototype.getInitialData = function (option, ecModel) {
  41519. return createListSimply(this, {
  41520. generateCoord: 'indicator_',
  41521. generateCoordCount: Infinity
  41522. });
  41523. };
  41524. RadarSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  41525. var data = this.getData();
  41526. var coordSys = this.coordinateSystem;
  41527. var indicatorAxes = coordSys.getIndicatorAxes();
  41528. var name = this.getData().getName(dataIndex);
  41529. var nameToDisplay = name === '' ? this.name : name;
  41530. var markerColor = retrieveVisualColorForTooltipMarker(this, dataIndex);
  41531. return createTooltipMarkup('section', {
  41532. header: nameToDisplay,
  41533. sortBlocks: true,
  41534. blocks: map(indicatorAxes, function (axis) {
  41535. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  41536. return createTooltipMarkup('nameValue', {
  41537. markerType: 'subItem',
  41538. markerColor: markerColor,
  41539. name: axis.name,
  41540. value: val,
  41541. sortParam: val
  41542. });
  41543. })
  41544. });
  41545. };
  41546. RadarSeriesModel.prototype.getTooltipPosition = function (dataIndex) {
  41547. if (dataIndex != null) {
  41548. var data_1 = this.getData();
  41549. var coordSys = this.coordinateSystem;
  41550. var values = data_1.getValues(map(coordSys.dimensions, function (dim) {
  41551. return data_1.mapDimension(dim);
  41552. }), dataIndex);
  41553. for (var i = 0, len = values.length; i < len; i++) {
  41554. if (!isNaN(values[i])) {
  41555. var indicatorAxes = coordSys.getIndicatorAxes();
  41556. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  41557. }
  41558. }
  41559. }
  41560. };
  41561. RadarSeriesModel.type = 'series.radar';
  41562. RadarSeriesModel.dependencies = ['radar'];
  41563. RadarSeriesModel.defaultOption = {
  41564. zlevel: 0,
  41565. z: 2,
  41566. coordinateSystem: 'radar',
  41567. legendHoverLink: true,
  41568. radarIndex: 0,
  41569. lineStyle: {
  41570. width: 2,
  41571. type: 'solid'
  41572. },
  41573. label: {
  41574. position: 'top'
  41575. },
  41576. // areaStyle: {
  41577. // },
  41578. // itemStyle: {}
  41579. symbol: 'emptyCircle',
  41580. symbolSize: 4 // symbolRotate: null
  41581. };
  41582. return RadarSeriesModel;
  41583. }(SeriesModel);
  41584. var valueAxisDefault = axisDefault.value;
  41585. function defaultsShow(opt, show) {
  41586. return defaults({
  41587. show: show
  41588. }, opt);
  41589. }
  41590. var RadarModel =
  41591. /** @class */
  41592. function (_super) {
  41593. __extends(RadarModel, _super);
  41594. function RadarModel() {
  41595. var _this = _super !== null && _super.apply(this, arguments) || this;
  41596. _this.type = RadarModel.type;
  41597. return _this;
  41598. }
  41599. RadarModel.prototype.optionUpdated = function () {
  41600. var boundaryGap = this.get('boundaryGap');
  41601. var splitNumber = this.get('splitNumber');
  41602. var scale = this.get('scale');
  41603. var axisLine = this.get('axisLine');
  41604. var axisTick = this.get('axisTick'); // let axisType = this.get('axisType');
  41605. var axisLabel = this.get('axisLabel');
  41606. var nameTextStyle = this.get('axisName');
  41607. var showName = this.get(['axisName', 'show']);
  41608. var nameFormatter = this.get(['axisName', 'formatter']);
  41609. var nameGap = this.get('axisNameGap');
  41610. var triggerEvent = this.get('triggerEvent');
  41611. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  41612. // PENDING
  41613. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  41614. indicatorOpt.min = 0;
  41615. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  41616. indicatorOpt.max = 0;
  41617. }
  41618. var iNameTextStyle = nameTextStyle;
  41619. if (indicatorOpt.color != null) {
  41620. iNameTextStyle = defaults({
  41621. color: indicatorOpt.color
  41622. }, nameTextStyle);
  41623. } // Use same configuration
  41624. var innerIndicatorOpt = merge(clone(indicatorOpt), {
  41625. boundaryGap: boundaryGap,
  41626. splitNumber: splitNumber,
  41627. scale: scale,
  41628. axisLine: axisLine,
  41629. axisTick: axisTick,
  41630. // axisType: axisType,
  41631. axisLabel: axisLabel,
  41632. // Compatible with 2 and use text
  41633. name: indicatorOpt.text,
  41634. nameLocation: 'end',
  41635. nameGap: nameGap,
  41636. // min: 0,
  41637. nameTextStyle: iNameTextStyle,
  41638. triggerEvent: triggerEvent
  41639. }, false);
  41640. if (!showName) {
  41641. innerIndicatorOpt.name = '';
  41642. }
  41643. if (typeof nameFormatter === 'string') {
  41644. var indName = innerIndicatorOpt.name;
  41645. innerIndicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  41646. } else if (typeof nameFormatter === 'function') {
  41647. innerIndicatorOpt.name = nameFormatter(innerIndicatorOpt.name, innerIndicatorOpt);
  41648. }
  41649. var model = new Model(innerIndicatorOpt, null, this.ecModel);
  41650. mixin(model, AxisModelCommonMixin.prototype); // For triggerEvent.
  41651. model.mainType = 'radar';
  41652. model.componentIndex = this.componentIndex;
  41653. return model;
  41654. }, this);
  41655. this._indicatorModels = indicatorModels;
  41656. };
  41657. RadarModel.prototype.getIndicatorModels = function () {
  41658. return this._indicatorModels;
  41659. };
  41660. RadarModel.type = 'radar';
  41661. RadarModel.defaultOption = {
  41662. zlevel: 0,
  41663. z: 0,
  41664. center: ['50%', '50%'],
  41665. radius: '75%',
  41666. startAngle: 90,
  41667. axisName: {
  41668. show: true // formatter: null
  41669. // textStyle: {}
  41670. },
  41671. boundaryGap: [0, 0],
  41672. splitNumber: 5,
  41673. axisNameGap: 15,
  41674. scale: false,
  41675. // Polygon or circle
  41676. shape: 'polygon',
  41677. axisLine: merge({
  41678. lineStyle: {
  41679. color: '#bbb'
  41680. }
  41681. }, valueAxisDefault.axisLine),
  41682. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  41683. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  41684. // axisType: 'value',
  41685. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  41686. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  41687. // {text, min, max}
  41688. indicator: []
  41689. };
  41690. return RadarModel;
  41691. }(ComponentModel);
  41692. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  41693. var RadarView$1 =
  41694. /** @class */
  41695. function (_super) {
  41696. __extends(RadarView, _super);
  41697. function RadarView() {
  41698. var _this = _super !== null && _super.apply(this, arguments) || this;
  41699. _this.type = RadarView.type;
  41700. return _this;
  41701. }
  41702. RadarView.prototype.render = function (radarModel, ecModel, api) {
  41703. var group = this.group;
  41704. group.removeAll();
  41705. this._buildAxes(radarModel);
  41706. this._buildSplitLineAndArea(radarModel);
  41707. };
  41708. RadarView.prototype._buildAxes = function (radarModel) {
  41709. var radar = radarModel.coordinateSystem;
  41710. var indicatorAxes = radar.getIndicatorAxes();
  41711. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  41712. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  41713. position: [radar.cx, radar.cy],
  41714. rotation: indicatorAxis.angle,
  41715. labelDirection: -1,
  41716. tickDirection: -1,
  41717. nameDirection: 1
  41718. });
  41719. return axisBuilder;
  41720. });
  41721. each(axisBuilders, function (axisBuilder) {
  41722. each(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  41723. this.group.add(axisBuilder.getGroup());
  41724. }, this);
  41725. };
  41726. RadarView.prototype._buildSplitLineAndArea = function (radarModel) {
  41727. var radar = radarModel.coordinateSystem;
  41728. var indicatorAxes = radar.getIndicatorAxes();
  41729. if (!indicatorAxes.length) {
  41730. return;
  41731. }
  41732. var shape = radarModel.get('shape');
  41733. var splitLineModel = radarModel.getModel('splitLine');
  41734. var splitAreaModel = radarModel.getModel('splitArea');
  41735. var lineStyleModel = splitLineModel.getModel('lineStyle');
  41736. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  41737. var showSplitLine = splitLineModel.get('show');
  41738. var showSplitArea = splitAreaModel.get('show');
  41739. var splitLineColors = lineStyleModel.get('color');
  41740. var splitAreaColors = areaStyleModel.get('color');
  41741. var splitLineColorsArr = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  41742. var splitAreaColorsArr = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  41743. var splitLines = [];
  41744. var splitAreas = [];
  41745. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  41746. var colorIndex = idx % areaOrLineColorList.length;
  41747. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  41748. return colorIndex;
  41749. }
  41750. if (shape === 'circle') {
  41751. var ticksRadius = indicatorAxes[0].getTicksCoords();
  41752. var cx = radar.cx;
  41753. var cy = radar.cy;
  41754. for (var i = 0; i < ticksRadius.length; i++) {
  41755. if (showSplitLine) {
  41756. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  41757. splitLines[colorIndex].push(new Circle({
  41758. shape: {
  41759. cx: cx,
  41760. cy: cy,
  41761. r: ticksRadius[i].coord
  41762. }
  41763. }));
  41764. }
  41765. if (showSplitArea && i < ticksRadius.length - 1) {
  41766. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i);
  41767. splitAreas[colorIndex].push(new Ring({
  41768. shape: {
  41769. cx: cx,
  41770. cy: cy,
  41771. r0: ticksRadius[i].coord,
  41772. r: ticksRadius[i + 1].coord
  41773. }
  41774. }));
  41775. }
  41776. }
  41777. } // Polyyon
  41778. else {
  41779. var realSplitNumber_1;
  41780. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  41781. var ticksCoords = indicatorAxis.getTicksCoords();
  41782. realSplitNumber_1 = realSplitNumber_1 == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber_1);
  41783. return map(ticksCoords, function (tickCoord) {
  41784. return radar.coordToPoint(tickCoord.coord, idx);
  41785. });
  41786. });
  41787. var prevPoints = [];
  41788. for (var i = 0; i <= realSplitNumber_1; i++) {
  41789. var points = [];
  41790. for (var j = 0; j < indicatorAxes.length; j++) {
  41791. points.push(axesTicksPoints[j][i]);
  41792. } // Close
  41793. if (points[0]) {
  41794. points.push(points[0].slice());
  41795. } else {
  41796. if ("development" !== 'production') {
  41797. console.error('Can\'t draw value axis ' + i);
  41798. }
  41799. }
  41800. if (showSplitLine) {
  41801. var colorIndex = getColorIndex(splitLines, splitLineColorsArr, i);
  41802. splitLines[colorIndex].push(new Polyline({
  41803. shape: {
  41804. points: points
  41805. }
  41806. }));
  41807. }
  41808. if (showSplitArea && prevPoints) {
  41809. var colorIndex = getColorIndex(splitAreas, splitAreaColorsArr, i - 1);
  41810. splitAreas[colorIndex].push(new Polygon({
  41811. shape: {
  41812. points: points.concat(prevPoints)
  41813. }
  41814. }));
  41815. }
  41816. prevPoints = points.slice().reverse();
  41817. }
  41818. }
  41819. var lineStyle = lineStyleModel.getLineStyle();
  41820. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  41821. each(splitAreas, function (splitAreas, idx) {
  41822. this.group.add(mergePath$1(splitAreas, {
  41823. style: defaults({
  41824. stroke: 'none',
  41825. fill: splitAreaColorsArr[idx % splitAreaColorsArr.length]
  41826. }, areaStyle),
  41827. silent: true
  41828. }));
  41829. }, this);
  41830. each(splitLines, function (splitLines, idx) {
  41831. this.group.add(mergePath$1(splitLines, {
  41832. style: defaults({
  41833. fill: 'none',
  41834. stroke: splitLineColorsArr[idx % splitLineColorsArr.length]
  41835. }, lineStyle),
  41836. silent: true
  41837. }));
  41838. }, this);
  41839. };
  41840. RadarView.type = 'radar';
  41841. return RadarView;
  41842. }(ComponentView);
  41843. var IndicatorAxis =
  41844. /** @class */
  41845. function (_super) {
  41846. __extends(IndicatorAxis, _super);
  41847. function IndicatorAxis(dim, scale, radiusExtent) {
  41848. var _this = _super.call(this, dim, scale, radiusExtent) || this;
  41849. _this.type = 'value';
  41850. _this.angle = 0;
  41851. _this.name = '';
  41852. return _this;
  41853. }
  41854. return IndicatorAxis;
  41855. }(Axis);
  41856. var Radar =
  41857. /** @class */
  41858. function () {
  41859. function Radar(radarModel, ecModel, api) {
  41860. /**
  41861. *
  41862. * Radar dimensions
  41863. */
  41864. this.dimensions = [];
  41865. this._model = radarModel;
  41866. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  41867. var dim = 'indicator_' + idx;
  41868. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale() // (indicatorModel.get('axisType') === 'log') ? new LogScale() : new IntervalScale()
  41869. );
  41870. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  41871. indicatorAxis.model = indicatorModel;
  41872. indicatorModel.axis = indicatorAxis;
  41873. this.dimensions.push(dim);
  41874. return indicatorAxis;
  41875. }, this);
  41876. this.resize(radarModel, api);
  41877. }
  41878. Radar.prototype.getIndicatorAxes = function () {
  41879. return this._indicatorAxes;
  41880. };
  41881. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  41882. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  41883. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  41884. }; // TODO: API should be coordToPoint([coord, indicatorIndex])
  41885. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  41886. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  41887. var angle = indicatorAxis.angle;
  41888. var x = this.cx + coord * Math.cos(angle);
  41889. var y = this.cy - coord * Math.sin(angle);
  41890. return [x, y];
  41891. };
  41892. Radar.prototype.pointToData = function (pt) {
  41893. var dx = pt[0] - this.cx;
  41894. var dy = pt[1] - this.cy;
  41895. var radius = Math.sqrt(dx * dx + dy * dy);
  41896. dx /= radius;
  41897. dy /= radius;
  41898. var radian = Math.atan2(-dy, dx); // Find the closest angle
  41899. // FIXME index can calculated directly
  41900. var minRadianDiff = Infinity;
  41901. var closestAxis;
  41902. var closestAxisIdx = -1;
  41903. for (var i = 0; i < this._indicatorAxes.length; i++) {
  41904. var indicatorAxis = this._indicatorAxes[i];
  41905. var diff = Math.abs(radian - indicatorAxis.angle);
  41906. if (diff < minRadianDiff) {
  41907. closestAxis = indicatorAxis;
  41908. closestAxisIdx = i;
  41909. minRadianDiff = diff;
  41910. }
  41911. }
  41912. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  41913. };
  41914. Radar.prototype.resize = function (radarModel, api) {
  41915. var center = radarModel.get('center');
  41916. var viewWidth = api.getWidth();
  41917. var viewHeight = api.getHeight();
  41918. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  41919. this.cx = parsePercent$1(center[0], viewWidth);
  41920. this.cy = parsePercent$1(center[1], viewHeight);
  41921. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  41922. var radius = radarModel.get('radius');
  41923. if (typeof radius === 'string' || typeof radius === 'number') {
  41924. radius = [0, radius];
  41925. }
  41926. this.r0 = parsePercent$1(radius[0], viewSize);
  41927. this.r = parsePercent$1(radius[1], viewSize);
  41928. each(this._indicatorAxes, function (indicatorAxis, idx) {
  41929. indicatorAxis.setExtent(this.r0, this.r);
  41930. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  41931. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  41932. indicatorAxis.angle = angle;
  41933. }, this);
  41934. };
  41935. Radar.prototype.update = function (ecModel, api) {
  41936. var indicatorAxes = this._indicatorAxes;
  41937. var radarModel = this._model;
  41938. each(indicatorAxes, function (indicatorAxis) {
  41939. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  41940. });
  41941. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  41942. if (radarSeries.get('coordinateSystem') !== 'radar' // @ts-ignore
  41943. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  41944. return;
  41945. }
  41946. var data = radarSeries.getData();
  41947. each(indicatorAxes, function (indicatorAxis) {
  41948. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  41949. });
  41950. }, this);
  41951. var splitNumber = radarModel.get('splitNumber');
  41952. function increaseInterval(interval) {
  41953. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10)); // Increase interval
  41954. var f = interval / exp10;
  41955. if (f === 2) {
  41956. f = 5;
  41957. } else {
  41958. // f is 2 or 5
  41959. f *= 2;
  41960. }
  41961. return f * exp10;
  41962. } // Force all the axis fixing the maxSplitNumber.
  41963. each(indicatorAxes, function (indicatorAxis, idx) {
  41964. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model).extent;
  41965. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  41966. var axisModel = indicatorAxis.model;
  41967. var scale = indicatorAxis.scale;
  41968. var fixedMin = parseAxisModelMinMax(scale, axisModel.get('min', true));
  41969. var fixedMax = parseAxisModelMinMax(scale, axisModel.get('max', true));
  41970. var interval = scale.getInterval();
  41971. if (fixedMin != null && fixedMax != null) {
  41972. // User set min, max, divide to get new interval
  41973. scale.setExtent(+fixedMin, +fixedMax);
  41974. scale.setInterval((fixedMax - fixedMin) / splitNumber);
  41975. } else if (fixedMin != null) {
  41976. var max = void 0; // User set min, expand extent on the other side
  41977. do {
  41978. max = fixedMin + interval * splitNumber;
  41979. scale.setExtent(+fixedMin, max); // Interval must been set after extent
  41980. // FIXME
  41981. scale.setInterval(interval);
  41982. interval = increaseInterval(interval);
  41983. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  41984. } else if (fixedMax != null) {
  41985. var min = void 0; // User set min, expand extent on the other side
  41986. do {
  41987. min = fixedMax - interval * splitNumber;
  41988. scale.setExtent(min, +fixedMax);
  41989. scale.setInterval(interval);
  41990. interval = increaseInterval(interval);
  41991. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  41992. } else {
  41993. var nicedSplitNumber = scale.getTicks().length - 1;
  41994. if (nicedSplitNumber > splitNumber) {
  41995. interval = increaseInterval(interval);
  41996. } // TODO
  41997. var max = Math.ceil(rawExtent[1] / interval) * interval;
  41998. var min = round(max - interval * splitNumber);
  41999. scale.setExtent(min, max);
  42000. scale.setInterval(interval);
  42001. }
  42002. });
  42003. };
  42004. Radar.prototype.convertToPixel = function (ecModel, finder, value) {
  42005. console.warn('Not implemented.');
  42006. return null;
  42007. };
  42008. Radar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  42009. console.warn('Not implemented.');
  42010. return null;
  42011. };
  42012. Radar.prototype.containPoint = function (point) {
  42013. console.warn('Not implemented.');
  42014. return false;
  42015. };
  42016. Radar.create = function (ecModel, api) {
  42017. var radarList = [];
  42018. ecModel.eachComponent('radar', function (radarModel) {
  42019. var radar = new Radar(radarModel, ecModel, api);
  42020. radarList.push(radar);
  42021. radarModel.coordinateSystem = radar;
  42022. });
  42023. ecModel.eachSeriesByType('radar', function (radarSeries) {
  42024. if (radarSeries.get('coordinateSystem') === 'radar') {
  42025. // Inject coordinate system
  42026. // @ts-ignore
  42027. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  42028. }
  42029. });
  42030. return radarList;
  42031. };
  42032. /**
  42033. * Radar dimensions is based on the data
  42034. */
  42035. Radar.dimensions = [];
  42036. return Radar;
  42037. }();
  42038. function install$7(registers) {
  42039. registers.registerCoordinateSystem('radar', Radar);
  42040. registers.registerComponentModel(RadarModel);
  42041. registers.registerComponentView(RadarView$1);
  42042. }
  42043. function install$8(registers) {
  42044. use(install$7);
  42045. registers.registerChartView(RadarView);
  42046. registers.registerSeriesModel(RadarSeriesModel);
  42047. registers.registerLayout(radarLayout);
  42048. registers.registerProcessor(dataFilter('radar'));
  42049. registers.registerPreprocessor(radarBackwardCompat);
  42050. }
  42051. var ATTR = '\0_ec_interaction_mutex';
  42052. function take(zr, resourceKey, userKey) {
  42053. var store = getStore(zr);
  42054. store[resourceKey] = userKey;
  42055. }
  42056. function release(zr, resourceKey, userKey) {
  42057. var store = getStore(zr);
  42058. var uKey = store[resourceKey];
  42059. if (uKey === userKey) {
  42060. store[resourceKey] = null;
  42061. }
  42062. }
  42063. function isTaken(zr, resourceKey) {
  42064. return !!getStore(zr)[resourceKey];
  42065. }
  42066. function getStore(zr) {
  42067. return zr[ATTR] || (zr[ATTR] = {});
  42068. }
  42069. /**
  42070. * payload: {
  42071. * type: 'takeGlobalCursor',
  42072. * key: 'dataZoomSelect', or 'brush', or ...,
  42073. * If no userKey, release global cursor.
  42074. * }
  42075. */
  42076. // TODO: SELF REGISTERED.
  42077. registerAction({
  42078. type: 'takeGlobalCursor',
  42079. event: 'globalCursorTaken',
  42080. update: 'update'
  42081. }, function () {});
  42082. var RoamController =
  42083. /** @class */
  42084. function (_super) {
  42085. __extends(RoamController, _super);
  42086. function RoamController(zr) {
  42087. var _this = _super.call(this) || this;
  42088. _this._zr = zr; // Avoid two roamController bind the same handler
  42089. var mousedownHandler = bind(_this._mousedownHandler, _this);
  42090. var mousemoveHandler = bind(_this._mousemoveHandler, _this);
  42091. var mouseupHandler = bind(_this._mouseupHandler, _this);
  42092. var mousewheelHandler = bind(_this._mousewheelHandler, _this);
  42093. var pinchHandler = bind(_this._pinchHandler, _this);
  42094. /**
  42095. * Notice: only enable needed types. For example, if 'zoom'
  42096. * is not needed, 'zoom' should not be enabled, otherwise
  42097. * default mousewheel behaviour (scroll page) will be disabled.
  42098. */
  42099. _this.enable = function (controlType, opt) {
  42100. // Disable previous first
  42101. this.disable();
  42102. this._opt = defaults(clone(opt) || {}, {
  42103. zoomOnMouseWheel: true,
  42104. moveOnMouseMove: true,
  42105. // By default, wheel do not trigger move.
  42106. moveOnMouseWheel: false,
  42107. preventDefaultMouseMove: true
  42108. });
  42109. if (controlType == null) {
  42110. controlType = true;
  42111. }
  42112. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  42113. zr.on('mousedown', mousedownHandler);
  42114. zr.on('mousemove', mousemoveHandler);
  42115. zr.on('mouseup', mouseupHandler);
  42116. }
  42117. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  42118. zr.on('mousewheel', mousewheelHandler);
  42119. zr.on('pinch', pinchHandler);
  42120. }
  42121. };
  42122. _this.disable = function () {
  42123. zr.off('mousedown', mousedownHandler);
  42124. zr.off('mousemove', mousemoveHandler);
  42125. zr.off('mouseup', mouseupHandler);
  42126. zr.off('mousewheel', mousewheelHandler);
  42127. zr.off('pinch', pinchHandler);
  42128. };
  42129. return _this;
  42130. }
  42131. RoamController.prototype.isDragging = function () {
  42132. return this._dragging;
  42133. };
  42134. RoamController.prototype.isPinching = function () {
  42135. return this._pinching;
  42136. };
  42137. RoamController.prototype.setPointerChecker = function (pointerChecker) {
  42138. this.pointerChecker = pointerChecker;
  42139. };
  42140. RoamController.prototype.dispose = function () {
  42141. this.disable();
  42142. };
  42143. RoamController.prototype._mousedownHandler = function (e) {
  42144. if (isMiddleOrRightButtonOnMouseUpDown(e) || e.target && e.target.draggable) {
  42145. return;
  42146. }
  42147. var x = e.offsetX;
  42148. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  42149. // Mouse can be out of target when mouse moving.
  42150. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  42151. this._x = x;
  42152. this._y = y;
  42153. this._dragging = true;
  42154. }
  42155. };
  42156. RoamController.prototype._mousemoveHandler = function (e) {
  42157. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  42158. return;
  42159. }
  42160. var x = e.offsetX;
  42161. var y = e.offsetY;
  42162. var oldX = this._x;
  42163. var oldY = this._y;
  42164. var dx = x - oldX;
  42165. var dy = y - oldY;
  42166. this._x = x;
  42167. this._y = y;
  42168. this._opt.preventDefaultMouseMove && stop(e.event);
  42169. trigger(this, 'pan', 'moveOnMouseMove', e, {
  42170. dx: dx,
  42171. dy: dy,
  42172. oldX: oldX,
  42173. oldY: oldY,
  42174. newX: x,
  42175. newY: y,
  42176. isAvailableBehavior: null
  42177. });
  42178. };
  42179. RoamController.prototype._mouseupHandler = function (e) {
  42180. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  42181. this._dragging = false;
  42182. }
  42183. };
  42184. RoamController.prototype._mousewheelHandler = function (e) {
  42185. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  42186. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  42187. var wheelDelta = e.wheelDelta;
  42188. var absWheelDeltaDelta = Math.abs(wheelDelta);
  42189. var originX = e.offsetX;
  42190. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  42191. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  42192. return;
  42193. } // If both `shouldZoom` and `shouldMove` is true, trigger
  42194. // their event both, and the final behavior is determined
  42195. // by event listener themselves.
  42196. if (shouldZoom) {
  42197. // Convenience:
  42198. // Mac and VM Windows on Mac: scroll up: zoom out.
  42199. // Windows: scroll up: zoom in.
  42200. // FIXME: Should do more test in different environment.
  42201. // wheelDelta is too complicated in difference nvironment
  42202. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  42203. // although it has been normallized by zrender.
  42204. // wheelDelta of mouse wheel is bigger than touch pad.
  42205. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  42206. var scale = wheelDelta > 0 ? factor : 1 / factor;
  42207. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  42208. scale: scale,
  42209. originX: originX,
  42210. originY: originY,
  42211. isAvailableBehavior: null
  42212. });
  42213. }
  42214. if (shouldMove) {
  42215. // FIXME: Should do more test in different environment.
  42216. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  42217. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  42218. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  42219. scrollDelta: scrollDelta,
  42220. originX: originX,
  42221. originY: originY,
  42222. isAvailableBehavior: null
  42223. });
  42224. }
  42225. };
  42226. RoamController.prototype._pinchHandler = function (e) {
  42227. if (isTaken(this._zr, 'globalPan')) {
  42228. return;
  42229. }
  42230. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  42231. checkPointerAndTrigger(this, 'zoom', null, e, {
  42232. scale: scale,
  42233. originX: e.pinchX,
  42234. originY: e.pinchY,
  42235. isAvailableBehavior: null
  42236. });
  42237. };
  42238. return RoamController;
  42239. }(Eventful);
  42240. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  42241. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  42242. // When mouse is out of roamController rect,
  42243. // default befavoius should not be be disabled, otherwise
  42244. // page sliding is disabled, contrary to expectation.
  42245. stop(e.event);
  42246. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  42247. }
  42248. }
  42249. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  42250. // Also provide behavior checker for event listener, for some case that
  42251. // multiple components share one listener.
  42252. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  42253. controller.trigger(eventName, contollerEvent);
  42254. } // settings: {
  42255. // zoomOnMouseWheel
  42256. // moveOnMouseMove
  42257. // moveOnMouseWheel
  42258. // }
  42259. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  42260. function isAvailableBehavior(behaviorToCheck, e, settings) {
  42261. var setting = settings[behaviorToCheck];
  42262. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  42263. }
  42264. /*
  42265. * Licensed to the Apache Software Foundation (ASF) under one
  42266. * or more contributor license agreements. See the NOTICE file
  42267. * distributed with this work for additional information
  42268. * regarding copyright ownership. The ASF licenses this file
  42269. * to you under the Apache License, Version 2.0 (the
  42270. * "License"); you may not use this file except in compliance
  42271. * with the License. You may obtain a copy of the License at
  42272. *
  42273. * http://www.apache.org/licenses/LICENSE-2.0
  42274. *
  42275. * Unless required by applicable law or agreed to in writing,
  42276. * software distributed under the License is distributed on an
  42277. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42278. * KIND, either express or implied. See the License for the
  42279. * specific language governing permissions and limitations
  42280. * under the License.
  42281. */
  42282. /**
  42283. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42284. */
  42285. /*
  42286. * Licensed to the Apache Software Foundation (ASF) under one
  42287. * or more contributor license agreements. See the NOTICE file
  42288. * distributed with this work for additional information
  42289. * regarding copyright ownership. The ASF licenses this file
  42290. * to you under the Apache License, Version 2.0 (the
  42291. * "License"); you may not use this file except in compliance
  42292. * with the License. You may obtain a copy of the License at
  42293. *
  42294. * http://www.apache.org/licenses/LICENSE-2.0
  42295. *
  42296. * Unless required by applicable law or agreed to in writing,
  42297. * software distributed under the License is distributed on an
  42298. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42299. * KIND, either express or implied. See the License for the
  42300. * specific language governing permissions and limitations
  42301. * under the License.
  42302. */
  42303. /**
  42304. * For geo and graph.
  42305. */
  42306. function updateViewOnPan(controllerHost, dx, dy) {
  42307. var target = controllerHost.target;
  42308. target.x += dx;
  42309. target.y += dy;
  42310. target.dirty();
  42311. }
  42312. /**
  42313. * For geo and graph.
  42314. */
  42315. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  42316. var target = controllerHost.target;
  42317. var zoomLimit = controllerHost.zoomLimit;
  42318. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  42319. newZoom *= zoomDelta;
  42320. if (zoomLimit) {
  42321. var zoomMin = zoomLimit.min || 0;
  42322. var zoomMax = zoomLimit.max || Infinity;
  42323. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  42324. }
  42325. var zoomScale = newZoom / controllerHost.zoom;
  42326. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  42327. target.x -= (zoomX - target.x) * (zoomScale - 1);
  42328. target.y -= (zoomY - target.y) * (zoomScale - 1);
  42329. target.scaleX *= zoomScale;
  42330. target.scaleY *= zoomScale;
  42331. target.dirty();
  42332. }
  42333. /*
  42334. * Licensed to the Apache Software Foundation (ASF) under one
  42335. * or more contributor license agreements. See the NOTICE file
  42336. * distributed with this work for additional information
  42337. * regarding copyright ownership. The ASF licenses this file
  42338. * to you under the Apache License, Version 2.0 (the
  42339. * "License"); you may not use this file except in compliance
  42340. * with the License. You may obtain a copy of the License at
  42341. *
  42342. * http://www.apache.org/licenses/LICENSE-2.0
  42343. *
  42344. * Unless required by applicable law or agreed to in writing,
  42345. * software distributed under the License is distributed on an
  42346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42347. * KIND, either express or implied. See the License for the
  42348. * specific language governing permissions and limitations
  42349. * under the License.
  42350. */
  42351. /**
  42352. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42353. */
  42354. /*
  42355. * Licensed to the Apache Software Foundation (ASF) under one
  42356. * or more contributor license agreements. See the NOTICE file
  42357. * distributed with this work for additional information
  42358. * regarding copyright ownership. The ASF licenses this file
  42359. * to you under the Apache License, Version 2.0 (the
  42360. * "License"); you may not use this file except in compliance
  42361. * with the License. You may obtain a copy of the License at
  42362. *
  42363. * http://www.apache.org/licenses/LICENSE-2.0
  42364. *
  42365. * Unless required by applicable law or agreed to in writing,
  42366. * software distributed under the License is distributed on an
  42367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42368. * KIND, either express or implied. See the License for the
  42369. * specific language governing permissions and limitations
  42370. * under the License.
  42371. */
  42372. var IRRELEVANT_EXCLUDES = {
  42373. 'axisPointer': 1,
  42374. 'tooltip': 1,
  42375. 'brush': 1
  42376. };
  42377. /**
  42378. * Avoid that: mouse click on a elements that is over geo or graph,
  42379. * but roam is triggered.
  42380. */
  42381. function onIrrelevantElement(e, api, targetCoordSysModel) {
  42382. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  42383. var coordSys = model && model.coordinateSystem;
  42384. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES.hasOwnProperty(model.mainType) && coordSys && coordSys.model !== targetCoordSysModel;
  42385. }
  42386. var geoCoord = [126, 25];
  42387. 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]]];
  42388. for (var i = 0; i < points$1.length; i++) {
  42389. for (var k = 0; k < points$1[i].length; k++) {
  42390. points$1[i][k][0] /= 10.5;
  42391. points$1[i][k][1] /= -10.5 / 0.75;
  42392. points$1[i][k][0] += geoCoord[0];
  42393. points$1[i][k][1] += geoCoord[1];
  42394. }
  42395. }
  42396. function fixNanhai(mapType, regions) {
  42397. if (mapType === 'china') {
  42398. regions.push(new Region('南海诸岛', map(points$1, function (exterior) {
  42399. return {
  42400. type: 'polygon',
  42401. exterior: exterior
  42402. };
  42403. }), geoCoord));
  42404. }
  42405. }
  42406. /*
  42407. * Licensed to the Apache Software Foundation (ASF) under one
  42408. * or more contributor license agreements. See the NOTICE file
  42409. * distributed with this work for additional information
  42410. * regarding copyright ownership. The ASF licenses this file
  42411. * to you under the Apache License, Version 2.0 (the
  42412. * "License"); you may not use this file except in compliance
  42413. * with the License. You may obtain a copy of the License at
  42414. *
  42415. * http://www.apache.org/licenses/LICENSE-2.0
  42416. *
  42417. * Unless required by applicable law or agreed to in writing,
  42418. * software distributed under the License is distributed on an
  42419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42420. * KIND, either express or implied. See the License for the
  42421. * specific language governing permissions and limitations
  42422. * under the License.
  42423. */
  42424. /**
  42425. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42426. */
  42427. /*
  42428. * Licensed to the Apache Software Foundation (ASF) under one
  42429. * or more contributor license agreements. See the NOTICE file
  42430. * distributed with this work for additional information
  42431. * regarding copyright ownership. The ASF licenses this file
  42432. * to you under the Apache License, Version 2.0 (the
  42433. * "License"); you may not use this file except in compliance
  42434. * with the License. You may obtain a copy of the License at
  42435. *
  42436. * http://www.apache.org/licenses/LICENSE-2.0
  42437. *
  42438. * Unless required by applicable law or agreed to in writing,
  42439. * software distributed under the License is distributed on an
  42440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42441. * KIND, either express or implied. See the License for the
  42442. * specific language governing permissions and limitations
  42443. * under the License.
  42444. */
  42445. var coordsOffsetMap = {
  42446. '南海诸岛': [32, 80],
  42447. // 全国
  42448. '广东': [0, -10],
  42449. '香港': [10, 5],
  42450. '澳门': [-10, 10],
  42451. //'北京': [-10, 0],
  42452. '天津': [5, 5]
  42453. };
  42454. function fixTextCoords(mapType, region) {
  42455. if (mapType === 'china') {
  42456. var coordFix = coordsOffsetMap[region.name];
  42457. if (coordFix) {
  42458. var cp = region.center;
  42459. cp[0] += coordFix[0] / 10.5;
  42460. cp[1] += -coordFix[1] / (10.5 / 0.75);
  42461. }
  42462. }
  42463. }
  42464. /*
  42465. * Licensed to the Apache Software Foundation (ASF) under one
  42466. * or more contributor license agreements. See the NOTICE file
  42467. * distributed with this work for additional information
  42468. * regarding copyright ownership. The ASF licenses this file
  42469. * to you under the Apache License, Version 2.0 (the
  42470. * "License"); you may not use this file except in compliance
  42471. * with the License. You may obtain a copy of the License at
  42472. *
  42473. * http://www.apache.org/licenses/LICENSE-2.0
  42474. *
  42475. * Unless required by applicable law or agreed to in writing,
  42476. * software distributed under the License is distributed on an
  42477. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42478. * KIND, either express or implied. See the License for the
  42479. * specific language governing permissions and limitations
  42480. * under the License.
  42481. */
  42482. /**
  42483. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42484. */
  42485. /*
  42486. * Licensed to the Apache Software Foundation (ASF) under one
  42487. * or more contributor license agreements. See the NOTICE file
  42488. * distributed with this work for additional information
  42489. * regarding copyright ownership. The ASF licenses this file
  42490. * to you under the Apache License, Version 2.0 (the
  42491. * "License"); you may not use this file except in compliance
  42492. * with the License. You may obtain a copy of the License at
  42493. *
  42494. * http://www.apache.org/licenses/LICENSE-2.0
  42495. *
  42496. * Unless required by applicable law or agreed to in writing,
  42497. * software distributed under the License is distributed on an
  42498. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42499. * KIND, either express or implied. See the License for the
  42500. * specific language governing permissions and limitations
  42501. * under the License.
  42502. */
  42503. var geoCoordMap = {
  42504. 'Russia': [100, 60],
  42505. 'United States': [-99, 38],
  42506. 'United States of America': [-99, 38]
  42507. };
  42508. function fixGeoCoords(mapType, region) {
  42509. if (mapType === 'world') {
  42510. var geoCoord = geoCoordMap[region.name];
  42511. if (geoCoord) {
  42512. var cp = region.center;
  42513. cp[0] = geoCoord[0];
  42514. cp[1] = geoCoord[1];
  42515. }
  42516. }
  42517. }
  42518. /*
  42519. * Licensed to the Apache Software Foundation (ASF) under one
  42520. * or more contributor license agreements. See the NOTICE file
  42521. * distributed with this work for additional information
  42522. * regarding copyright ownership. The ASF licenses this file
  42523. * to you under the Apache License, Version 2.0 (the
  42524. * "License"); you may not use this file except in compliance
  42525. * with the License. You may obtain a copy of the License at
  42526. *
  42527. * http://www.apache.org/licenses/LICENSE-2.0
  42528. *
  42529. * Unless required by applicable law or agreed to in writing,
  42530. * software distributed under the License is distributed on an
  42531. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42532. * KIND, either express or implied. See the License for the
  42533. * specific language governing permissions and limitations
  42534. * under the License.
  42535. */
  42536. /**
  42537. * AUTO-GENERATED FILE. DO NOT MODIFY.
  42538. */
  42539. /*
  42540. * Licensed to the Apache Software Foundation (ASF) under one
  42541. * or more contributor license agreements. See the NOTICE file
  42542. * distributed with this work for additional information
  42543. * regarding copyright ownership. The ASF licenses this file
  42544. * to you under the Apache License, Version 2.0 (the
  42545. * "License"); you may not use this file except in compliance
  42546. * with the License. You may obtain a copy of the License at
  42547. *
  42548. * http://www.apache.org/licenses/LICENSE-2.0
  42549. *
  42550. * Unless required by applicable law or agreed to in writing,
  42551. * software distributed under the License is distributed on an
  42552. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42553. * KIND, either express or implied. See the License for the
  42554. * specific language governing permissions and limitations
  42555. * under the License.
  42556. */
  42557. // Fix for 钓鱼岛
  42558. // let Region = require('../Region');
  42559. // let zrUtil = require('zrender/lib/core/util');
  42560. // let geoCoord = [126, 25];
  42561. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  42562. function fixDiaoyuIsland(mapType, region) {
  42563. if (mapType === 'china' && region.name === '台湾') {
  42564. region.geometries.push({
  42565. type: 'polygon',
  42566. exterior: points$2[0]
  42567. });
  42568. }
  42569. }
  42570. var inner$6 = makeInner();
  42571. var geoJSONLoader = {
  42572. load: function (mapName, mapRecord, nameProperty) {
  42573. var parsed = inner$6(mapRecord).parsed;
  42574. if (parsed) {
  42575. return parsed;
  42576. }
  42577. var specialAreas = mapRecord.specialAreas || {};
  42578. var geoJSON = mapRecord.geoJSON;
  42579. var regions; // https://jsperf.com/try-catch-performance-overhead
  42580. try {
  42581. regions = geoJSON ? parseGeoJSON(geoJSON, nameProperty) : [];
  42582. } catch (e) {
  42583. throw new Error('Invalid geoJson format\n' + e.message);
  42584. }
  42585. fixNanhai(mapName, regions);
  42586. each(regions, function (region) {
  42587. var regionName = region.name;
  42588. fixTextCoords(mapName, region);
  42589. fixGeoCoords(mapName, region);
  42590. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  42591. // to look better
  42592. var specialArea = specialAreas[regionName];
  42593. if (specialArea) {
  42594. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  42595. }
  42596. });
  42597. return inner$6(mapRecord).parsed = {
  42598. regions: regions,
  42599. boundingRect: getBoundingRect$1(regions)
  42600. };
  42601. }
  42602. };
  42603. function getBoundingRect$1(regions) {
  42604. var rect;
  42605. for (var i = 0; i < regions.length; i++) {
  42606. var regionRect = regions[i].getBoundingRect();
  42607. rect = rect || regionRect.clone();
  42608. rect.union(regionRect);
  42609. }
  42610. return rect;
  42611. }
  42612. var DILIMITER_REG = /[\s,]+/;
  42613. var nodeParsers;
  42614. var SVGParser = (function () {
  42615. function SVGParser() {
  42616. this._defs = {};
  42617. this._root = null;
  42618. this._isDefine = false;
  42619. this._isText = false;
  42620. }
  42621. SVGParser.prototype.parse = function (xml, opt) {
  42622. opt = opt || {};
  42623. var svg = parseXML(xml);
  42624. if (!svg) {
  42625. throw new Error('Illegal svg');
  42626. }
  42627. var root = new Group();
  42628. this._root = root;
  42629. var viewBox = svg.getAttribute('viewBox') || '';
  42630. var width = parseFloat((svg.getAttribute('width') || opt.width));
  42631. var height = parseFloat((svg.getAttribute('height') || opt.height));
  42632. isNaN(width) && (width = null);
  42633. isNaN(height) && (height = null);
  42634. parseAttributes(svg, root, null, true);
  42635. var child = svg.firstChild;
  42636. while (child) {
  42637. this._parseNode(child, root);
  42638. child = child.nextSibling;
  42639. }
  42640. var viewBoxRect;
  42641. var viewBoxTransform;
  42642. if (viewBox) {
  42643. var viewBoxArr = trim(viewBox).split(DILIMITER_REG);
  42644. if (viewBoxArr.length >= 4) {
  42645. viewBoxRect = {
  42646. x: parseFloat((viewBoxArr[0] || 0)),
  42647. y: parseFloat((viewBoxArr[1] || 0)),
  42648. width: parseFloat(viewBoxArr[2]),
  42649. height: parseFloat(viewBoxArr[3])
  42650. };
  42651. }
  42652. }
  42653. if (viewBoxRect && width != null && height != null) {
  42654. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  42655. if (!opt.ignoreViewBox) {
  42656. var elRoot = root;
  42657. root = new Group();
  42658. root.add(elRoot);
  42659. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  42660. elRoot.x = viewBoxTransform.x;
  42661. elRoot.y = viewBoxTransform.y;
  42662. }
  42663. }
  42664. if (!opt.ignoreRootClip && width != null && height != null) {
  42665. root.setClipPath(new Rect({
  42666. shape: { x: 0, y: 0, width: width, height: height }
  42667. }));
  42668. }
  42669. return {
  42670. root: root,
  42671. width: width,
  42672. height: height,
  42673. viewBoxRect: viewBoxRect,
  42674. viewBoxTransform: viewBoxTransform
  42675. };
  42676. };
  42677. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  42678. var nodeName = xmlNode.nodeName.toLowerCase();
  42679. if (nodeName === 'defs') {
  42680. this._isDefine = true;
  42681. }
  42682. else if (nodeName === 'text') {
  42683. this._isText = true;
  42684. }
  42685. var el;
  42686. if (this._isDefine) {
  42687. var parser = defineParsers[nodeName];
  42688. if (parser) {
  42689. var def = parser.call(this, xmlNode);
  42690. var id = xmlNode.getAttribute('id');
  42691. if (id) {
  42692. this._defs[id] = def;
  42693. }
  42694. }
  42695. }
  42696. else {
  42697. var parser = nodeParsers[nodeName];
  42698. if (parser) {
  42699. el = parser.call(this, xmlNode, parentGroup);
  42700. parentGroup.add(el);
  42701. }
  42702. }
  42703. if (el) {
  42704. var child = xmlNode.firstChild;
  42705. while (child) {
  42706. if (child.nodeType === 1) {
  42707. this._parseNode(child, el);
  42708. }
  42709. if (child.nodeType === 3 && this._isText) {
  42710. this._parseText(child, el);
  42711. }
  42712. child = child.nextSibling;
  42713. }
  42714. }
  42715. if (nodeName === 'defs') {
  42716. this._isDefine = false;
  42717. }
  42718. else if (nodeName === 'text') {
  42719. this._isText = false;
  42720. }
  42721. };
  42722. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  42723. if (xmlNode.nodeType === 1) {
  42724. var dx = xmlNode.getAttribute('dx') || 0;
  42725. var dy = xmlNode.getAttribute('dy') || 0;
  42726. this._textX += parseFloat(dx);
  42727. this._textY += parseFloat(dy);
  42728. }
  42729. var text = new TSpan({
  42730. style: {
  42731. text: xmlNode.textContent
  42732. },
  42733. x: this._textX || 0,
  42734. y: this._textY || 0
  42735. });
  42736. inheritStyle(parentGroup, text);
  42737. parseAttributes(xmlNode, text, this._defs);
  42738. var textStyle = text.style;
  42739. var fontSize = textStyle.fontSize;
  42740. if (fontSize && fontSize < 9) {
  42741. textStyle.fontSize = 9;
  42742. text.scaleX *= fontSize / 9;
  42743. text.scaleY *= fontSize / 9;
  42744. }
  42745. var font = (textStyle.fontSize || textStyle.fontFamily) && [
  42746. textStyle.fontStyle,
  42747. textStyle.fontWeight,
  42748. (textStyle.fontSize || 12) + 'px',
  42749. textStyle.fontFamily || 'sans-serif'
  42750. ].join(' ');
  42751. textStyle.font = font;
  42752. var rect = text.getBoundingRect();
  42753. this._textX += rect.width;
  42754. parentGroup.add(text);
  42755. return text;
  42756. };
  42757. SVGParser.internalField = (function () {
  42758. nodeParsers = {
  42759. 'g': function (xmlNode, parentGroup) {
  42760. var g = new Group();
  42761. inheritStyle(parentGroup, g);
  42762. parseAttributes(xmlNode, g, this._defs);
  42763. return g;
  42764. },
  42765. 'rect': function (xmlNode, parentGroup) {
  42766. var rect = new Rect();
  42767. inheritStyle(parentGroup, rect);
  42768. parseAttributes(xmlNode, rect, this._defs);
  42769. rect.setShape({
  42770. x: parseFloat(xmlNode.getAttribute('x') || '0'),
  42771. y: parseFloat(xmlNode.getAttribute('y') || '0'),
  42772. width: parseFloat(xmlNode.getAttribute('width') || '0'),
  42773. height: parseFloat(xmlNode.getAttribute('height') || '0')
  42774. });
  42775. return rect;
  42776. },
  42777. 'circle': function (xmlNode, parentGroup) {
  42778. var circle = new Circle();
  42779. inheritStyle(parentGroup, circle);
  42780. parseAttributes(xmlNode, circle, this._defs);
  42781. circle.setShape({
  42782. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  42783. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  42784. r: parseFloat(xmlNode.getAttribute('r') || '0')
  42785. });
  42786. return circle;
  42787. },
  42788. 'line': function (xmlNode, parentGroup) {
  42789. var line = new Line();
  42790. inheritStyle(parentGroup, line);
  42791. parseAttributes(xmlNode, line, this._defs);
  42792. line.setShape({
  42793. x1: parseFloat(xmlNode.getAttribute('x1') || '0'),
  42794. y1: parseFloat(xmlNode.getAttribute('y1') || '0'),
  42795. x2: parseFloat(xmlNode.getAttribute('x2') || '0'),
  42796. y2: parseFloat(xmlNode.getAttribute('y2') || '0')
  42797. });
  42798. return line;
  42799. },
  42800. 'ellipse': function (xmlNode, parentGroup) {
  42801. var ellipse = new Ellipse();
  42802. inheritStyle(parentGroup, ellipse);
  42803. parseAttributes(xmlNode, ellipse, this._defs);
  42804. ellipse.setShape({
  42805. cx: parseFloat(xmlNode.getAttribute('cx') || '0'),
  42806. cy: parseFloat(xmlNode.getAttribute('cy') || '0'),
  42807. rx: parseFloat(xmlNode.getAttribute('rx') || '0'),
  42808. ry: parseFloat(xmlNode.getAttribute('ry') || '0')
  42809. });
  42810. return ellipse;
  42811. },
  42812. 'polygon': function (xmlNode, parentGroup) {
  42813. var pointsStr = xmlNode.getAttribute('points');
  42814. var pointsArr;
  42815. if (pointsStr) {
  42816. pointsArr = parsePoints(pointsStr);
  42817. }
  42818. var polygon = new Polygon({
  42819. shape: {
  42820. points: pointsArr || []
  42821. }
  42822. });
  42823. inheritStyle(parentGroup, polygon);
  42824. parseAttributes(xmlNode, polygon, this._defs);
  42825. return polygon;
  42826. },
  42827. 'polyline': function (xmlNode, parentGroup) {
  42828. var path = new Path();
  42829. inheritStyle(parentGroup, path);
  42830. parseAttributes(xmlNode, path, this._defs);
  42831. var pointsStr = xmlNode.getAttribute('points');
  42832. var pointsArr;
  42833. if (pointsStr) {
  42834. pointsArr = parsePoints(pointsStr);
  42835. }
  42836. var polyline = new Polyline({
  42837. shape: {
  42838. points: pointsArr || []
  42839. }
  42840. });
  42841. return polyline;
  42842. },
  42843. 'image': function (xmlNode, parentGroup) {
  42844. var img = new ZRImage();
  42845. inheritStyle(parentGroup, img);
  42846. parseAttributes(xmlNode, img, this._defs);
  42847. img.setStyle({
  42848. image: xmlNode.getAttribute('xlink:href'),
  42849. x: +xmlNode.getAttribute('x'),
  42850. y: +xmlNode.getAttribute('y'),
  42851. width: +xmlNode.getAttribute('width'),
  42852. height: +xmlNode.getAttribute('height')
  42853. });
  42854. return img;
  42855. },
  42856. 'text': function (xmlNode, parentGroup) {
  42857. var x = xmlNode.getAttribute('x') || '0';
  42858. var y = xmlNode.getAttribute('y') || '0';
  42859. var dx = xmlNode.getAttribute('dx') || '0';
  42860. var dy = xmlNode.getAttribute('dy') || '0';
  42861. this._textX = parseFloat(x) + parseFloat(dx);
  42862. this._textY = parseFloat(y) + parseFloat(dy);
  42863. var g = new Group();
  42864. inheritStyle(parentGroup, g);
  42865. parseAttributes(xmlNode, g, this._defs);
  42866. return g;
  42867. },
  42868. 'tspan': function (xmlNode, parentGroup) {
  42869. var x = xmlNode.getAttribute('x');
  42870. var y = xmlNode.getAttribute('y');
  42871. if (x != null) {
  42872. this._textX = parseFloat(x);
  42873. }
  42874. if (y != null) {
  42875. this._textY = parseFloat(y);
  42876. }
  42877. var dx = xmlNode.getAttribute('dx') || 0;
  42878. var dy = xmlNode.getAttribute('dy') || 0;
  42879. var g = new Group();
  42880. inheritStyle(parentGroup, g);
  42881. parseAttributes(xmlNode, g, this._defs);
  42882. this._textX += dx;
  42883. this._textY += dy;
  42884. return g;
  42885. },
  42886. 'path': function (xmlNode, parentGroup) {
  42887. var d = xmlNode.getAttribute('d') || '';
  42888. var path = createFromString(d);
  42889. inheritStyle(parentGroup, path);
  42890. parseAttributes(xmlNode, path, this._defs);
  42891. return path;
  42892. }
  42893. };
  42894. })();
  42895. return SVGParser;
  42896. }());
  42897. var defineParsers = {
  42898. 'lineargradient': function (xmlNode) {
  42899. var x1 = parseInt(xmlNode.getAttribute('x1') || '0', 10);
  42900. var y1 = parseInt(xmlNode.getAttribute('y1') || '0', 10);
  42901. var x2 = parseInt(xmlNode.getAttribute('x2') || '10', 10);
  42902. var y2 = parseInt(xmlNode.getAttribute('y2') || '0', 10);
  42903. var gradient = new LinearGradient(x1, y1, x2, y2);
  42904. _parseGradientColorStops(xmlNode, gradient);
  42905. return gradient;
  42906. }
  42907. };
  42908. function _parseGradientColorStops(xmlNode, gradient) {
  42909. var stop = xmlNode.firstChild;
  42910. while (stop) {
  42911. if (stop.nodeType === 1) {
  42912. var offsetStr = stop.getAttribute('offset');
  42913. var offset = void 0;
  42914. if (offsetStr.indexOf('%') > 0) {
  42915. offset = parseInt(offsetStr, 10) / 100;
  42916. }
  42917. else if (offsetStr) {
  42918. offset = parseFloat(offsetStr);
  42919. }
  42920. else {
  42921. offset = 0;
  42922. }
  42923. var stopColor = stop.getAttribute('stop-color') || '#000000';
  42924. gradient.colorStops.push({
  42925. offset: offset,
  42926. color: stopColor
  42927. });
  42928. }
  42929. stop = stop.nextSibling;
  42930. }
  42931. }
  42932. function inheritStyle(parent, child) {
  42933. if (parent && parent.__inheritedStyle) {
  42934. if (!child.__inheritedStyle) {
  42935. child.__inheritedStyle = {};
  42936. }
  42937. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  42938. }
  42939. }
  42940. function parsePoints(pointsString) {
  42941. var list = trim(pointsString).split(DILIMITER_REG);
  42942. var points = [];
  42943. for (var i = 0; i < list.length; i += 2) {
  42944. var x = parseFloat(list[i]);
  42945. var y = parseFloat(list[i + 1]);
  42946. points.push([x, y]);
  42947. }
  42948. return points;
  42949. }
  42950. var attributesMap = {
  42951. 'fill': 'fill',
  42952. 'stroke': 'stroke',
  42953. 'stroke-width': 'lineWidth',
  42954. 'opacity': 'opacity',
  42955. 'fill-opacity': 'fillOpacity',
  42956. 'stroke-opacity': 'strokeOpacity',
  42957. 'stroke-dasharray': 'lineDash',
  42958. 'stroke-dashoffset': 'lineDashOffset',
  42959. 'stroke-linecap': 'lineCap',
  42960. 'stroke-linejoin': 'lineJoin',
  42961. 'stroke-miterlimit': 'miterLimit',
  42962. 'font-family': 'fontFamily',
  42963. 'font-size': 'fontSize',
  42964. 'font-style': 'fontStyle',
  42965. 'font-weight': 'fontWeight',
  42966. 'text-align': 'textAlign',
  42967. 'alignment-baseline': 'textBaseline'
  42968. };
  42969. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  42970. var disp = el;
  42971. var zrStyle = disp.__inheritedStyle || {};
  42972. if (xmlNode.nodeType === 1) {
  42973. parseTransformAttribute(xmlNode, el);
  42974. extend(zrStyle, parseStyleAttribute(xmlNode));
  42975. if (!onlyInlineStyle) {
  42976. for (var svgAttrName in attributesMap) {
  42977. if (attributesMap.hasOwnProperty(svgAttrName)) {
  42978. var attrValue = xmlNode.getAttribute(svgAttrName);
  42979. if (attrValue != null) {
  42980. zrStyle[attributesMap[svgAttrName]] = attrValue;
  42981. }
  42982. }
  42983. }
  42984. }
  42985. }
  42986. disp.style = disp.style || {};
  42987. zrStyle.fill != null && (disp.style.fill = getPaint(zrStyle.fill, defs));
  42988. zrStyle.stroke != null && (disp.style.stroke = getPaint(zrStyle.stroke, defs));
  42989. each([
  42990. 'lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'
  42991. ], function (propName) {
  42992. zrStyle[propName] != null && (disp.style[propName] = parseFloat(zrStyle[propName]));
  42993. });
  42994. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  42995. zrStyle.textBaseline = 'alphabetic';
  42996. }
  42997. if (zrStyle.textBaseline === 'alphabetic') {
  42998. zrStyle.textBaseline = 'bottom';
  42999. }
  43000. if (zrStyle.textAlign === 'start') {
  43001. zrStyle.textAlign = 'left';
  43002. }
  43003. if (zrStyle.textAlign === 'end') {
  43004. zrStyle.textAlign = 'right';
  43005. }
  43006. each(['lineDashOffset', 'lineCap', 'lineJoin',
  43007. 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'
  43008. ], function (propName) {
  43009. zrStyle[propName] != null && (disp.style[propName] = zrStyle[propName]);
  43010. });
  43011. if (zrStyle.lineDash) {
  43012. disp.style.lineDash = map(trim(zrStyle.lineDash).split(DILIMITER_REG), function (str) {
  43013. return parseFloat(str);
  43014. });
  43015. }
  43016. disp.__inheritedStyle = zrStyle;
  43017. }
  43018. var urlRegex = /url\(\s*#(.*?)\)/;
  43019. function getPaint(str, defs) {
  43020. var urlMatch = defs && str && str.match(urlRegex);
  43021. if (urlMatch) {
  43022. var url = trim(urlMatch[1]);
  43023. var def = defs[url];
  43024. return def;
  43025. }
  43026. return str;
  43027. }
  43028. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  43029. function parseTransformAttribute(xmlNode, node) {
  43030. var transform = xmlNode.getAttribute('transform');
  43031. if (transform) {
  43032. transform = transform.replace(/,/g, ' ');
  43033. var transformOps_1 = [];
  43034. var m = null;
  43035. transform.replace(transformRegex, function (str, type, value) {
  43036. transformOps_1.push(type, value);
  43037. return '';
  43038. });
  43039. for (var i = transformOps_1.length - 1; i > 0; i -= 2) {
  43040. var value = transformOps_1[i];
  43041. var type = transformOps_1[i - 1];
  43042. var valueArr = void 0;
  43043. m = m || create$1();
  43044. switch (type) {
  43045. case 'translate':
  43046. valueArr = trim(value).split(DILIMITER_REG);
  43047. translate(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || '0')]);
  43048. break;
  43049. case 'scale':
  43050. valueArr = trim(value).split(DILIMITER_REG);
  43051. scale$1(m, m, [parseFloat(valueArr[0]), parseFloat(valueArr[1] || valueArr[0])]);
  43052. break;
  43053. case 'rotate':
  43054. valueArr = trim(value).split(DILIMITER_REG);
  43055. rotate(m, m, parseFloat(valueArr[0]));
  43056. break;
  43057. case 'skew':
  43058. valueArr = trim(value).split(DILIMITER_REG);
  43059. console.warn('Skew transform is not supported yet');
  43060. break;
  43061. case 'matrix':
  43062. valueArr = trim(value).split(DILIMITER_REG);
  43063. m[0] = parseFloat(valueArr[0]);
  43064. m[1] = parseFloat(valueArr[1]);
  43065. m[2] = parseFloat(valueArr[2]);
  43066. m[3] = parseFloat(valueArr[3]);
  43067. m[4] = parseFloat(valueArr[4]);
  43068. m[5] = parseFloat(valueArr[5]);
  43069. break;
  43070. }
  43071. }
  43072. node.setLocalTransform(m);
  43073. }
  43074. }
  43075. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  43076. function parseStyleAttribute(xmlNode) {
  43077. var style = xmlNode.getAttribute('style');
  43078. var result = {};
  43079. if (!style) {
  43080. return result;
  43081. }
  43082. var styleList = {};
  43083. styleRegex.lastIndex = 0;
  43084. var styleRegResult;
  43085. while ((styleRegResult = styleRegex.exec(style)) != null) {
  43086. styleList[styleRegResult[1]] = styleRegResult[2];
  43087. }
  43088. for (var svgAttrName in attributesMap) {
  43089. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  43090. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  43091. }
  43092. }
  43093. return result;
  43094. }
  43095. function makeViewBoxTransform(viewBoxRect, width, height) {
  43096. var scaleX = width / viewBoxRect.width;
  43097. var scaleY = height / viewBoxRect.height;
  43098. var scale = Math.min(scaleX, scaleY);
  43099. return {
  43100. scale: scale,
  43101. x: -(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2,
  43102. y: -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2
  43103. };
  43104. }
  43105. function parseSVG(xml, opt) {
  43106. var parser = new SVGParser();
  43107. return parser.parse(xml, opt);
  43108. }
  43109. var inner$7 = makeInner();
  43110. var geoSVGLoader = {
  43111. load: function (mapName, mapRecord) {
  43112. var originRoot = inner$7(mapRecord).originRoot;
  43113. if (originRoot) {
  43114. return {
  43115. root: originRoot,
  43116. boundingRect: inner$7(mapRecord).boundingRect
  43117. };
  43118. }
  43119. var graphic = buildGraphic(mapRecord);
  43120. inner$7(mapRecord).originRoot = graphic.root;
  43121. inner$7(mapRecord).boundingRect = graphic.boundingRect;
  43122. return graphic;
  43123. },
  43124. makeGraphic: function (mapName, mapRecord, hostKey) {
  43125. // For performance consideration (in large SVG), graphic only maked
  43126. // when necessary and reuse them according to hostKey.
  43127. var field = inner$7(mapRecord);
  43128. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  43129. var root = rootMap.get(hostKey);
  43130. if (root) {
  43131. return root;
  43132. }
  43133. var originRoot = field.originRoot;
  43134. var boundingRect = field.boundingRect; // For performance, if originRoot is not used by a view,
  43135. // assign it to a view, but not reproduce graphic elements.
  43136. if (!field.originRootHostKey) {
  43137. field.originRootHostKey = hostKey;
  43138. root = originRoot;
  43139. } else {
  43140. root = buildGraphic(mapRecord, boundingRect).root;
  43141. }
  43142. return rootMap.set(hostKey, root);
  43143. },
  43144. removeGraphic: function (mapName, mapRecord, hostKey) {
  43145. var field = inner$7(mapRecord);
  43146. var rootMap = field.rootMap;
  43147. rootMap && rootMap.removeKey(hostKey);
  43148. if (hostKey === field.originRootHostKey) {
  43149. field.originRootHostKey = null;
  43150. }
  43151. }
  43152. };
  43153. function buildGraphic(mapRecord, boundingRect) {
  43154. var svgXML = mapRecord.svgXML;
  43155. var result;
  43156. var root;
  43157. try {
  43158. result = svgXML && parseSVG(svgXML, {
  43159. ignoreViewBox: true,
  43160. ignoreRootClip: true
  43161. }) || {};
  43162. root = result.root;
  43163. assert(root != null);
  43164. } catch (e) {
  43165. throw new Error('Invalid svg format\n' + e.message);
  43166. }
  43167. var svgWidth = result.width;
  43168. var svgHeight = result.height;
  43169. var viewBoxRect = result.viewBoxRect;
  43170. if (!boundingRect) {
  43171. boundingRect = svgWidth == null || svgHeight == null ? // If svg width / height not specified, calculate
  43172. // bounding rect as the width / height
  43173. root.getBoundingRect() : new BoundingRect(0, 0, 0, 0);
  43174. if (svgWidth != null) {
  43175. boundingRect.width = svgWidth;
  43176. }
  43177. if (svgHeight != null) {
  43178. boundingRect.height = svgHeight;
  43179. }
  43180. }
  43181. if (viewBoxRect) {
  43182. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  43183. var elRoot = root;
  43184. root = new Group();
  43185. root.add(elRoot);
  43186. elRoot.scaleX = elRoot.scaleY = viewBoxTransform.scale;
  43187. elRoot.x = viewBoxTransform.x;
  43188. elRoot.y = viewBoxTransform.y;
  43189. }
  43190. root.setClipPath(new Rect({
  43191. shape: boundingRect.plain()
  43192. }));
  43193. return {
  43194. root: root,
  43195. boundingRect: boundingRect
  43196. };
  43197. }
  43198. var loaders = {
  43199. geoJSON: geoJSONLoader,
  43200. svg: geoSVGLoader
  43201. };
  43202. var geoSourceManager = {
  43203. load: function (mapName, nameMap, nameProperty) {
  43204. var regions = [];
  43205. var regionsMap = createHashMap();
  43206. var nameCoordMap = createHashMap();
  43207. var boundingRect;
  43208. var mapRecords = retrieveMap(mapName);
  43209. each(mapRecords, function (record) {
  43210. var singleSource = loaders[record.type].load(mapName, record, nameProperty);
  43211. each(singleSource.regions, function (region) {
  43212. var regionName = region.name; // Try use the alias in geoNameMap
  43213. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  43214. region = region.cloneShallow(regionName = nameMap[regionName]);
  43215. }
  43216. regions.push(region);
  43217. regionsMap.set(regionName, region);
  43218. nameCoordMap.set(regionName, region.center);
  43219. });
  43220. var rect = singleSource.boundingRect;
  43221. if (rect) {
  43222. boundingRect ? boundingRect.union(rect) : boundingRect = rect.clone();
  43223. }
  43224. });
  43225. return {
  43226. regions: regions,
  43227. regionsMap: regionsMap,
  43228. nameCoordMap: nameCoordMap,
  43229. // FIXME Always return new ?
  43230. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  43231. };
  43232. },
  43233. /**
  43234. * @param hostKey For cache.
  43235. * @return Roots.
  43236. */
  43237. makeGraphic: function (mapName, hostKey) {
  43238. var mapRecords = retrieveMap(mapName);
  43239. var results = [];
  43240. each(mapRecords, function (record) {
  43241. var method = loaders[record.type].makeGraphic;
  43242. method && results.push(method(mapName, record, hostKey));
  43243. });
  43244. return results;
  43245. },
  43246. /**
  43247. * @param hostKey For cache.
  43248. */
  43249. removeGraphic: function (mapName, hostKey) {
  43250. var mapRecords = retrieveMap(mapName);
  43251. each(mapRecords, function (record) {
  43252. var method = loaders[record.type].makeGraphic;
  43253. method && method(mapName, record, hostKey);
  43254. });
  43255. }
  43256. };
  43257. function mapNotExistsError(mapName) {
  43258. if ("development" !== 'production') {
  43259. console.error('Map ' + mapName + ' not exists. The GeoJSON of the map must be provided.');
  43260. }
  43261. }
  43262. function retrieveMap(mapName) {
  43263. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  43264. if ("development" !== 'production') {
  43265. if (!mapRecords.length) {
  43266. mapNotExistsError(mapName);
  43267. }
  43268. }
  43269. return mapRecords;
  43270. }
  43271. function getFixedItemStyle(model) {
  43272. var itemStyle = model.getItemStyle();
  43273. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  43274. // they should both set areaColor and color to be null.
  43275. if (areaColor != null) {
  43276. itemStyle.fill = areaColor;
  43277. }
  43278. return itemStyle;
  43279. }
  43280. var MapDraw =
  43281. /** @class */
  43282. function () {
  43283. function MapDraw(api) {
  43284. var group = new Group();
  43285. this.uid = getUID('ec_map_draw'); // @ts-ignore FIXME:TS
  43286. this._controller = new RoamController(api.getZr());
  43287. this._controllerHost = {
  43288. target: group
  43289. };
  43290. this.group = group;
  43291. group.add(this._regionsGroup = new Group());
  43292. group.add(this._backgroundGroup = new Group());
  43293. }
  43294. MapDraw.prototype.draw = function (mapOrGeoModel, ecModel, api, fromView, payload) {
  43295. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  43296. // will be assigned with map data. Other GEO model has no data.
  43297. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  43298. isGeo && ecModel.eachComponent({
  43299. mainType: 'series',
  43300. subType: 'map'
  43301. }, function (mapSeries) {
  43302. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  43303. data = mapSeries.getData();
  43304. }
  43305. });
  43306. var geo = mapOrGeoModel.coordinateSystem;
  43307. this._updateBackground(geo);
  43308. var regionsGroup = this._regionsGroup;
  43309. var group = this.group;
  43310. var transformInfo = geo.getTransformInfo(); // No animation when first draw or in action
  43311. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  43312. var targetScaleX;
  43313. var targetScaleY;
  43314. if (isFirstDraw) {
  43315. group.transform = transformInfo.roamTransform;
  43316. group.decomposeTransform();
  43317. group.dirty();
  43318. } else {
  43319. var target = new Transformable();
  43320. target.transform = transformInfo.roamTransform;
  43321. target.decomposeTransform();
  43322. var props = {
  43323. scaleX: target.scaleX,
  43324. scaleY: target.scaleY,
  43325. x: target.x,
  43326. y: target.y
  43327. };
  43328. targetScaleX = target.scaleX;
  43329. targetScaleY = target.scaleY;
  43330. updateProps(group, props, mapOrGeoModel);
  43331. }
  43332. regionsGroup.removeAll();
  43333. var nameMap = createHashMap();
  43334. var isVisualEncodedByVisualMap = data && data.getVisual('visualMeta') && data.getVisual('visualMeta').length > 0;
  43335. each(geo.regions, function (region) {
  43336. // Consider in GeoJson properties.name may be duplicated, for example,
  43337. // there is multiple region named "United Kindom" or "France" (so many
  43338. // colonies). And it is not appropriate to merge them in geo, which
  43339. // will make them share the same label and bring trouble in label
  43340. // location calculation.
  43341. var regionGroup = nameMap.get(region.name) || nameMap.set(region.name, new Group());
  43342. var compoundPath = new CompoundPath({
  43343. segmentIgnoreThreshold: 1,
  43344. shape: {
  43345. paths: []
  43346. }
  43347. });
  43348. regionGroup.add(compoundPath);
  43349. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel; // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43350. var itemStyleModel = regionModel.getModel('itemStyle'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43351. var emphasisModel = regionModel.getModel('emphasis');
  43352. var emphasisItemStyleModel = emphasisModel.getModel('itemStyle'); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43353. var blurItemStyleModel = regionModel.getModel(['blur', 'itemStyle']); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43354. var selectItemStyleModel = regionModel.getModel(['select', 'itemStyle']); // NOTE: DONT use 'style' in visual when drawing map.
  43355. // This component is used for drawing underlying map for both geo component and map series.
  43356. var itemStyle = getFixedItemStyle(itemStyleModel);
  43357. var emphasisItemStyle = getFixedItemStyle(emphasisItemStyleModel);
  43358. var blurItemStyle = getFixedItemStyle(blurItemStyleModel);
  43359. var selectItemStyle = getFixedItemStyle(selectItemStyleModel);
  43360. var dataIdx; // Use the itemStyle in data if has data
  43361. if (data) {
  43362. dataIdx = data.indexOfName(region.name); // Only visual color of each item will be used. It can be encoded by visualMap
  43363. // But visual color of series is used in symbol drawing
  43364. //
  43365. // Visual color for each series is for the symbol draw
  43366. var style = data.getItemVisual(dataIdx, 'style');
  43367. var decal = data.getItemVisual(dataIdx, 'decal');
  43368. if (isVisualEncodedByVisualMap && style.fill) {
  43369. itemStyle.fill = style.fill;
  43370. }
  43371. if (decal) {
  43372. itemStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  43373. }
  43374. }
  43375. var sx = transformInfo.rawScaleX;
  43376. var sy = transformInfo.rawScaleY;
  43377. var offsetX = transformInfo.rawX;
  43378. var offsetY = transformInfo.rawY;
  43379. var transformPoint = function (point) {
  43380. return [point[0] * sx + offsetX, point[1] * sy + offsetY];
  43381. };
  43382. each(region.geometries, function (geometry) {
  43383. if (geometry.type !== 'polygon') {
  43384. return;
  43385. }
  43386. var points = [];
  43387. for (var i = 0; i < geometry.exterior.length; ++i) {
  43388. points.push(transformPoint(geometry.exterior[i]));
  43389. }
  43390. compoundPath.shape.paths.push(new Polygon({
  43391. segmentIgnoreThreshold: 1,
  43392. shape: {
  43393. points: points
  43394. }
  43395. }));
  43396. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  43397. var interior = geometry.interiors[i];
  43398. var points_1 = [];
  43399. for (var j = 0; j < interior.length; ++j) {
  43400. points_1.push(transformPoint(interior[j]));
  43401. }
  43402. compoundPath.shape.paths.push(new Polygon({
  43403. segmentIgnoreThreshold: 1,
  43404. shape: {
  43405. points: points_1
  43406. }
  43407. }));
  43408. }
  43409. });
  43410. compoundPath.setStyle(itemStyle);
  43411. compoundPath.style.strokeNoScale = true;
  43412. compoundPath.culling = true;
  43413. compoundPath.ensureState('emphasis').style = emphasisItemStyle;
  43414. compoundPath.ensureState('blur').style = blurItemStyle;
  43415. compoundPath.ensureState('select').style = selectItemStyle;
  43416. var showLabel = false;
  43417. for (var i = 0; i < DISPLAY_STATES.length; i++) {
  43418. var stateName = DISPLAY_STATES[i]; // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43419. if (regionModel.get(stateName === 'normal' ? ['label', 'show'] : [stateName, 'label', 'show'])) {
  43420. showLabel = true;
  43421. break;
  43422. }
  43423. }
  43424. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  43425. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  43426. // 1. In map series and data value is NaN
  43427. // 2. In geo component
  43428. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  43429. if (isGeo || isDataNaN && showLabel || itemLayout && itemLayout.showLabel) {
  43430. var query = !isGeo ? dataIdx : region.name;
  43431. var labelFetcher = void 0; // Consider dataIdx not found.
  43432. if (!data || dataIdx >= 0) {
  43433. labelFetcher = mapOrGeoModel;
  43434. }
  43435. var centerPt = transformPoint(region.center);
  43436. var textEl = new ZRText({
  43437. x: centerPt[0],
  43438. y: centerPt[1],
  43439. // FIXME
  43440. // label rotation is not support yet in geo or regions of series-map
  43441. // that has no data. The rotation will be effected by this `scale`.
  43442. // So needed to change to RectText?
  43443. scaleX: 1 / group.scaleX,
  43444. scaleY: 1 / group.scaleY,
  43445. z2: 10,
  43446. silent: true
  43447. });
  43448. setLabelStyle(textEl, getLabelStatesModels(regionModel), {
  43449. labelFetcher: labelFetcher,
  43450. labelDataIndex: query,
  43451. defaultText: region.name
  43452. }, {
  43453. normal: {
  43454. align: 'center',
  43455. verticalAlign: 'middle'
  43456. }
  43457. });
  43458. compoundPath.setTextContent(textEl);
  43459. compoundPath.setTextConfig({
  43460. local: true
  43461. });
  43462. compoundPath.disableLabelAnimation = true;
  43463. if (!isFirstDraw) {
  43464. // Text animation
  43465. updateProps(textEl, {
  43466. scaleX: 1 / targetScaleX,
  43467. scaleY: 1 / targetScaleY
  43468. }, mapOrGeoModel);
  43469. }
  43470. } // setItemGraphicEl, setHoverStyle after all polygons and labels
  43471. // are added to the rigionGroup
  43472. if (data) {
  43473. data.setItemGraphicEl(dataIdx, regionGroup);
  43474. } else {
  43475. var regionModel_1 = mapOrGeoModel.getRegionModel(region.name); // Package custom mouse event for geo component
  43476. getECData(compoundPath).eventData = {
  43477. componentType: 'geo',
  43478. componentIndex: mapOrGeoModel.componentIndex,
  43479. geoIndex: mapOrGeoModel.componentIndex,
  43480. name: region.name,
  43481. region: regionModel_1 && regionModel_1.option || {}
  43482. };
  43483. }
  43484. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  43485. groupRegions.push(region); // @ts-ignore FIXME:TS fix the "compatible with each other"?
  43486. regionGroup.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
  43487. enableHoverEmphasis(regionGroup, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  43488. regionsGroup.add(regionGroup);
  43489. });
  43490. this._updateController(mapOrGeoModel, ecModel, api);
  43491. this._updateMapSelectHandler(mapOrGeoModel, regionsGroup, api, fromView);
  43492. };
  43493. MapDraw.prototype.remove = function () {
  43494. this._regionsGroup.removeAll();
  43495. this._backgroundGroup.removeAll();
  43496. this._controller.dispose();
  43497. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  43498. this._mapName = null;
  43499. this._controllerHost = null;
  43500. };
  43501. MapDraw.prototype._updateBackground = function (geo) {
  43502. var mapName = geo.map;
  43503. if (this._mapName !== mapName) {
  43504. each(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  43505. this._backgroundGroup.add(root);
  43506. }, this);
  43507. }
  43508. this._mapName = mapName;
  43509. };
  43510. MapDraw.prototype._updateController = function (mapOrGeoModel, ecModel, api) {
  43511. var geo = mapOrGeoModel.coordinateSystem;
  43512. var controller = this._controller;
  43513. var controllerHost = this._controllerHost; // @ts-ignore FIXME:TS
  43514. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  43515. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  43516. // @ts-ignore FIXME:TS
  43517. controller.enable(mapOrGeoModel.get('roam') || false);
  43518. var mainType = mapOrGeoModel.mainType;
  43519. function makeActionBase() {
  43520. var action = {
  43521. type: 'geoRoam',
  43522. componentType: mainType
  43523. };
  43524. action[mainType + 'Id'] = mapOrGeoModel.id;
  43525. return action;
  43526. }
  43527. controller.off('pan').on('pan', function (e) {
  43528. this._mouseDownFlag = false;
  43529. updateViewOnPan(controllerHost, e.dx, e.dy);
  43530. api.dispatchAction(extend(makeActionBase(), {
  43531. dx: e.dx,
  43532. dy: e.dy
  43533. }));
  43534. }, this);
  43535. controller.off('zoom').on('zoom', function (e) {
  43536. this._mouseDownFlag = false;
  43537. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  43538. api.dispatchAction(extend(makeActionBase(), {
  43539. zoom: e.scale,
  43540. originX: e.originX,
  43541. originY: e.originY
  43542. }));
  43543. var group = this.group;
  43544. this._regionsGroup.traverse(function (el) {
  43545. var textContent = el.getTextContent();
  43546. if (textContent) {
  43547. textContent.scaleX = 1 / group.scaleX;
  43548. textContent.scaleY = 1 / group.scaleY;
  43549. textContent.markRedraw();
  43550. }
  43551. });
  43552. }, this);
  43553. controller.setPointerChecker(function (e, x, y) {
  43554. return geo.getViewRectAfterRoam().contain(x, y) && !onIrrelevantElement(e, api, mapOrGeoModel);
  43555. });
  43556. };
  43557. MapDraw.prototype._updateMapSelectHandler = function (mapOrGeoModel, regionsGroup, api, fromView) {
  43558. var mapDraw = this;
  43559. regionsGroup.off('mousedown'); // @ts-ignore FIXME:TS resolve type conflict
  43560. if (mapOrGeoModel.get('selectedMode')) {
  43561. regionsGroup.on('mousedown', function () {
  43562. mapDraw._mouseDownFlag = true;
  43563. });
  43564. regionsGroup.on('click', function (e) {
  43565. if (!mapDraw._mouseDownFlag) {
  43566. return;
  43567. }
  43568. mapDraw._mouseDownFlag = false;
  43569. });
  43570. }
  43571. };
  43572. return MapDraw;
  43573. }();
  43574. var MapView =
  43575. /** @class */
  43576. function (_super) {
  43577. __extends(MapView, _super);
  43578. function MapView() {
  43579. var _this = _super !== null && _super.apply(this, arguments) || this;
  43580. _this.type = MapView.type;
  43581. return _this;
  43582. }
  43583. MapView.prototype.render = function (mapModel, ecModel, api, payload) {
  43584. // Not render if it is an toggleSelect action from self
  43585. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  43586. return;
  43587. }
  43588. var group = this.group;
  43589. group.removeAll();
  43590. if (mapModel.getHostGeoModel()) {
  43591. return;
  43592. } // Not update map if it is an roam action from self
  43593. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  43594. if (mapModel.needsDrawMap) {
  43595. var mapDraw = this._mapDraw || new MapDraw(api);
  43596. group.add(mapDraw.group);
  43597. mapDraw.draw(mapModel, ecModel, api, this, payload);
  43598. this._mapDraw = mapDraw;
  43599. } else {
  43600. // Remove drawed map
  43601. this._mapDraw && this._mapDraw.remove();
  43602. this._mapDraw = null;
  43603. }
  43604. } else {
  43605. var mapDraw = this._mapDraw;
  43606. mapDraw && group.add(mapDraw.group);
  43607. }
  43608. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  43609. };
  43610. MapView.prototype.remove = function () {
  43611. this._mapDraw && this._mapDraw.remove();
  43612. this._mapDraw = null;
  43613. this.group.removeAll();
  43614. };
  43615. MapView.prototype.dispose = function () {
  43616. this._mapDraw && this._mapDraw.remove();
  43617. this._mapDraw = null;
  43618. };
  43619. MapView.prototype._renderSymbols = function (mapModel, ecModel, api) {
  43620. var originalData = mapModel.originalData;
  43621. var group = this.group;
  43622. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  43623. if (isNaN(value)) {
  43624. return;
  43625. }
  43626. var layout = originalData.getItemLayout(originalDataIndex);
  43627. if (!layout || !layout.point) {
  43628. // Not exists in map
  43629. return;
  43630. }
  43631. var point = layout.point;
  43632. var offset = layout.offset;
  43633. var circle = new Circle({
  43634. style: {
  43635. // Because the special of map draw.
  43636. // Which needs statistic of multiple series and draw on one map.
  43637. // And each series also need a symbol with legend color
  43638. //
  43639. // Layout and visual are put one the different data
  43640. // TODO
  43641. fill: mapModel.getData().getVisual('style').fill
  43642. },
  43643. shape: {
  43644. cx: point[0] + offset * 9,
  43645. cy: point[1],
  43646. r: 3
  43647. },
  43648. silent: true,
  43649. // Do not overlap the first series, on which labels are displayed.
  43650. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  43651. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  43652. // But consider the case:
  43653. // series: [
  43654. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  43655. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  43656. // ]
  43657. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  43658. // For backward compatibility, we follow the rule that render label `A` by the
  43659. // settings on series `X` but render label `C` by the settings on series `Y`.
  43660. if (!offset) {
  43661. var fullData = mapModel.mainSeries.getData();
  43662. var name_1 = originalData.getName(originalDataIndex);
  43663. var fullIndex_1 = fullData.indexOfName(name_1);
  43664. var itemModel = originalData.getItemModel(originalDataIndex);
  43665. var labelModel = itemModel.getModel('label');
  43666. var regionGroup = fullData.getItemGraphicEl(fullIndex_1); // `getFormattedLabel` needs to use `getData` inside. Here
  43667. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  43668. // FIXME
  43669. // If this is not the `mainSeries`, the item model (like label formatter)
  43670. // set on original data item will never get. But it has been working
  43671. // like that from the begining, and this scenario is rarely encountered.
  43672. // So it won't be fixed until have to.
  43673. setLabelStyle(circle, getLabelStatesModels(itemModel), {
  43674. labelFetcher: {
  43675. getFormattedLabel: function (idx, state) {
  43676. return mapModel.getFormattedLabel(fullIndex_1, state);
  43677. }
  43678. }
  43679. });
  43680. circle.disableLabelAnimation = true;
  43681. if (!labelModel.get('position')) {
  43682. circle.setTextConfig({
  43683. position: 'bottom'
  43684. });
  43685. }
  43686. regionGroup.onHoverStateChange = function (toState) {
  43687. circle.useState(toState);
  43688. };
  43689. }
  43690. group.add(circle);
  43691. });
  43692. };
  43693. MapView.type = 'map';
  43694. return MapView;
  43695. }(ChartView);
  43696. var MapSeries =
  43697. /** @class */
  43698. function (_super) {
  43699. __extends(MapSeries, _super);
  43700. function MapSeries() {
  43701. var _this = _super !== null && _super.apply(this, arguments) || this;
  43702. _this.type = MapSeries.type; // Only first map series of same mapType will drawMap.
  43703. _this.needsDrawMap = false; // Group of all map series with same mapType
  43704. _this.seriesGroup = [];
  43705. _this.getTooltipPosition = function (dataIndex) {
  43706. if (dataIndex != null) {
  43707. var name_1 = this.getData().getName(dataIndex);
  43708. var geo = this.coordinateSystem;
  43709. var region = geo.getRegion(name_1);
  43710. return region && geo.dataToPoint(region.center);
  43711. }
  43712. };
  43713. return _this;
  43714. }
  43715. MapSeries.prototype.getInitialData = function (option) {
  43716. var data = createListSimply(this, {
  43717. coordDimensions: ['value'],
  43718. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  43719. });
  43720. var dataNameMap = createHashMap();
  43721. var toAppendNames = [];
  43722. for (var i = 0, len = data.count(); i < len; i++) {
  43723. var name_2 = data.getName(i);
  43724. dataNameMap.set(name_2, true);
  43725. }
  43726. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  43727. each(geoSource.regions, function (region) {
  43728. var name = region.name;
  43729. if (!dataNameMap.get(name)) {
  43730. toAppendNames.push(name);
  43731. }
  43732. }); // Complete data with missing regions. The consequent processes (like visual
  43733. // map and render) can not be performed without a "full data". For example,
  43734. // find `dataIndex` by name.
  43735. data.appendValues([], toAppendNames);
  43736. return data;
  43737. };
  43738. /**
  43739. * If no host geo model, return null, which means using a
  43740. * inner exclusive geo model.
  43741. */
  43742. MapSeries.prototype.getHostGeoModel = function () {
  43743. var geoIndex = this.option.geoIndex;
  43744. return geoIndex != null ? this.ecModel.getComponent('geo', geoIndex) : null;
  43745. };
  43746. MapSeries.prototype.getMapType = function () {
  43747. return (this.getHostGeoModel() || this).option.map;
  43748. }; // _fillOption(option, mapName) {
  43749. // Shallow clone
  43750. // option = zrUtil.extend({}, option);
  43751. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  43752. // return option;
  43753. // }
  43754. MapSeries.prototype.getRawValue = function (dataIndex) {
  43755. // Use value stored in data instead because it is calculated from multiple series
  43756. // FIXME Provide all value of multiple series ?
  43757. var data = this.getData();
  43758. return data.get(data.mapDimension('value'), dataIndex);
  43759. };
  43760. /**
  43761. * Get model of region
  43762. */
  43763. MapSeries.prototype.getRegionModel = function (regionName) {
  43764. var data = this.getData();
  43765. return data.getItemModel(data.indexOfName(regionName));
  43766. };
  43767. /**
  43768. * Map tooltip formatter
  43769. */
  43770. MapSeries.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  43771. // FIXME orignalData and data is a bit confusing
  43772. var data = this.getData();
  43773. var value = this.getRawValue(dataIndex);
  43774. var name = data.getName(dataIndex);
  43775. var seriesGroup = this.seriesGroup;
  43776. var seriesNames = [];
  43777. for (var i = 0; i < seriesGroup.length; i++) {
  43778. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  43779. var valueDim = data.mapDimension('value');
  43780. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  43781. seriesNames.push(seriesGroup[i].name);
  43782. }
  43783. }
  43784. return createTooltipMarkup('section', {
  43785. header: seriesNames.join(', '),
  43786. noHeader: !seriesNames.length,
  43787. blocks: [createTooltipMarkup('nameValue', {
  43788. name: name,
  43789. value: value
  43790. })]
  43791. });
  43792. };
  43793. MapSeries.prototype.setZoom = function (zoom) {
  43794. this.option.zoom = zoom;
  43795. };
  43796. MapSeries.prototype.setCenter = function (center) {
  43797. this.option.center = center;
  43798. };
  43799. MapSeries.type = 'series.map';
  43800. MapSeries.dependencies = ['geo'];
  43801. MapSeries.layoutMode = 'box';
  43802. MapSeries.defaultOption = {
  43803. // 一级层叠
  43804. zlevel: 0,
  43805. // 二级层叠
  43806. z: 2,
  43807. coordinateSystem: 'geo',
  43808. // map should be explicitly specified since ec3.
  43809. map: '',
  43810. // If `geoIndex` is not specified, a exclusive geo will be
  43811. // created. Otherwise use the specified geo component, and
  43812. // `map` and `mapType` are ignored.
  43813. // geoIndex: 0,
  43814. // 'center' | 'left' | 'right' | 'x%' | {number}
  43815. left: 'center',
  43816. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  43817. top: 'center',
  43818. // right
  43819. // bottom
  43820. // width:
  43821. // height
  43822. // Aspect is width / height. Inited to be geoJson bbox aspect
  43823. // This parameter is used for scale this aspect
  43824. aspectScale: 0.75,
  43825. ///// Layout with center and size
  43826. // If you wan't to put map in a fixed size box with right aspect ratio
  43827. // This two properties may more conveninet
  43828. // layoutCenter: [50%, 50%]
  43829. // layoutSize: 100
  43830. showLegendSymbol: true,
  43831. // Define left-top, right-bottom coords to control view
  43832. // For example, [ [180, 90], [-180, -90] ],
  43833. // higher priority than center and zoom
  43834. boundingCoords: null,
  43835. // Default on center of map
  43836. center: null,
  43837. zoom: 1,
  43838. scaleLimit: null,
  43839. selectedMode: true,
  43840. label: {
  43841. show: false,
  43842. color: '#000'
  43843. },
  43844. // scaleLimit: null,
  43845. itemStyle: {
  43846. borderWidth: 0.5,
  43847. borderColor: '#444',
  43848. areaColor: '#eee'
  43849. },
  43850. emphasis: {
  43851. label: {
  43852. show: true,
  43853. color: 'rgb(100,0,0)'
  43854. },
  43855. itemStyle: {
  43856. areaColor: 'rgba(255,215,0,0.8)'
  43857. }
  43858. },
  43859. select: {
  43860. label: {
  43861. show: true,
  43862. color: 'rgb(100,0,0)'
  43863. },
  43864. itemStyle: {
  43865. color: 'rgba(255,215,0,0.8)'
  43866. }
  43867. },
  43868. nameProperty: 'name'
  43869. };
  43870. return MapSeries;
  43871. }(SeriesModel);
  43872. function dataStatistics(datas, statisticType) {
  43873. var dataNameMap = {};
  43874. each(datas, function (data) {
  43875. data.each(data.mapDimension('value'), function (value, idx) {
  43876. // Add prefix to avoid conflict with Object.prototype.
  43877. var mapKey = 'ec-' + data.getName(idx);
  43878. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  43879. if (!isNaN(value)) {
  43880. dataNameMap[mapKey].push(value);
  43881. }
  43882. });
  43883. });
  43884. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  43885. var mapKey = 'ec-' + datas[0].getName(idx);
  43886. var sum = 0;
  43887. var min = Infinity;
  43888. var max = -Infinity;
  43889. var len = dataNameMap[mapKey].length;
  43890. for (var i = 0; i < len; i++) {
  43891. min = Math.min(min, dataNameMap[mapKey][i]);
  43892. max = Math.max(max, dataNameMap[mapKey][i]);
  43893. sum += dataNameMap[mapKey][i];
  43894. }
  43895. var result;
  43896. if (statisticType === 'min') {
  43897. result = min;
  43898. } else if (statisticType === 'max') {
  43899. result = max;
  43900. } else if (statisticType === 'average') {
  43901. result = sum / len;
  43902. } else {
  43903. result = sum;
  43904. }
  43905. return len === 0 ? NaN : result;
  43906. });
  43907. }
  43908. function mapDataStatistic(ecModel) {
  43909. var seriesGroups = {};
  43910. ecModel.eachSeriesByType('map', function (seriesModel) {
  43911. var hostGeoModel = seriesModel.getHostGeoModel();
  43912. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  43913. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  43914. });
  43915. each(seriesGroups, function (seriesList, key) {
  43916. var data = dataStatistics(map(seriesList, function (seriesModel) {
  43917. return seriesModel.getData();
  43918. }), seriesList[0].get('mapValueCalculation'));
  43919. for (var i = 0; i < seriesList.length; i++) {
  43920. seriesList[i].originalData = seriesList[i].getData();
  43921. } // FIXME Put where?
  43922. for (var i = 0; i < seriesList.length; i++) {
  43923. seriesList[i].seriesGroup = seriesList;
  43924. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  43925. seriesList[i].setData(data.cloneShallow());
  43926. seriesList[i].mainSeries = seriesList[0];
  43927. }
  43928. });
  43929. }
  43930. function mapSymbolLayout(ecModel) {
  43931. var processedMapType = {};
  43932. ecModel.eachSeriesByType('map', function (mapSeries) {
  43933. var mapType = mapSeries.getMapType();
  43934. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  43935. return;
  43936. }
  43937. var mapSymbolOffsets = {};
  43938. each(mapSeries.seriesGroup, function (subMapSeries) {
  43939. var geo = subMapSeries.coordinateSystem;
  43940. var data = subMapSeries.originalData;
  43941. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  43942. data.each(data.mapDimension('value'), function (value, idx) {
  43943. var name = data.getName(idx);
  43944. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  43945. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  43946. // not be drawn. So here must validate if value is NaN.
  43947. if (!region || isNaN(value)) {
  43948. return;
  43949. }
  43950. var offset = mapSymbolOffsets[name] || 0;
  43951. var point = geo.dataToPoint(region.center);
  43952. mapSymbolOffsets[name] = offset + 1;
  43953. data.setItemLayout(idx, {
  43954. point: point,
  43955. offset: offset
  43956. });
  43957. });
  43958. }
  43959. }); // Show label of those region not has legendSymbol(which is offset 0)
  43960. var data = mapSeries.getData();
  43961. data.each(function (idx) {
  43962. var name = data.getName(idx);
  43963. var layout = data.getItemLayout(idx) || {};
  43964. layout.showLabel = !mapSymbolOffsets[name];
  43965. data.setItemLayout(idx, layout);
  43966. });
  43967. processedMapType[mapType] = true;
  43968. });
  43969. }
  43970. var v2ApplyTransform = applyTransform;
  43971. var View =
  43972. /** @class */
  43973. function (_super) {
  43974. __extends(View, _super);
  43975. function View(name) {
  43976. var _this = _super.call(this) || this;
  43977. _this.type = 'view';
  43978. _this.dimensions = ['x', 'y'];
  43979. _this._roamTransformable = new Transformable();
  43980. _this._rawTransformable = new Transformable();
  43981. _this.name = name;
  43982. return _this;
  43983. } // PENDING to getRect
  43984. View.prototype.setBoundingRect = function (x, y, width, height) {
  43985. this._rect = new BoundingRect(x, y, width, height);
  43986. return this._rect;
  43987. };
  43988. /**
  43989. * @return {module:zrender/core/BoundingRect}
  43990. */
  43991. // PENDING to getRect
  43992. View.prototype.getBoundingRect = function () {
  43993. return this._rect;
  43994. };
  43995. View.prototype.setViewRect = function (x, y, width, height) {
  43996. this.transformTo(x, y, width, height);
  43997. this._viewRect = new BoundingRect(x, y, width, height);
  43998. };
  43999. /**
  44000. * Transformed to particular position and size
  44001. */
  44002. View.prototype.transformTo = function (x, y, width, height) {
  44003. var rect = this.getBoundingRect();
  44004. var rawTransform = this._rawTransformable;
  44005. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  44006. rawTransform.decomposeTransform();
  44007. this._updateTransform();
  44008. };
  44009. /**
  44010. * Set center of view
  44011. */
  44012. View.prototype.setCenter = function (centerCoord) {
  44013. if (!centerCoord) {
  44014. return;
  44015. }
  44016. this._center = centerCoord;
  44017. this._updateCenterAndZoom();
  44018. };
  44019. View.prototype.setZoom = function (zoom) {
  44020. zoom = zoom || 1;
  44021. var zoomLimit = this.zoomLimit;
  44022. if (zoomLimit) {
  44023. if (zoomLimit.max != null) {
  44024. zoom = Math.min(zoomLimit.max, zoom);
  44025. }
  44026. if (zoomLimit.min != null) {
  44027. zoom = Math.max(zoomLimit.min, zoom);
  44028. }
  44029. }
  44030. this._zoom = zoom;
  44031. this._updateCenterAndZoom();
  44032. };
  44033. /**
  44034. * Get default center without roam
  44035. */
  44036. View.prototype.getDefaultCenter = function () {
  44037. // Rect before any transform
  44038. var rawRect = this.getBoundingRect();
  44039. var cx = rawRect.x + rawRect.width / 2;
  44040. var cy = rawRect.y + rawRect.height / 2;
  44041. return [cx, cy];
  44042. };
  44043. View.prototype.getCenter = function () {
  44044. return this._center || this.getDefaultCenter();
  44045. };
  44046. View.prototype.getZoom = function () {
  44047. return this._zoom || 1;
  44048. };
  44049. View.prototype.getRoamTransform = function () {
  44050. return this._roamTransformable.getLocalTransform();
  44051. };
  44052. /**
  44053. * Remove roam
  44054. */
  44055. View.prototype._updateCenterAndZoom = function () {
  44056. // Must update after view transform updated
  44057. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  44058. var roamTransform = this._roamTransformable;
  44059. var defaultCenter = this.getDefaultCenter();
  44060. var center = this.getCenter();
  44061. var zoom = this.getZoom();
  44062. center = applyTransform([], center, rawTransformMatrix);
  44063. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  44064. roamTransform.originX = center[0];
  44065. roamTransform.originY = center[1];
  44066. roamTransform.x = defaultCenter[0] - center[0];
  44067. roamTransform.y = defaultCenter[1] - center[1];
  44068. roamTransform.scaleX = roamTransform.scaleY = zoom;
  44069. this._updateTransform();
  44070. };
  44071. /**
  44072. * Update transform from roam and mapLocation
  44073. */
  44074. View.prototype._updateTransform = function () {
  44075. var roamTransformable = this._roamTransformable;
  44076. var rawTransformable = this._rawTransformable;
  44077. rawTransformable.parent = roamTransformable;
  44078. roamTransformable.updateTransform();
  44079. rawTransformable.updateTransform();
  44080. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  44081. this._rawTransform = rawTransformable.getLocalTransform();
  44082. this.invTransform = this.invTransform || [];
  44083. invert(this.invTransform, this.transform);
  44084. this.decomposeTransform();
  44085. };
  44086. View.prototype.getTransformInfo = function () {
  44087. var roamTransform = this._roamTransformable.transform;
  44088. var rawTransformable = this._rawTransformable;
  44089. return {
  44090. roamTransform: roamTransform ? slice(roamTransform) : create$1(),
  44091. rawScaleX: rawTransformable.scaleX,
  44092. rawScaleY: rawTransformable.scaleY,
  44093. rawX: rawTransformable.x,
  44094. rawY: rawTransformable.y
  44095. };
  44096. };
  44097. View.prototype.getViewRect = function () {
  44098. return this._viewRect;
  44099. };
  44100. /**
  44101. * Get view rect after roam transform
  44102. */
  44103. View.prototype.getViewRectAfterRoam = function () {
  44104. var rect = this.getBoundingRect().clone();
  44105. rect.applyTransform(this.transform);
  44106. return rect;
  44107. };
  44108. /**
  44109. * Convert a single (lon, lat) data item to (x, y) point.
  44110. */
  44111. View.prototype.dataToPoint = function (data, noRoam, out) {
  44112. var transform = noRoam ? this._rawTransform : this.transform;
  44113. out = out || [];
  44114. return transform ? v2ApplyTransform(out, data, transform) : copy(out, data);
  44115. };
  44116. /**
  44117. * Convert a (x, y) point to (lon, lat) data
  44118. */
  44119. View.prototype.pointToData = function (point) {
  44120. var invTransform = this.invTransform;
  44121. return invTransform ? v2ApplyTransform([], point, invTransform) : [point[0], point[1]];
  44122. };
  44123. View.prototype.convertToPixel = function (ecModel, finder, value) {
  44124. var coordSys = getCoordSys(finder);
  44125. return coordSys === this ? coordSys.dataToPoint(value) : null;
  44126. };
  44127. View.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44128. var coordSys = getCoordSys(finder);
  44129. return coordSys === this ? coordSys.pointToData(pixel) : null;
  44130. };
  44131. /**
  44132. * @implements
  44133. */
  44134. View.prototype.containPoint = function (point) {
  44135. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  44136. };
  44137. View.dimensions = ['x', 'y'];
  44138. return View;
  44139. }(Transformable);
  44140. function getCoordSys(finder) {
  44141. var seriesModel = finder.seriesModel;
  44142. return seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  44143. }
  44144. var Geo =
  44145. /** @class */
  44146. function (_super) {
  44147. __extends(Geo, _super);
  44148. /**
  44149. * For backward compatibility, the orginal interface:
  44150. * `name, map, geoJson, specialAreas, nameMap` is kept.
  44151. *
  44152. * @param map Map type Specify the positioned areas by left, top, width, height.
  44153. * @param [nameMap] Specify name alias
  44154. */
  44155. function Geo(name, map, nameMap, invertLongitute) {
  44156. var _this = _super.call(this, name) || this;
  44157. _this.dimensions = ['lng', 'lat'];
  44158. _this.type = 'geo';
  44159. _this.map = map;
  44160. var source = geoSourceManager.load(map, nameMap);
  44161. _this._nameCoordMap = source.nameCoordMap;
  44162. _this._regionsMap = source.regionsMap;
  44163. _this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  44164. _this.regions = source.regions;
  44165. _this._rect = source.boundingRect;
  44166. return _this;
  44167. }
  44168. /**
  44169. * Whether contain the given [lng, lat] coord.
  44170. */
  44171. Geo.prototype.containCoord = function (coord) {
  44172. var regions = this.regions;
  44173. for (var i = 0; i < regions.length; i++) {
  44174. if (regions[i].contain(coord)) {
  44175. return true;
  44176. }
  44177. }
  44178. return false;
  44179. };
  44180. Geo.prototype.transformTo = function (x, y, width, height) {
  44181. var rect = this.getBoundingRect();
  44182. var invertLongitute = this._invertLongitute;
  44183. rect = rect.clone();
  44184. if (invertLongitute) {
  44185. // Longitute is inverted
  44186. rect.y = -rect.y - rect.height;
  44187. }
  44188. var rawTransformable = this._rawTransformable;
  44189. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  44190. rawTransformable.decomposeTransform();
  44191. if (invertLongitute) {
  44192. rawTransformable.scaleY = -rawTransformable.scaleY;
  44193. }
  44194. rawTransformable.updateTransform();
  44195. this._updateTransform();
  44196. };
  44197. Geo.prototype.getRegion = function (name) {
  44198. return this._regionsMap.get(name);
  44199. };
  44200. Geo.prototype.getRegionByCoord = function (coord) {
  44201. var regions = this.regions;
  44202. for (var i = 0; i < regions.length; i++) {
  44203. if (regions[i].contain(coord)) {
  44204. return regions[i];
  44205. }
  44206. }
  44207. };
  44208. /**
  44209. * Add geoCoord for indexing by name
  44210. */
  44211. Geo.prototype.addGeoCoord = function (name, geoCoord) {
  44212. this._nameCoordMap.set(name, geoCoord);
  44213. };
  44214. /**
  44215. * Get geoCoord by name
  44216. */
  44217. Geo.prototype.getGeoCoord = function (name) {
  44218. return this._nameCoordMap.get(name);
  44219. };
  44220. Geo.prototype.getBoundingRect = function () {
  44221. return this._rect;
  44222. };
  44223. Geo.prototype.dataToPoint = function (data, noRoam, out) {
  44224. if (typeof data === 'string') {
  44225. // Map area name to geoCoord
  44226. data = this.getGeoCoord(data);
  44227. }
  44228. if (data) {
  44229. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  44230. }
  44231. };
  44232. Geo.prototype.convertToPixel = function (ecModel, finder, value) {
  44233. var coordSys = getCoordSys$1(finder);
  44234. return coordSys === this ? coordSys.dataToPoint(value) : null;
  44235. };
  44236. Geo.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  44237. var coordSys = getCoordSys$1(finder);
  44238. return coordSys === this ? coordSys.pointToData(pixel) : null;
  44239. };
  44240. return Geo;
  44241. }(View);
  44242. mixin(Geo, View);
  44243. function getCoordSys$1(finder) {
  44244. var geoModel = finder.geoModel;
  44245. var seriesModel = finder.seriesModel;
  44246. return geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map series.
  44247. || (seriesModel.getReferringComponents('geo', SINGLE_REFERRING).models[0] || {}).coordinateSystem : null;
  44248. }
  44249. /**
  44250. * Resize method bound to the geo
  44251. */
  44252. function resizeGeo(geoModel, api) {
  44253. var boundingCoords = geoModel.get('boundingCoords');
  44254. if (boundingCoords != null) {
  44255. var leftTop = boundingCoords[0];
  44256. var rightBottom = boundingCoords[1];
  44257. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  44258. if ("development" !== 'production') {
  44259. console.error('Invalid boundingCoords');
  44260. }
  44261. } else {
  44262. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  44263. }
  44264. }
  44265. var rect = this.getBoundingRect();
  44266. var centerOption = geoModel.get('layoutCenter');
  44267. var sizeOption = geoModel.get('layoutSize');
  44268. var viewWidth = api.getWidth();
  44269. var viewHeight = api.getHeight();
  44270. var aspect = rect.width / rect.height * this.aspectScale;
  44271. var useCenterAndSize = false;
  44272. var center;
  44273. var size;
  44274. if (centerOption && sizeOption) {
  44275. center = [parsePercent$1(centerOption[0], viewWidth), parsePercent$1(centerOption[1], viewHeight)];
  44276. size = parsePercent$1(sizeOption, Math.min(viewWidth, viewHeight));
  44277. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  44278. useCenterAndSize = true;
  44279. } else {
  44280. if ("development" !== 'production') {
  44281. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  44282. }
  44283. }
  44284. }
  44285. var viewRect;
  44286. if (useCenterAndSize) {
  44287. viewRect = {};
  44288. if (aspect > 1) {
  44289. // Width is same with size
  44290. viewRect.width = size;
  44291. viewRect.height = size / aspect;
  44292. } else {
  44293. viewRect.height = size;
  44294. viewRect.width = size * aspect;
  44295. }
  44296. viewRect.y = center[1] - viewRect.height / 2;
  44297. viewRect.x = center[0] - viewRect.width / 2;
  44298. } else {
  44299. // Use left/top/width/height
  44300. var boxLayoutOption = geoModel.getBoxLayoutParams(); // 0.75 rate
  44301. boxLayoutOption.aspect = aspect;
  44302. viewRect = getLayoutRect(boxLayoutOption, {
  44303. width: viewWidth,
  44304. height: viewHeight
  44305. });
  44306. }
  44307. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  44308. this.setCenter(geoModel.get('center'));
  44309. this.setZoom(geoModel.get('zoom'));
  44310. } // Back compat for ECharts2, where the coord map is set on map series:
  44311. // {type: 'map', geoCoord: {'cityA': [116.46,39.92], 'cityA': [119.12,24.61]}},
  44312. function setGeoCoords(geo, model) {
  44313. each(model.get('geoCoord'), function (geoCoord, name) {
  44314. geo.addGeoCoord(name, geoCoord);
  44315. });
  44316. }
  44317. var GeoCreator =
  44318. /** @class */
  44319. function () {
  44320. function GeoCreator() {
  44321. // For deciding which dimensions to use when creating list data
  44322. this.dimensions = Geo.prototype.dimensions;
  44323. }
  44324. GeoCreator.prototype.create = function (ecModel, api) {
  44325. var geoList = []; // FIXME Create each time may be slow
  44326. ecModel.eachComponent('geo', function (geoModel, idx) {
  44327. var name = geoModel.get('map');
  44328. var aspectScale = geoModel.get('aspectScale');
  44329. var invertLongitute = true;
  44330. var mapRecords = mapDataStorage.retrieveMap(name);
  44331. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  44332. aspectScale == null && (aspectScale = 1);
  44333. invertLongitute = false;
  44334. } else {
  44335. aspectScale == null && (aspectScale = 0.75);
  44336. }
  44337. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  44338. geo.aspectScale = aspectScale;
  44339. geo.zoomLimit = geoModel.get('scaleLimit');
  44340. geoList.push(geo); // setGeoCoords(geo, geoModel);
  44341. geoModel.coordinateSystem = geo;
  44342. geo.model = geoModel; // Inject resize method
  44343. geo.resize = resizeGeo;
  44344. geo.resize(geoModel, api);
  44345. });
  44346. ecModel.eachSeries(function (seriesModel) {
  44347. var coordSys = seriesModel.get('coordinateSystem');
  44348. if (coordSys === 'geo') {
  44349. var geoIndex = seriesModel.get('geoIndex') || 0;
  44350. seriesModel.coordinateSystem = geoList[geoIndex];
  44351. }
  44352. }); // If has map series
  44353. var mapModelGroupBySeries = {};
  44354. ecModel.eachSeriesByType('map', function (seriesModel) {
  44355. if (!seriesModel.getHostGeoModel()) {
  44356. var mapType = seriesModel.getMapType();
  44357. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  44358. mapModelGroupBySeries[mapType].push(seriesModel);
  44359. }
  44360. });
  44361. each(mapModelGroupBySeries, function (mapSeries, mapType) {
  44362. var nameMapList = map(mapSeries, function (singleMapSeries) {
  44363. return singleMapSeries.get('nameMap');
  44364. });
  44365. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  44366. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  44367. return singleMapSeries.get('scaleLimit');
  44368. }));
  44369. geoList.push(geo); // Inject resize method
  44370. geo.resize = resizeGeo;
  44371. geo.aspectScale = mapSeries[0].get('aspectScale');
  44372. geo.resize(mapSeries[0], api);
  44373. each(mapSeries, function (singleMapSeries) {
  44374. singleMapSeries.coordinateSystem = geo;
  44375. setGeoCoords(geo, singleMapSeries);
  44376. });
  44377. });
  44378. return geoList;
  44379. };
  44380. /**
  44381. * Fill given regions array
  44382. */
  44383. GeoCreator.prototype.getFilledRegions = function (originRegionArr, mapName, nameMap) {
  44384. // Not use the original
  44385. var regionsArr = (originRegionArr || []).slice();
  44386. var dataNameMap = createHashMap();
  44387. for (var i = 0; i < regionsArr.length; i++) {
  44388. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  44389. }
  44390. var source = geoSourceManager.load(mapName, nameMap);
  44391. each(source.regions, function (region) {
  44392. var name = region.name;
  44393. !dataNameMap.get(name) && regionsArr.push({
  44394. name: name
  44395. });
  44396. });
  44397. return regionsArr;
  44398. };
  44399. return GeoCreator;
  44400. }();
  44401. var geoCreator = new GeoCreator();
  44402. var GeoModel =
  44403. /** @class */
  44404. function (_super) {
  44405. __extends(GeoModel, _super);
  44406. function GeoModel() {
  44407. var _this = _super !== null && _super.apply(this, arguments) || this;
  44408. _this.type = GeoModel.type;
  44409. return _this;
  44410. }
  44411. GeoModel.prototype.init = function (option, parentModel, ecModel) {
  44412. _super.prototype.init.call(this, option, parentModel, ecModel); // Default label emphasis `show`
  44413. defaultEmphasis(option, 'label', ['show']);
  44414. };
  44415. GeoModel.prototype.optionUpdated = function () {
  44416. var option = this.option;
  44417. var self = this;
  44418. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  44419. var selectedMap = {};
  44420. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  44421. var regionName = regionOpt.name;
  44422. if (regionName) {
  44423. optionModelMap.set(regionName, new Model(regionOpt, self));
  44424. if (regionOpt.selected) {
  44425. selectedMap[regionName] = true;
  44426. }
  44427. }
  44428. return optionModelMap;
  44429. }, createHashMap());
  44430. if (!option.selectedMap) {
  44431. option.selectedMap = selectedMap;
  44432. }
  44433. };
  44434. /**
  44435. * Get model of region.
  44436. */
  44437. GeoModel.prototype.getRegionModel = function (name) {
  44438. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  44439. };
  44440. /**
  44441. * Format label
  44442. * @param name Region name
  44443. */
  44444. GeoModel.prototype.getFormattedLabel = function (name, status) {
  44445. var regionModel = this.getRegionModel(name);
  44446. var formatter = status === 'normal' ? regionModel.get(['label', 'formatter']) : regionModel.get(['emphasis', 'label', 'formatter']);
  44447. var params = {
  44448. name: name
  44449. };
  44450. if (typeof formatter === 'function') {
  44451. params.status = status;
  44452. return formatter(params);
  44453. } else if (typeof formatter === 'string') {
  44454. return formatter.replace('{a}', name != null ? name : '');
  44455. }
  44456. };
  44457. GeoModel.prototype.setZoom = function (zoom) {
  44458. this.option.zoom = zoom;
  44459. };
  44460. GeoModel.prototype.setCenter = function (center) {
  44461. this.option.center = center;
  44462. }; // PENGING If selectedMode is null ?
  44463. GeoModel.prototype.select = function (name) {
  44464. var option = this.option;
  44465. var selectedMode = option.selectedMode;
  44466. if (!selectedMode) {
  44467. return;
  44468. }
  44469. if (selectedMode !== 'multiple') {
  44470. option.selectedMap = null;
  44471. }
  44472. var selectedMap = option.selectedMap || (option.selectedMap = {});
  44473. selectedMap[name] = true;
  44474. };
  44475. GeoModel.prototype.unSelect = function (name) {
  44476. var selectedMap = this.option.selectedMap;
  44477. if (selectedMap) {
  44478. selectedMap[name] = false;
  44479. }
  44480. };
  44481. GeoModel.prototype.toggleSelected = function (name) {
  44482. this[this.isSelected(name) ? 'unSelect' : 'select'](name);
  44483. };
  44484. GeoModel.prototype.isSelected = function (name) {
  44485. var selectedMap = this.option.selectedMap;
  44486. return !!(selectedMap && selectedMap[name]);
  44487. };
  44488. GeoModel.prototype._initSelectedMapFromData = function () {};
  44489. GeoModel.type = 'geo';
  44490. GeoModel.layoutMode = 'box';
  44491. GeoModel.defaultOption = {
  44492. zlevel: 0,
  44493. z: 0,
  44494. show: true,
  44495. left: 'center',
  44496. top: 'center',
  44497. // If svg used, aspectScale is 1 by default.
  44498. // aspectScale: 0.75,
  44499. aspectScale: null,
  44500. ///// Layout with center and size
  44501. // If you wan't to put map in a fixed size box with right aspect ratio
  44502. // This two properties may more conveninet
  44503. // layoutCenter: [50%, 50%]
  44504. // layoutSize: 100
  44505. silent: false,
  44506. // Map type
  44507. map: '',
  44508. // Define left-top, right-bottom coords to control view
  44509. // For example, [ [180, 90], [-180, -90] ]
  44510. boundingCoords: null,
  44511. // Default on center of map
  44512. center: null,
  44513. zoom: 1,
  44514. scaleLimit: null,
  44515. // selectedMode: false
  44516. label: {
  44517. show: false,
  44518. color: '#000'
  44519. },
  44520. itemStyle: {
  44521. // color: 各异,
  44522. borderWidth: 0.5,
  44523. borderColor: '#444',
  44524. color: '#eee'
  44525. },
  44526. emphasis: {
  44527. label: {
  44528. show: true,
  44529. color: 'rgb(100,0,0)'
  44530. },
  44531. itemStyle: {
  44532. color: 'rgba(255,215,0,0.8)'
  44533. }
  44534. },
  44535. select: {
  44536. label: {
  44537. show: true,
  44538. color: 'rgb(100,0,0)'
  44539. },
  44540. itemStyle: {
  44541. color: 'rgba(255,215,0,0.8)'
  44542. }
  44543. },
  44544. regions: []
  44545. };
  44546. return GeoModel;
  44547. }(ComponentModel);
  44548. /*
  44549. * Licensed to the Apache Software Foundation (ASF) under one
  44550. * or more contributor license agreements. See the NOTICE file
  44551. * distributed with this work for additional information
  44552. * regarding copyright ownership. The ASF licenses this file
  44553. * to you under the Apache License, Version 2.0 (the
  44554. * "License"); you may not use this file except in compliance
  44555. * with the License. You may obtain a copy of the License at
  44556. *
  44557. * http://www.apache.org/licenses/LICENSE-2.0
  44558. *
  44559. * Unless required by applicable law or agreed to in writing,
  44560. * software distributed under the License is distributed on an
  44561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44562. * KIND, either express or implied. See the License for the
  44563. * specific language governing permissions and limitations
  44564. * under the License.
  44565. */
  44566. /**
  44567. * AUTO-GENERATED FILE. DO NOT MODIFY.
  44568. */
  44569. /*
  44570. * Licensed to the Apache Software Foundation (ASF) under one
  44571. * or more contributor license agreements. See the NOTICE file
  44572. * distributed with this work for additional information
  44573. * regarding copyright ownership. The ASF licenses this file
  44574. * to you under the Apache License, Version 2.0 (the
  44575. * "License"); you may not use this file except in compliance
  44576. * with the License. You may obtain a copy of the License at
  44577. *
  44578. * http://www.apache.org/licenses/LICENSE-2.0
  44579. *
  44580. * Unless required by applicable law or agreed to in writing,
  44581. * software distributed under the License is distributed on an
  44582. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44583. * KIND, either express or implied. See the License for the
  44584. * specific language governing permissions and limitations
  44585. * under the License.
  44586. */
  44587. function updateCenterAndZoom(view, payload, zoomLimit) {
  44588. var previousZoom = view.getZoom();
  44589. var center = view.getCenter();
  44590. var zoom = payload.zoom;
  44591. var point = view.dataToPoint(center);
  44592. if (payload.dx != null && payload.dy != null) {
  44593. point[0] -= payload.dx;
  44594. point[1] -= payload.dy;
  44595. view.setCenter(view.pointToData(point));
  44596. }
  44597. if (zoom != null) {
  44598. if (zoomLimit) {
  44599. var zoomMin = zoomLimit.min || 0;
  44600. var zoomMax = zoomLimit.max || Infinity;
  44601. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  44602. } // Zoom on given point(originX, originY)
  44603. view.scaleX *= zoom;
  44604. view.scaleY *= zoom;
  44605. var fixX = (payload.originX - view.x) * (zoom - 1);
  44606. var fixY = (payload.originY - view.y) * (zoom - 1);
  44607. view.x -= fixX;
  44608. view.y -= fixY;
  44609. view.updateTransform(); // Get the new center
  44610. view.setCenter(view.pointToData(point));
  44611. view.setZoom(zoom * previousZoom);
  44612. }
  44613. return {
  44614. center: view.getCenter(),
  44615. zoom: view.getZoom()
  44616. };
  44617. }
  44618. var GeoView =
  44619. /** @class */
  44620. function (_super) {
  44621. __extends(GeoView, _super);
  44622. function GeoView() {
  44623. var _this = _super !== null && _super.apply(this, arguments) || this;
  44624. _this.type = GeoView.type;
  44625. return _this;
  44626. }
  44627. GeoView.prototype.init = function (ecModel, api) {
  44628. var mapDraw = new MapDraw(api);
  44629. this._mapDraw = mapDraw;
  44630. this.group.add(mapDraw.group);
  44631. this._api = api;
  44632. };
  44633. GeoView.prototype.render = function (geoModel, ecModel, api, payload) {
  44634. var mapDraw = this._mapDraw;
  44635. if (geoModel.get('show')) {
  44636. mapDraw.draw(geoModel, ecModel, api, this, payload);
  44637. } else {
  44638. this._mapDraw.group.removeAll();
  44639. }
  44640. mapDraw.group.on('click', this._handleRegionClick, this);
  44641. mapDraw.group.silent = geoModel.get('silent');
  44642. this._model = geoModel;
  44643. this.updateSelectStatus(geoModel, ecModel, api);
  44644. };
  44645. GeoView.prototype._handleRegionClick = function (e) {
  44646. var current = e.target;
  44647. var eventData; // TODO extract a util function
  44648. while (current && (eventData = getECData(current).eventData) == null) {
  44649. current = current.__hostTarget || current.parent;
  44650. }
  44651. if (eventData) {
  44652. this._api.dispatchAction({
  44653. type: 'geoToggleSelect',
  44654. geoId: this._model.id,
  44655. name: eventData.name
  44656. });
  44657. }
  44658. };
  44659. GeoView.prototype.updateSelectStatus = function (model, ecModel, api) {
  44660. var _this = this;
  44661. this._mapDraw.group.traverse(function (node) {
  44662. var eventData = getECData(node).eventData;
  44663. if (eventData) {
  44664. _this._model.isSelected(eventData.name) ? api.enterSelect(node) : api.leaveSelect(node); // No need to traverse children.
  44665. return true;
  44666. }
  44667. });
  44668. };
  44669. GeoView.prototype.dispose = function () {
  44670. this._mapDraw && this._mapDraw.remove();
  44671. };
  44672. GeoView.type = 'geo';
  44673. return GeoView;
  44674. }(ComponentView);
  44675. function install$9(registers) {
  44676. registers.registerCoordinateSystem('geo', geoCreator);
  44677. registers.registerComponentModel(GeoModel);
  44678. registers.registerComponentView(GeoView);
  44679. function makeAction(method, actionInfo) {
  44680. actionInfo.update = 'geo:updateSelectStatus';
  44681. registers.registerAction(actionInfo, function (payload, ecModel) {
  44682. var selected = {};
  44683. ecModel.eachComponent({
  44684. mainType: 'geo',
  44685. query: payload
  44686. }, function (geoModel) {
  44687. geoModel[method](payload.name);
  44688. var geo = geoModel.coordinateSystem;
  44689. each(geo.regions, function (region) {
  44690. selected[region.name] = geoModel.isSelected(region.name) || false;
  44691. });
  44692. });
  44693. return {
  44694. selected: selected,
  44695. name: payload.name
  44696. };
  44697. });
  44698. }
  44699. makeAction('toggleSelected', {
  44700. type: 'geoToggleSelect',
  44701. event: 'geoselectchanged'
  44702. });
  44703. makeAction('select', {
  44704. type: 'geoSelect',
  44705. event: 'geoselected'
  44706. });
  44707. makeAction('unSelect', {
  44708. type: 'geoUnSelect',
  44709. event: 'geounselected'
  44710. });
  44711. /**
  44712. * @payload
  44713. * @property {string} [componentType=series]
  44714. * @property {number} [dx]
  44715. * @property {number} [dy]
  44716. * @property {number} [zoom]
  44717. * @property {number} [originX]
  44718. * @property {number} [originY]
  44719. */
  44720. registers.registerAction({
  44721. type: 'geoRoam',
  44722. event: 'geoRoam',
  44723. update: 'updateTransform'
  44724. }, function (payload, ecModel) {
  44725. var componentType = payload.componentType || 'series';
  44726. ecModel.eachComponent({
  44727. mainType: componentType,
  44728. query: payload
  44729. }, function (componentModel) {
  44730. var geo = componentModel.coordinateSystem;
  44731. if (geo.type !== 'geo') {
  44732. return;
  44733. }
  44734. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'));
  44735. componentModel.setCenter && componentModel.setCenter(res.center);
  44736. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  44737. // So the center and zoom must be in sync. Include the series not selected by legend
  44738. if (componentType === 'series') {
  44739. each(componentModel.seriesGroup, function (seriesModel) {
  44740. seriesModel.setCenter(res.center);
  44741. seriesModel.setZoom(res.zoom);
  44742. });
  44743. }
  44744. });
  44745. });
  44746. }
  44747. function install$a(registers) {
  44748. use(install$9);
  44749. registers.registerChartView(MapView);
  44750. registers.registerSeriesModel(MapSeries);
  44751. registers.registerLayout(mapSymbolLayout);
  44752. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  44753. createLegacyDataSelectAction('map', registers.registerAction);
  44754. }
  44755. /**
  44756. * Initialize all computational message for following algorithm.
  44757. */
  44758. function init$2(inRoot) {
  44759. var root = inRoot;
  44760. root.hierNode = {
  44761. defaultAncestor: null,
  44762. ancestor: root,
  44763. prelim: 0,
  44764. modifier: 0,
  44765. change: 0,
  44766. shift: 0,
  44767. i: 0,
  44768. thread: null
  44769. };
  44770. var nodes = [root];
  44771. var node;
  44772. var children;
  44773. while (node = nodes.pop()) {
  44774. // jshint ignore:line
  44775. children = node.children;
  44776. if (node.isExpand && children.length) {
  44777. var n = children.length;
  44778. for (var i = n - 1; i >= 0; i--) {
  44779. var child = children[i];
  44780. child.hierNode = {
  44781. defaultAncestor: null,
  44782. ancestor: child,
  44783. prelim: 0,
  44784. modifier: 0,
  44785. change: 0,
  44786. shift: 0,
  44787. i: i,
  44788. thread: null
  44789. };
  44790. nodes.push(child);
  44791. }
  44792. }
  44793. }
  44794. }
  44795. /**
  44796. * The implementation of this function was originally copied from "d3.js"
  44797. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44798. * with some modifications made for this program.
  44799. * See the license statement at the head of this file.
  44800. *
  44801. * Computes a preliminary x coordinate for node. Before that, this function is
  44802. * applied recursively to the children of node, as well as the function
  44803. * apportion(). After spacing out the children by calling executeShifts(), the
  44804. * node is placed to the midpoint of its outermost children.
  44805. */
  44806. function firstWalk(node, separation) {
  44807. var children = node.isExpand ? node.children : [];
  44808. var siblings = node.parentNode.children;
  44809. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  44810. if (children.length) {
  44811. executeShifts(node);
  44812. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  44813. if (subtreeW) {
  44814. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44815. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  44816. } else {
  44817. node.hierNode.prelim = midPoint;
  44818. }
  44819. } else if (subtreeW) {
  44820. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  44821. }
  44822. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  44823. }
  44824. /**
  44825. * The implementation of this function was originally copied from "d3.js"
  44826. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44827. * with some modifications made for this program.
  44828. * See the license statement at the head of this file.
  44829. *
  44830. * Computes all real x-coordinates by summing up the modifiers recursively.
  44831. */
  44832. function secondWalk(node) {
  44833. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  44834. node.setLayout({
  44835. x: nodeX
  44836. }, true);
  44837. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  44838. }
  44839. function separation(cb) {
  44840. return arguments.length ? cb : defaultSeparation;
  44841. }
  44842. /**
  44843. * Transform the common coordinate to radial coordinate.
  44844. */
  44845. function radialCoordinate(rad, r) {
  44846. rad -= Math.PI / 2;
  44847. return {
  44848. x: r * Math.cos(rad),
  44849. y: r * Math.sin(rad)
  44850. };
  44851. }
  44852. /**
  44853. * Get the layout position of the whole view.
  44854. */
  44855. function getViewRect$1(seriesModel, api) {
  44856. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  44857. width: api.getWidth(),
  44858. height: api.getHeight()
  44859. });
  44860. }
  44861. /**
  44862. * All other shifts, applied to the smaller subtrees between w- and w+, are
  44863. * performed by this function.
  44864. *
  44865. * The implementation of this function was originally copied from "d3.js"
  44866. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44867. * with some modifications made for this program.
  44868. * See the license statement at the head of this file.
  44869. */
  44870. function executeShifts(node) {
  44871. var children = node.children;
  44872. var n = children.length;
  44873. var shift = 0;
  44874. var change = 0;
  44875. while (--n >= 0) {
  44876. var child = children[n];
  44877. child.hierNode.prelim += shift;
  44878. child.hierNode.modifier += shift;
  44879. change += child.hierNode.change;
  44880. shift += child.hierNode.shift + change;
  44881. }
  44882. }
  44883. /**
  44884. * The implementation of this function was originally copied from "d3.js"
  44885. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44886. * with some modifications made for this program.
  44887. * See the license statement at the head of this file.
  44888. *
  44889. * The core of the algorithm. Here, a new subtree is combined with the
  44890. * previous subtrees. Threads are used to traverse the inside and outside
  44891. * contours of the left and right subtree up to the highest common level.
  44892. * Whenever two nodes of the inside contours conflict, we compute the left
  44893. * one of the greatest uncommon ancestors using the function nextAncestor()
  44894. * and call moveSubtree() to shift the subtree and prepare the shifts of
  44895. * smaller subtrees. Finally, we add a new thread (if necessary).
  44896. */
  44897. function apportion(subtreeV, subtreeW, ancestor, separation) {
  44898. if (subtreeW) {
  44899. var nodeOutRight = subtreeV;
  44900. var nodeInRight = subtreeV;
  44901. var nodeOutLeft = nodeInRight.parentNode.children[0];
  44902. var nodeInLeft = subtreeW;
  44903. var sumOutRight = nodeOutRight.hierNode.modifier;
  44904. var sumInRight = nodeInRight.hierNode.modifier;
  44905. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  44906. var sumInLeft = nodeInLeft.hierNode.modifier;
  44907. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  44908. nodeOutRight = nextRight(nodeOutRight);
  44909. nodeOutLeft = nextLeft(nodeOutLeft);
  44910. nodeOutRight.hierNode.ancestor = subtreeV;
  44911. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  44912. if (shift > 0) {
  44913. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  44914. sumInRight += shift;
  44915. sumOutRight += shift;
  44916. }
  44917. sumInLeft += nodeInLeft.hierNode.modifier;
  44918. sumInRight += nodeInRight.hierNode.modifier;
  44919. sumOutRight += nodeOutRight.hierNode.modifier;
  44920. sumOutLeft += nodeOutLeft.hierNode.modifier;
  44921. }
  44922. if (nodeInLeft && !nextRight(nodeOutRight)) {
  44923. nodeOutRight.hierNode.thread = nodeInLeft;
  44924. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  44925. }
  44926. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  44927. nodeOutLeft.hierNode.thread = nodeInRight;
  44928. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  44929. ancestor = subtreeV;
  44930. }
  44931. }
  44932. return ancestor;
  44933. }
  44934. /**
  44935. * This function is used to traverse the right contour of a subtree.
  44936. * It returns the rightmost child of node or the thread of node. The function
  44937. * returns null if and only if node is on the highest depth of its subtree.
  44938. */
  44939. function nextRight(node) {
  44940. var children = node.children;
  44941. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  44942. }
  44943. /**
  44944. * This function is used to traverse the left contour of a subtree (or a subforest).
  44945. * It returns the leftmost child of node or the thread of node. The function
  44946. * returns null if and only if node is on the highest depth of its subtree.
  44947. */
  44948. function nextLeft(node) {
  44949. var children = node.children;
  44950. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  44951. }
  44952. /**
  44953. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  44954. * Otherwise, returns the specified ancestor.
  44955. */
  44956. function nextAncestor(nodeInLeft, node, ancestor) {
  44957. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  44958. }
  44959. /**
  44960. * The implementation of this function was originally copied from "d3.js"
  44961. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44962. * with some modifications made for this program.
  44963. * See the license statement at the head of this file.
  44964. *
  44965. * Shifts the current subtree rooted at wr.
  44966. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  44967. */
  44968. function moveSubtree(wl, wr, shift) {
  44969. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  44970. wr.hierNode.change -= change;
  44971. wr.hierNode.shift += shift;
  44972. wr.hierNode.modifier += shift;
  44973. wr.hierNode.prelim += shift;
  44974. wl.hierNode.change += change;
  44975. }
  44976. /**
  44977. * The implementation of this function was originally copied from "d3.js"
  44978. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  44979. * with some modifications made for this program.
  44980. * See the license statement at the head of this file.
  44981. */
  44982. function defaultSeparation(node1, node2) {
  44983. return node1.parentNode === node2.parentNode ? 1 : 2;
  44984. }
  44985. var TreeEdgeShape =
  44986. /** @class */
  44987. function () {
  44988. function TreeEdgeShape() {
  44989. this.parentPoint = [];
  44990. this.childPoints = [];
  44991. }
  44992. return TreeEdgeShape;
  44993. }();
  44994. var TreePath =
  44995. /** @class */
  44996. function (_super) {
  44997. __extends(TreePath, _super);
  44998. function TreePath(opts) {
  44999. return _super.call(this, opts) || this;
  45000. }
  45001. TreePath.prototype.getDefaultStyle = function () {
  45002. return {
  45003. stroke: '#000',
  45004. fill: null
  45005. };
  45006. };
  45007. TreePath.prototype.getDefaultShape = function () {
  45008. return new TreeEdgeShape();
  45009. };
  45010. TreePath.prototype.buildPath = function (ctx, shape) {
  45011. var childPoints = shape.childPoints;
  45012. var childLen = childPoints.length;
  45013. var parentPoint = shape.parentPoint;
  45014. var firstChildPos = childPoints[0];
  45015. var lastChildPos = childPoints[childLen - 1];
  45016. if (childLen === 1) {
  45017. ctx.moveTo(parentPoint[0], parentPoint[1]);
  45018. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  45019. return;
  45020. }
  45021. var orient = shape.orient;
  45022. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  45023. var otherDim = 1 - forkDim;
  45024. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  45025. var tmpPoint = [];
  45026. tmpPoint[forkDim] = parentPoint[forkDim];
  45027. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  45028. ctx.moveTo(parentPoint[0], parentPoint[1]);
  45029. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45030. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  45031. tmpPoint[forkDim] = firstChildPos[forkDim];
  45032. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45033. tmpPoint[forkDim] = lastChildPos[forkDim];
  45034. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45035. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  45036. for (var i = 1; i < childLen - 1; i++) {
  45037. var point = childPoints[i];
  45038. ctx.moveTo(point[0], point[1]);
  45039. tmpPoint[forkDim] = point[forkDim];
  45040. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  45041. }
  45042. };
  45043. return TreePath;
  45044. }(Path);
  45045. var TreeView =
  45046. /** @class */
  45047. function (_super) {
  45048. __extends(TreeView, _super);
  45049. function TreeView() {
  45050. var _this = _super !== null && _super.apply(this, arguments) || this;
  45051. _this.type = TreeView.type;
  45052. _this._mainGroup = new Group();
  45053. return _this;
  45054. }
  45055. TreeView.prototype.init = function (ecModel, api) {
  45056. this._controller = new RoamController(api.getZr());
  45057. this._controllerHost = {
  45058. target: this.group
  45059. };
  45060. this.group.add(this._mainGroup);
  45061. };
  45062. TreeView.prototype.render = function (seriesModel, ecModel, api) {
  45063. var data = seriesModel.getData();
  45064. var layoutInfo = seriesModel.layoutInfo;
  45065. var group = this._mainGroup;
  45066. var layout = seriesModel.get('layout');
  45067. if (layout === 'radial') {
  45068. group.x = layoutInfo.x + layoutInfo.width / 2;
  45069. group.y = layoutInfo.y + layoutInfo.height / 2;
  45070. } else {
  45071. group.x = layoutInfo.x;
  45072. group.y = layoutInfo.y;
  45073. }
  45074. this._updateViewCoordSys(seriesModel);
  45075. this._updateController(seriesModel, ecModel, api);
  45076. var oldData = this._data;
  45077. data.diff(oldData).add(function (newIdx) {
  45078. if (symbolNeedsDraw$1(data, newIdx)) {
  45079. // Create node and edge
  45080. updateNode(data, newIdx, null, group, seriesModel);
  45081. }
  45082. }).update(function (newIdx, oldIdx) {
  45083. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  45084. if (!symbolNeedsDraw$1(data, newIdx)) {
  45085. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  45086. return;
  45087. } // Update node and edge
  45088. updateNode(data, newIdx, symbolEl, group, seriesModel);
  45089. }).remove(function (oldIdx) {
  45090. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  45091. // node haven't been initialized with a symbol element,
  45092. // you can't found it's symbol element through index.
  45093. // so if we want to remove the symbol element we should insure
  45094. // that the symbol element is not null.
  45095. if (symbolEl) {
  45096. removeNode(oldData, oldIdx, symbolEl, group, seriesModel);
  45097. }
  45098. }).execute();
  45099. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  45100. this._updateNodeAndLinkScale(seriesModel);
  45101. if (seriesModel.get('expandAndCollapse') === true) {
  45102. data.eachItemGraphicEl(function (el, dataIndex) {
  45103. el.off('click').on('click', function () {
  45104. api.dispatchAction({
  45105. type: 'treeExpandAndCollapse',
  45106. seriesId: seriesModel.id,
  45107. dataIndex: dataIndex
  45108. });
  45109. });
  45110. });
  45111. }
  45112. this._data = data;
  45113. };
  45114. TreeView.prototype._updateViewCoordSys = function (seriesModel) {
  45115. var data = seriesModel.getData();
  45116. var points = [];
  45117. data.each(function (idx) {
  45118. var layout = data.getItemLayout(idx);
  45119. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  45120. points.push([+layout.x, +layout.y]);
  45121. }
  45122. });
  45123. var min = [];
  45124. var max = [];
  45125. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  45126. // the root node will disappear.
  45127. var oldMin = this._min;
  45128. var oldMax = this._max; // If width or height is 0
  45129. if (max[0] - min[0] === 0) {
  45130. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  45131. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  45132. }
  45133. if (max[1] - min[1] === 0) {
  45134. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  45135. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  45136. }
  45137. var viewCoordSys = seriesModel.coordinateSystem = new View();
  45138. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  45139. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  45140. viewCoordSys.setCenter(seriesModel.get('center'));
  45141. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  45142. this.group.attr({
  45143. x: viewCoordSys.x,
  45144. y: viewCoordSys.y,
  45145. scaleX: viewCoordSys.scaleX,
  45146. scaleY: viewCoordSys.scaleY
  45147. });
  45148. this._min = min;
  45149. this._max = max;
  45150. };
  45151. TreeView.prototype._updateController = function (seriesModel, ecModel, api) {
  45152. var _this = this;
  45153. var controller = this._controller;
  45154. var controllerHost = this._controllerHost;
  45155. var group = this.group;
  45156. controller.setPointerChecker(function (e, x, y) {
  45157. var rect = group.getBoundingRect();
  45158. rect.applyTransform(group.transform);
  45159. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  45160. });
  45161. controller.enable(seriesModel.get('roam'));
  45162. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  45163. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  45164. controller.off('pan').off('zoom').on('pan', function (e) {
  45165. updateViewOnPan(controllerHost, e.dx, e.dy);
  45166. api.dispatchAction({
  45167. seriesId: seriesModel.id,
  45168. type: 'treeRoam',
  45169. dx: e.dx,
  45170. dy: e.dy
  45171. });
  45172. }).on('zoom', function (e) {
  45173. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  45174. api.dispatchAction({
  45175. seriesId: seriesModel.id,
  45176. type: 'treeRoam',
  45177. zoom: e.scale,
  45178. originX: e.originX,
  45179. originY: e.originY
  45180. });
  45181. _this._updateNodeAndLinkScale(seriesModel); // Only update label layout on zoom
  45182. api.updateLabelLayout();
  45183. });
  45184. };
  45185. TreeView.prototype._updateNodeAndLinkScale = function (seriesModel) {
  45186. var data = seriesModel.getData();
  45187. var nodeScale = this._getNodeGlobalScale(seriesModel);
  45188. data.eachItemGraphicEl(function (el, idx) {
  45189. el.setSymbolScale(nodeScale);
  45190. });
  45191. };
  45192. TreeView.prototype._getNodeGlobalScale = function (seriesModel) {
  45193. var coordSys = seriesModel.coordinateSystem;
  45194. if (coordSys.type !== 'view') {
  45195. return 1;
  45196. }
  45197. var nodeScaleRatio = this._nodeScaleRatio;
  45198. var groupZoom = coordSys.scaleX || 1; // Scale node when zoom changes
  45199. var roamZoom = coordSys.getZoom();
  45200. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  45201. return nodeScale / groupZoom;
  45202. };
  45203. TreeView.prototype.dispose = function () {
  45204. this._controller && this._controller.dispose();
  45205. this._controllerHost = null;
  45206. };
  45207. TreeView.prototype.remove = function () {
  45208. this._mainGroup.removeAll();
  45209. this._data = null;
  45210. };
  45211. TreeView.type = 'tree';
  45212. return TreeView;
  45213. }(ChartView);
  45214. function symbolNeedsDraw$1(data, dataIndex) {
  45215. var layout = data.getItemLayout(dataIndex);
  45216. return layout && !isNaN(layout.x) && !isNaN(layout.y);
  45217. }
  45218. function updateNode(data, dataIndex, symbolEl, group, seriesModel) {
  45219. var isInit = !symbolEl;
  45220. var node = data.tree.getNodeByDataIndex(dataIndex);
  45221. var itemModel = node.getModel();
  45222. var visualColor = node.getVisual('style').fill;
  45223. var symbolInnerColor = node.isExpand === false && node.children.length !== 0 ? visualColor : '#fff';
  45224. var virtualRoot = data.tree.root;
  45225. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  45226. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  45227. var sourceLayout = source.getLayout();
  45228. var sourceOldLayout = sourceSymbolEl ? {
  45229. x: sourceSymbolEl.__oldX,
  45230. y: sourceSymbolEl.__oldY,
  45231. rawX: sourceSymbolEl.__radialOldRawX,
  45232. rawY: sourceSymbolEl.__radialOldRawY
  45233. } : sourceLayout;
  45234. var targetLayout = node.getLayout();
  45235. if (isInit) {
  45236. symbolEl = new Symbol(data, dataIndex, null, {
  45237. symbolInnerColor: symbolInnerColor,
  45238. useNameLabel: true
  45239. });
  45240. symbolEl.x = sourceOldLayout.x;
  45241. symbolEl.y = sourceOldLayout.y;
  45242. } else {
  45243. symbolEl.updateData(data, dataIndex, null, {
  45244. symbolInnerColor: symbolInnerColor,
  45245. useNameLabel: true
  45246. });
  45247. }
  45248. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  45249. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  45250. symbolEl.__radialRawX = targetLayout.rawX;
  45251. symbolEl.__radialRawY = targetLayout.rawY;
  45252. group.add(symbolEl);
  45253. data.setItemGraphicEl(dataIndex, symbolEl);
  45254. symbolEl.__oldX = symbolEl.x;
  45255. symbolEl.__oldY = symbolEl.y;
  45256. updateProps(symbolEl, {
  45257. x: targetLayout.x,
  45258. y: targetLayout.y
  45259. }, seriesModel);
  45260. var symbolPath = symbolEl.getSymbolPath();
  45261. if (seriesModel.get('layout') === 'radial') {
  45262. var realRoot = virtualRoot.children[0];
  45263. var rootLayout = realRoot.getLayout();
  45264. var length_1 = realRoot.children.length;
  45265. var rad = void 0;
  45266. var isLeft = void 0;
  45267. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  45268. var center = {
  45269. x: (realRoot.children[0].getLayout().x + realRoot.children[length_1 - 1].getLayout().x) / 2,
  45270. y: (realRoot.children[0].getLayout().y + realRoot.children[length_1 - 1].getLayout().y) / 2
  45271. };
  45272. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  45273. if (rad < 0) {
  45274. rad = Math.PI * 2 + rad;
  45275. }
  45276. isLeft = center.x < rootLayout.x;
  45277. if (isLeft) {
  45278. rad = rad - Math.PI;
  45279. }
  45280. } else {
  45281. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  45282. if (rad < 0) {
  45283. rad = Math.PI * 2 + rad;
  45284. }
  45285. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  45286. isLeft = targetLayout.x < rootLayout.x;
  45287. if (isLeft) {
  45288. rad = rad - Math.PI;
  45289. }
  45290. } else {
  45291. isLeft = targetLayout.x > rootLayout.x;
  45292. if (!isLeft) {
  45293. rad = rad - Math.PI;
  45294. }
  45295. }
  45296. }
  45297. var textPosition = isLeft ? 'left' : 'right';
  45298. var normalLabelModel = itemModel.getModel('label');
  45299. var rotate = normalLabelModel.get('rotate');
  45300. var labelRotateRadian = rotate * (Math.PI / 180);
  45301. var textContent = symbolPath.getTextContent();
  45302. if (textContent) {
  45303. symbolPath.setTextConfig({
  45304. position: normalLabelModel.get('position') || textPosition,
  45305. rotation: rotate == null ? -rad : labelRotateRadian,
  45306. origin: 'center'
  45307. });
  45308. textContent.setStyle('verticalAlign', 'middle');
  45309. }
  45310. } // Handle status
  45311. var focus = itemModel.get(['emphasis', 'focus']);
  45312. var focusDataIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  45313. if (focusDataIndices) {
  45314. // Modify the focus to data indices.
  45315. getECData(symbolEl).focus = focusDataIndices;
  45316. }
  45317. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group);
  45318. if (symbolEl.__edge) {
  45319. symbolEl.onHoverStateChange = function (toState) {
  45320. if (toState !== 'blur') {
  45321. // NOTE: Ensure the parent elements will been blurred firstly.
  45322. // According to the return of getAncestorsIndices and getDescendantIndices
  45323. // TODO: A bit tricky.
  45324. var parentEl = node.parentNode && data.getItemGraphicEl(node.parentNode.dataIndex);
  45325. if (!(parentEl && parentEl.hoverState === HOVER_STATE_BLUR)) {
  45326. setStatesFlag(symbolEl.__edge, toState);
  45327. }
  45328. }
  45329. };
  45330. }
  45331. }
  45332. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group) {
  45333. var itemModel = node.getModel();
  45334. var edgeShape = seriesModel.get('edgeShape');
  45335. var layout = seriesModel.get('layout');
  45336. var orient = seriesModel.getOrient();
  45337. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  45338. var edgeForkPosition = seriesModel.get('edgeForkPosition');
  45339. var lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  45340. var edge = symbolEl.__edge;
  45341. if (edgeShape === 'curve') {
  45342. if (node.parentNode && node.parentNode !== virtualRoot) {
  45343. if (!edge) {
  45344. edge = symbolEl.__edge = new BezierCurve({
  45345. shape: getEdgeShape(layout, orient, curvature, sourceOldLayout, sourceOldLayout)
  45346. });
  45347. }
  45348. updateProps(edge, {
  45349. shape: getEdgeShape(layout, orient, curvature, sourceLayout, targetLayout)
  45350. }, seriesModel);
  45351. }
  45352. } else if (edgeShape === 'polyline') {
  45353. if (layout === 'orthogonal') {
  45354. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  45355. var children = node.children;
  45356. var childPoints = [];
  45357. for (var i = 0; i < children.length; i++) {
  45358. var childLayout = children[i].getLayout();
  45359. childPoints.push([childLayout.x, childLayout.y]);
  45360. }
  45361. if (!edge) {
  45362. edge = symbolEl.__edge = new TreePath({
  45363. shape: {
  45364. parentPoint: [targetLayout.x, targetLayout.y],
  45365. childPoints: [[targetLayout.x, targetLayout.y]],
  45366. orient: orient,
  45367. forkPosition: edgeForkPosition
  45368. }
  45369. });
  45370. }
  45371. updateProps(edge, {
  45372. shape: {
  45373. parentPoint: [targetLayout.x, targetLayout.y],
  45374. childPoints: childPoints
  45375. }
  45376. }, seriesModel);
  45377. }
  45378. } else {
  45379. if ("development" !== 'production') {
  45380. throw new Error('The polyline edgeShape can only be used in orthogonal layout');
  45381. }
  45382. }
  45383. }
  45384. if (edge) {
  45385. edge.useStyle(defaults({
  45386. strokeNoScale: true,
  45387. fill: null
  45388. }, lineStyle));
  45389. setStatesStylesFromModel(edge, itemModel, 'lineStyle');
  45390. setDefaultStateProxy(edge);
  45391. group.add(edge);
  45392. }
  45393. }
  45394. function removeNode(data, dataIndex, symbolEl, group, seriesModel) {
  45395. var node = data.tree.getNodeByDataIndex(dataIndex);
  45396. var virtualRoot = data.tree.root;
  45397. var source = node.parentNode === virtualRoot ? node : node.parentNode || node; // let edgeShape = seriesScope.edgeShape;
  45398. var sourceLayout;
  45399. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  45400. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  45401. } // Use same duration and easing with update to have more consistent animation.
  45402. var removeAnimationOpt = {
  45403. duration: seriesModel.get('animationDurationUpdate'),
  45404. easing: seriesModel.get('animationEasingUpdate')
  45405. };
  45406. removeElement(symbolEl, {
  45407. x: sourceLayout.x + 1,
  45408. y: sourceLayout.y + 1
  45409. }, seriesModel, {
  45410. cb: function () {
  45411. group.remove(symbolEl);
  45412. data.setItemGraphicEl(dataIndex, null);
  45413. },
  45414. removeOpt: removeAnimationOpt
  45415. });
  45416. symbolEl.fadeOut(null, {
  45417. fadeLabel: true,
  45418. animation: removeAnimationOpt
  45419. });
  45420. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  45421. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  45422. // the source at the same time. because the polyline edge shape is only owned by the source.
  45423. // 2.when the node is the only children of the source, delete the node should delete the edge of
  45424. // the source at the same time. the same reason as above.
  45425. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  45426. var edgeShape = seriesModel.get('edgeShape');
  45427. var layoutOpt = seriesModel.get('layout');
  45428. var orient = seriesModel.get('orient');
  45429. var curvature = seriesModel.get(['lineStyle', 'curveness']);
  45430. if (edge) {
  45431. if (edgeShape === 'curve') {
  45432. removeElement(edge, {
  45433. shape: getEdgeShape(layoutOpt, orient, curvature, sourceLayout, sourceLayout),
  45434. style: {
  45435. opacity: 0
  45436. }
  45437. }, seriesModel, {
  45438. cb: function () {
  45439. group.remove(edge);
  45440. },
  45441. removeOpt: removeAnimationOpt
  45442. });
  45443. } else if (edgeShape === 'polyline' && seriesModel.get('layout') === 'orthogonal') {
  45444. removeElement(edge, {
  45445. shape: {
  45446. parentPoint: [sourceLayout.x, sourceLayout.y],
  45447. childPoints: [[sourceLayout.x, sourceLayout.y]]
  45448. },
  45449. style: {
  45450. opacity: 0
  45451. }
  45452. }, seriesModel, {
  45453. cb: function () {
  45454. group.remove(edge);
  45455. },
  45456. removeOpt: removeAnimationOpt
  45457. });
  45458. }
  45459. }
  45460. }
  45461. function getEdgeShape(layoutOpt, orient, curvature, sourceLayout, targetLayout) {
  45462. var cpx1;
  45463. var cpy1;
  45464. var cpx2;
  45465. var cpy2;
  45466. var x1;
  45467. var x2;
  45468. var y1;
  45469. var y2;
  45470. if (layoutOpt === 'radial') {
  45471. x1 = sourceLayout.rawX;
  45472. y1 = sourceLayout.rawY;
  45473. x2 = targetLayout.rawX;
  45474. y2 = targetLayout.rawY;
  45475. var radialCoor1 = radialCoordinate(x1, y1);
  45476. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * curvature);
  45477. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * curvature);
  45478. var radialCoor4 = radialCoordinate(x2, y2);
  45479. return {
  45480. x1: radialCoor1.x || 0,
  45481. y1: radialCoor1.y || 0,
  45482. x2: radialCoor4.x || 0,
  45483. y2: radialCoor4.y || 0,
  45484. cpx1: radialCoor2.x || 0,
  45485. cpy1: radialCoor2.y || 0,
  45486. cpx2: radialCoor3.x || 0,
  45487. cpy2: radialCoor3.y || 0
  45488. };
  45489. } else {
  45490. x1 = sourceLayout.x;
  45491. y1 = sourceLayout.y;
  45492. x2 = targetLayout.x;
  45493. y2 = targetLayout.y;
  45494. if (orient === 'LR' || orient === 'RL') {
  45495. cpx1 = x1 + (x2 - x1) * curvature;
  45496. cpy1 = y1;
  45497. cpx2 = x2 + (x1 - x2) * curvature;
  45498. cpy2 = y2;
  45499. }
  45500. if (orient === 'TB' || orient === 'BT') {
  45501. cpx1 = x1;
  45502. cpy1 = y1 + (y2 - y1) * curvature;
  45503. cpx2 = x2;
  45504. cpy2 = y2 + (y1 - y2) * curvature;
  45505. }
  45506. }
  45507. return {
  45508. x1: x1,
  45509. y1: y1,
  45510. x2: x2,
  45511. y2: y2,
  45512. cpx1: cpx1,
  45513. cpy1: cpy1,
  45514. cpx2: cpx2,
  45515. cpy2: cpy2
  45516. };
  45517. }
  45518. var inner$8 = makeInner();
  45519. function linkList(opt) {
  45520. var mainData = opt.mainData;
  45521. var datas = opt.datas;
  45522. if (!datas) {
  45523. datas = {
  45524. main: mainData
  45525. };
  45526. opt.datasAttr = {
  45527. main: 'data'
  45528. };
  45529. }
  45530. opt.datas = opt.mainData = null;
  45531. linkAll(mainData, datas, opt); // Porxy data original methods.
  45532. each(datas, function (data) {
  45533. each(mainData.TRANSFERABLE_METHODS, function (methodName) {
  45534. data.wrapMethod(methodName, curry(transferInjection, opt));
  45535. });
  45536. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  45537. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  45538. // another changable methods, which may bring about dead lock.
  45539. each(mainData.CHANGABLE_METHODS, function (methodName) {
  45540. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  45541. }); // Make sure datas contains mainData.
  45542. assert(datas[mainData.dataType] === mainData);
  45543. }
  45544. function transferInjection(opt, res) {
  45545. if (isMainData(this)) {
  45546. // Transfer datas to new main data.
  45547. var datas = extend({}, inner$8(this).datas);
  45548. datas[this.dataType] = res;
  45549. linkAll(res, datas, opt);
  45550. } else {
  45551. // Modify the reference in main data to point newData.
  45552. linkSingle(res, this.dataType, inner$8(this).mainData, opt);
  45553. }
  45554. return res;
  45555. }
  45556. function changeInjection(opt, res) {
  45557. opt.struct && opt.struct.update();
  45558. return res;
  45559. }
  45560. function cloneShallowInjection(opt, res) {
  45561. // cloneShallow, which brings about some fragilities, may be inappropriate
  45562. // to be exposed as an API. So for implementation simplicity we can make
  45563. // the restriction that cloneShallow of not-mainData should not be invoked
  45564. // outside, but only be invoked here.
  45565. each(inner$8(res).datas, function (data, dataType) {
  45566. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  45567. });
  45568. return res;
  45569. }
  45570. /**
  45571. * Supplement method to List.
  45572. *
  45573. * @public
  45574. * @param [dataType] If not specified, return mainData.
  45575. */
  45576. function getLinkedData(dataType) {
  45577. var mainData = inner$8(this).mainData;
  45578. return dataType == null || mainData == null ? mainData : inner$8(mainData).datas[dataType];
  45579. }
  45580. /**
  45581. * Get list of all linked data
  45582. */
  45583. function getLinkedDataAll() {
  45584. var mainData = inner$8(this).mainData;
  45585. return mainData == null ? [{
  45586. data: mainData
  45587. }] : map(keys(inner$8(mainData).datas), function (type) {
  45588. return {
  45589. type: type,
  45590. data: inner$8(mainData).datas[type]
  45591. };
  45592. });
  45593. }
  45594. function isMainData(data) {
  45595. return inner$8(data).mainData === data;
  45596. }
  45597. function linkAll(mainData, datas, opt) {
  45598. inner$8(mainData).datas = {};
  45599. each(datas, function (data, dataType) {
  45600. linkSingle(data, dataType, mainData, opt);
  45601. });
  45602. }
  45603. function linkSingle(data, dataType, mainData, opt) {
  45604. inner$8(mainData).datas[dataType] = data;
  45605. inner$8(data).mainData = mainData;
  45606. data.dataType = dataType;
  45607. if (opt.struct) {
  45608. data[opt.structAttr] = opt.struct;
  45609. opt.struct[opt.datasAttr[dataType]] = data;
  45610. } // Supplement method.
  45611. data.getLinkedData = getLinkedData;
  45612. data.getLinkedDataAll = getLinkedDataAll;
  45613. }
  45614. var TreeNode =
  45615. /** @class */
  45616. function () {
  45617. function TreeNode(name, hostTree) {
  45618. this.depth = 0;
  45619. this.height = 0;
  45620. /**
  45621. * Reference to list item.
  45622. * Do not persistent dataIndex outside,
  45623. * besause it may be changed by list.
  45624. * If dataIndex -1,
  45625. * this node is logical deleted (filtered) in list.
  45626. */
  45627. this.dataIndex = -1;
  45628. this.children = [];
  45629. this.viewChildren = [];
  45630. this.isExpand = false;
  45631. this.name = name || '';
  45632. this.hostTree = hostTree;
  45633. }
  45634. /**
  45635. * The node is removed.
  45636. */
  45637. TreeNode.prototype.isRemoved = function () {
  45638. return this.dataIndex < 0;
  45639. };
  45640. TreeNode.prototype.eachNode = function (options, cb, context) {
  45641. if (typeof options === 'function') {
  45642. context = cb;
  45643. cb = options;
  45644. options = null;
  45645. }
  45646. options = options || {};
  45647. if (isString(options)) {
  45648. options = {
  45649. order: options
  45650. };
  45651. }
  45652. var order = options.order || 'preorder';
  45653. var children = this[options.attr || 'children'];
  45654. var suppressVisitSub;
  45655. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  45656. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  45657. children[i].eachNode(options, cb, context);
  45658. }
  45659. order === 'postorder' && cb.call(context, this);
  45660. };
  45661. /**
  45662. * Update depth and height of this subtree.
  45663. */
  45664. TreeNode.prototype.updateDepthAndHeight = function (depth) {
  45665. var height = 0;
  45666. this.depth = depth;
  45667. for (var i = 0; i < this.children.length; i++) {
  45668. var child = this.children[i];
  45669. child.updateDepthAndHeight(depth + 1);
  45670. if (child.height > height) {
  45671. height = child.height;
  45672. }
  45673. }
  45674. this.height = height + 1;
  45675. };
  45676. TreeNode.prototype.getNodeById = function (id) {
  45677. if (this.getId() === id) {
  45678. return this;
  45679. }
  45680. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  45681. var res = children[i].getNodeById(id);
  45682. if (res) {
  45683. return res;
  45684. }
  45685. }
  45686. };
  45687. TreeNode.prototype.contains = function (node) {
  45688. if (node === this) {
  45689. return true;
  45690. }
  45691. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  45692. var res = children[i].contains(node);
  45693. if (res) {
  45694. return res;
  45695. }
  45696. }
  45697. };
  45698. /**
  45699. * @param includeSelf Default false.
  45700. * @return order: [root, child, grandchild, ...]
  45701. */
  45702. TreeNode.prototype.getAncestors = function (includeSelf) {
  45703. var ancestors = [];
  45704. var node = includeSelf ? this : this.parentNode;
  45705. while (node) {
  45706. ancestors.push(node);
  45707. node = node.parentNode;
  45708. }
  45709. ancestors.reverse();
  45710. return ancestors;
  45711. };
  45712. TreeNode.prototype.getAncestorsIndices = function () {
  45713. var indices = [];
  45714. var currNode = this;
  45715. while (currNode) {
  45716. indices.push(currNode.dataIndex);
  45717. currNode = currNode.parentNode;
  45718. }
  45719. indices.reverse();
  45720. return indices;
  45721. };
  45722. TreeNode.prototype.getDescendantIndices = function () {
  45723. var indices = [];
  45724. this.eachNode(function (childNode) {
  45725. indices.push(childNode.dataIndex);
  45726. });
  45727. return indices;
  45728. };
  45729. TreeNode.prototype.getValue = function (dimension) {
  45730. var data = this.hostTree.data;
  45731. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  45732. };
  45733. TreeNode.prototype.setLayout = function (layout, merge) {
  45734. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
  45735. };
  45736. /**
  45737. * @return {Object} layout
  45738. */
  45739. TreeNode.prototype.getLayout = function () {
  45740. return this.hostTree.data.getItemLayout(this.dataIndex);
  45741. }; // @depcrecated
  45742. // getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
  45743. TreeNode.prototype.getModel = function (path) {
  45744. if (this.dataIndex < 0) {
  45745. return;
  45746. }
  45747. var hostTree = this.hostTree;
  45748. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  45749. return itemModel.getModel(path);
  45750. }; // TODO: TYPE More specific model
  45751. TreeNode.prototype.getLevelModel = function () {
  45752. return (this.hostTree.levelModels || [])[this.depth];
  45753. };
  45754. TreeNode.prototype.setVisual = function (key, value) {
  45755. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  45756. };
  45757. /**
  45758. * Get item visual
  45759. */
  45760. TreeNode.prototype.getVisual = function (key) {
  45761. return this.hostTree.data.getItemVisual(this.dataIndex, key);
  45762. };
  45763. TreeNode.prototype.getRawIndex = function () {
  45764. return this.hostTree.data.getRawIndex(this.dataIndex);
  45765. };
  45766. TreeNode.prototype.getId = function () {
  45767. return this.hostTree.data.getId(this.dataIndex);
  45768. };
  45769. /**
  45770. * if this is an ancestor of another node
  45771. *
  45772. * @param node another node
  45773. * @return if is ancestor
  45774. */
  45775. TreeNode.prototype.isAncestorOf = function (node) {
  45776. var parent = node.parentNode;
  45777. while (parent) {
  45778. if (parent === this) {
  45779. return true;
  45780. }
  45781. parent = parent.parentNode;
  45782. }
  45783. return false;
  45784. };
  45785. /**
  45786. * if this is an descendant of another node
  45787. *
  45788. * @param node another node
  45789. * @return if is descendant
  45790. */
  45791. TreeNode.prototype.isDescendantOf = function (node) {
  45792. return node !== this && node.isAncestorOf(this);
  45793. };
  45794. return TreeNode;
  45795. }();
  45796. var Tree =
  45797. /** @class */
  45798. function () {
  45799. function Tree(hostModel) {
  45800. this.type = 'tree';
  45801. this._nodes = [];
  45802. this.hostModel = hostModel;
  45803. }
  45804. Tree.prototype.eachNode = function (options, cb, context) {
  45805. this.root.eachNode(options, cb, context);
  45806. };
  45807. Tree.prototype.getNodeByDataIndex = function (dataIndex) {
  45808. var rawIndex = this.data.getRawIndex(dataIndex);
  45809. return this._nodes[rawIndex];
  45810. };
  45811. Tree.prototype.getNodeById = function (name) {
  45812. return this.root.getNodeById(name);
  45813. };
  45814. /**
  45815. * Update item available by list,
  45816. * when list has been performed options like 'filterSelf' or 'map'.
  45817. */
  45818. Tree.prototype.update = function () {
  45819. var data = this.data;
  45820. var nodes = this._nodes;
  45821. for (var i = 0, len = nodes.length; i < len; i++) {
  45822. nodes[i].dataIndex = -1;
  45823. }
  45824. for (var i = 0, len = data.count(); i < len; i++) {
  45825. nodes[data.getRawIndex(i)].dataIndex = i;
  45826. }
  45827. };
  45828. /**
  45829. * Clear all layouts
  45830. */
  45831. Tree.prototype.clearLayouts = function () {
  45832. this.data.clearItemLayouts();
  45833. };
  45834. /**
  45835. * data node format:
  45836. * {
  45837. * name: ...
  45838. * value: ...
  45839. * children: [
  45840. * {
  45841. * name: ...
  45842. * value: ...
  45843. * children: ...
  45844. * },
  45845. * ...
  45846. * ]
  45847. * }
  45848. */
  45849. Tree.createTree = function (dataRoot, hostModel, beforeLink) {
  45850. var tree = new Tree(hostModel);
  45851. var listData = [];
  45852. var dimMax = 1;
  45853. buildHierarchy(dataRoot);
  45854. function buildHierarchy(dataNode, parentNode) {
  45855. var value = dataNode.value;
  45856. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  45857. listData.push(dataNode);
  45858. var node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
  45859. parentNode ? addChild(node, parentNode) : tree.root = node;
  45860. tree._nodes.push(node);
  45861. var children = dataNode.children;
  45862. if (children) {
  45863. for (var i = 0; i < children.length; i++) {
  45864. buildHierarchy(children[i], node);
  45865. }
  45866. }
  45867. }
  45868. tree.root.updateDepthAndHeight(0);
  45869. var dimensionsInfo = createDimensions(listData, {
  45870. coordDimensions: ['value'],
  45871. dimensionsCount: dimMax
  45872. });
  45873. var list = new List(dimensionsInfo, hostModel);
  45874. list.initData(listData);
  45875. beforeLink && beforeLink(list);
  45876. linkList({
  45877. mainData: list,
  45878. struct: tree,
  45879. structAttr: 'tree'
  45880. });
  45881. tree.update();
  45882. return tree;
  45883. };
  45884. return Tree;
  45885. }();
  45886. /**
  45887. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  45888. * so this function is not ready and not necessary to be public.
  45889. */
  45890. function addChild(child, node) {
  45891. var children = node.children;
  45892. if (child.parentNode === node) {
  45893. return;
  45894. }
  45895. children.push(child);
  45896. child.parentNode = node;
  45897. }
  45898. var TreeSeriesModel =
  45899. /** @class */
  45900. function (_super) {
  45901. __extends(TreeSeriesModel, _super);
  45902. function TreeSeriesModel() {
  45903. var _this = _super !== null && _super.apply(this, arguments) || this;
  45904. _this.hasSymbolVisual = true; // Do it self.
  45905. _this.ignoreStyleOnData = true;
  45906. return _this;
  45907. }
  45908. /**
  45909. * Init a tree data structure from data in option series
  45910. * @param option the object used to config echarts view
  45911. * @return storage initial data
  45912. */
  45913. TreeSeriesModel.prototype.getInitialData = function (option) {
  45914. //create an virtual root
  45915. var root = {
  45916. name: option.name,
  45917. children: option.data
  45918. };
  45919. var leaves = option.leaves || {};
  45920. var leavesModel = new Model(leaves, this, this.ecModel);
  45921. var tree = Tree.createTree(root, this, beforeLink);
  45922. function beforeLink(nodeData) {
  45923. nodeData.wrapMethod('getItemModel', function (model, idx) {
  45924. var node = tree.getNodeByDataIndex(idx);
  45925. if (!node.children.length || !node.isExpand) {
  45926. model.parentModel = leavesModel;
  45927. }
  45928. return model;
  45929. });
  45930. }
  45931. var treeDepth = 0;
  45932. tree.eachNode('preorder', function (node) {
  45933. if (node.depth > treeDepth) {
  45934. treeDepth = node.depth;
  45935. }
  45936. });
  45937. var expandAndCollapse = option.expandAndCollapse;
  45938. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  45939. tree.root.eachNode('preorder', function (node) {
  45940. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  45941. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  45942. });
  45943. return tree.data;
  45944. };
  45945. /**
  45946. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  45947. * @returns {string} orient
  45948. */
  45949. TreeSeriesModel.prototype.getOrient = function () {
  45950. var orient = this.get('orient');
  45951. if (orient === 'horizontal') {
  45952. orient = 'LR';
  45953. } else if (orient === 'vertical') {
  45954. orient = 'TB';
  45955. }
  45956. return orient;
  45957. };
  45958. TreeSeriesModel.prototype.setZoom = function (zoom) {
  45959. this.option.zoom = zoom;
  45960. };
  45961. TreeSeriesModel.prototype.setCenter = function (center) {
  45962. this.option.center = center;
  45963. };
  45964. TreeSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  45965. var tree = this.getData().tree;
  45966. var realRoot = tree.root.children[0];
  45967. var node = tree.getNodeByDataIndex(dataIndex);
  45968. var value = node.getValue();
  45969. var name = node.name;
  45970. while (node && node !== realRoot) {
  45971. name = node.parentNode.name + '.' + name;
  45972. node = node.parentNode;
  45973. }
  45974. return createTooltipMarkup('nameValue', {
  45975. name: name,
  45976. value: value,
  45977. noValue: isNaN(value) || value == null
  45978. });
  45979. };
  45980. TreeSeriesModel.type = 'series.tree'; // can support the position parameters 'left', 'top','right','bottom', 'width',
  45981. // 'height' in the setOption() with 'merge' mode normal.
  45982. TreeSeriesModel.layoutMode = 'box';
  45983. TreeSeriesModel.defaultOption = {
  45984. zlevel: 0,
  45985. z: 2,
  45986. coordinateSystem: 'view',
  45987. // the position of the whole view
  45988. left: '12%',
  45989. top: '12%',
  45990. right: '12%',
  45991. bottom: '12%',
  45992. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  45993. layout: 'orthogonal',
  45994. // value can be 'polyline'
  45995. edgeShape: 'curve',
  45996. edgeForkPosition: '50%',
  45997. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  45998. roam: false,
  45999. // Symbol size scale ratio in roam
  46000. nodeScaleRatio: 0.4,
  46001. // Default on center of graph
  46002. center: null,
  46003. zoom: 1,
  46004. orient: 'LR',
  46005. symbol: 'emptyCircle',
  46006. symbolSize: 7,
  46007. expandAndCollapse: true,
  46008. initialTreeDepth: 2,
  46009. lineStyle: {
  46010. color: '#ccc',
  46011. width: 1.5,
  46012. curveness: 0.5
  46013. },
  46014. itemStyle: {
  46015. color: 'lightsteelblue',
  46016. borderColor: '#c23531',
  46017. borderWidth: 1.5
  46018. },
  46019. label: {
  46020. show: true
  46021. },
  46022. animationEasing: 'linear',
  46023. animationDuration: 700,
  46024. animationDurationUpdate: 500
  46025. };
  46026. return TreeSeriesModel;
  46027. }(SeriesModel);
  46028. /*
  46029. * Licensed to the Apache Software Foundation (ASF) under one
  46030. * or more contributor license agreements. See the NOTICE file
  46031. * distributed with this work for additional information
  46032. * regarding copyright ownership. The ASF licenses this file
  46033. * to you under the Apache License, Version 2.0 (the
  46034. * "License"); you may not use this file except in compliance
  46035. * with the License. You may obtain a copy of the License at
  46036. *
  46037. * http://www.apache.org/licenses/LICENSE-2.0
  46038. *
  46039. * Unless required by applicable law or agreed to in writing,
  46040. * software distributed under the License is distributed on an
  46041. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46042. * KIND, either express or implied. See the License for the
  46043. * specific language governing permissions and limitations
  46044. * under the License.
  46045. */
  46046. /**
  46047. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46048. */
  46049. /*
  46050. * Licensed to the Apache Software Foundation (ASF) under one
  46051. * or more contributor license agreements. See the NOTICE file
  46052. * distributed with this work for additional information
  46053. * regarding copyright ownership. The ASF licenses this file
  46054. * to you under the Apache License, Version 2.0 (the
  46055. * "License"); you may not use this file except in compliance
  46056. * with the License. You may obtain a copy of the License at
  46057. *
  46058. * http://www.apache.org/licenses/LICENSE-2.0
  46059. *
  46060. * Unless required by applicable law or agreed to in writing,
  46061. * software distributed under the License is distributed on an
  46062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46063. * KIND, either express or implied. See the License for the
  46064. * specific language governing permissions and limitations
  46065. * under the License.
  46066. */
  46067. /**
  46068. * Traverse the tree from bottom to top and do something
  46069. */
  46070. function eachAfter(root, callback, separation) {
  46071. var nodes = [root];
  46072. var next = [];
  46073. var node;
  46074. while (node = nodes.pop()) {
  46075. // jshint ignore:line
  46076. next.push(node);
  46077. if (node.isExpand) {
  46078. var children = node.children;
  46079. if (children.length) {
  46080. for (var i = 0; i < children.length; i++) {
  46081. nodes.push(children[i]);
  46082. }
  46083. }
  46084. }
  46085. }
  46086. while (node = next.pop()) {
  46087. // jshint ignore:line
  46088. callback(node, separation);
  46089. }
  46090. }
  46091. /**
  46092. * Traverse the tree from top to bottom and do something
  46093. */
  46094. function eachBefore(root, callback) {
  46095. var nodes = [root];
  46096. var node;
  46097. while (node = nodes.pop()) {
  46098. // jshint ignore:line
  46099. callback(node);
  46100. if (node.isExpand) {
  46101. var children = node.children;
  46102. if (children.length) {
  46103. for (var i = children.length - 1; i >= 0; i--) {
  46104. nodes.push(children[i]);
  46105. }
  46106. }
  46107. }
  46108. }
  46109. }
  46110. function treeLayout(ecModel, api) {
  46111. ecModel.eachSeriesByType('tree', function (seriesModel) {
  46112. commonLayout(seriesModel, api);
  46113. });
  46114. }
  46115. function commonLayout(seriesModel, api) {
  46116. var layoutInfo = getViewRect$1(seriesModel, api);
  46117. seriesModel.layoutInfo = layoutInfo;
  46118. var layout = seriesModel.get('layout');
  46119. var width = 0;
  46120. var height = 0;
  46121. var separation$1 = null;
  46122. if (layout === 'radial') {
  46123. width = 2 * Math.PI;
  46124. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  46125. separation$1 = separation(function (node1, node2) {
  46126. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  46127. });
  46128. } else {
  46129. width = layoutInfo.width;
  46130. height = layoutInfo.height;
  46131. separation$1 = separation();
  46132. }
  46133. var virtualRoot = seriesModel.getData().tree.root;
  46134. var realRoot = virtualRoot.children[0];
  46135. if (realRoot) {
  46136. init$2(virtualRoot);
  46137. eachAfter(realRoot, firstWalk, separation$1);
  46138. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  46139. eachBefore(realRoot, secondWalk);
  46140. var left_1 = realRoot;
  46141. var right_1 = realRoot;
  46142. var bottom_1 = realRoot;
  46143. eachBefore(realRoot, function (node) {
  46144. var x = node.getLayout().x;
  46145. if (x < left_1.getLayout().x) {
  46146. left_1 = node;
  46147. }
  46148. if (x > right_1.getLayout().x) {
  46149. right_1 = node;
  46150. }
  46151. if (node.depth > bottom_1.depth) {
  46152. bottom_1 = node;
  46153. }
  46154. });
  46155. var delta = left_1 === right_1 ? 1 : separation$1(left_1, right_1) / 2;
  46156. var tx_1 = delta - left_1.getLayout().x;
  46157. var kx_1 = 0;
  46158. var ky_1 = 0;
  46159. var coorX_1 = 0;
  46160. var coorY_1 = 0;
  46161. if (layout === 'radial') {
  46162. kx_1 = width / (right_1.getLayout().x + delta + tx_1); // here we use (node.depth - 1), bucause the real root's depth is 1
  46163. ky_1 = height / (bottom_1.depth - 1 || 1);
  46164. eachBefore(realRoot, function (node) {
  46165. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  46166. coorY_1 = (node.depth - 1) * ky_1;
  46167. var finalCoor = radialCoordinate(coorX_1, coorY_1);
  46168. node.setLayout({
  46169. x: finalCoor.x,
  46170. y: finalCoor.y,
  46171. rawX: coorX_1,
  46172. rawY: coorY_1
  46173. }, true);
  46174. });
  46175. } else {
  46176. var orient_1 = seriesModel.getOrient();
  46177. if (orient_1 === 'RL' || orient_1 === 'LR') {
  46178. ky_1 = height / (right_1.getLayout().x + delta + tx_1);
  46179. kx_1 = width / (bottom_1.depth - 1 || 1);
  46180. eachBefore(realRoot, function (node) {
  46181. coorY_1 = (node.getLayout().x + tx_1) * ky_1;
  46182. coorX_1 = orient_1 === 'LR' ? (node.depth - 1) * kx_1 : width - (node.depth - 1) * kx_1;
  46183. node.setLayout({
  46184. x: coorX_1,
  46185. y: coorY_1
  46186. }, true);
  46187. });
  46188. } else if (orient_1 === 'TB' || orient_1 === 'BT') {
  46189. kx_1 = width / (right_1.getLayout().x + delta + tx_1);
  46190. ky_1 = height / (bottom_1.depth - 1 || 1);
  46191. eachBefore(realRoot, function (node) {
  46192. coorX_1 = (node.getLayout().x + tx_1) * kx_1;
  46193. coorY_1 = orient_1 === 'TB' ? (node.depth - 1) * ky_1 : height - (node.depth - 1) * ky_1;
  46194. node.setLayout({
  46195. x: coorX_1,
  46196. y: coorY_1
  46197. }, true);
  46198. });
  46199. }
  46200. }
  46201. }
  46202. }
  46203. function treeVisual(ecModel) {
  46204. ecModel.eachSeriesByType('tree', function (seriesModel) {
  46205. var data = seriesModel.getData();
  46206. var tree = data.tree;
  46207. tree.eachNode(function (node) {
  46208. var model = node.getModel(); // TODO Optimize
  46209. var style = model.getModel('itemStyle').getItemStyle();
  46210. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  46211. extend(existsStyle, style);
  46212. });
  46213. });
  46214. }
  46215. function installTreeAction(registers) {
  46216. registers.registerAction({
  46217. type: 'treeExpandAndCollapse',
  46218. event: 'treeExpandAndCollapse',
  46219. update: 'update'
  46220. }, function (payload, ecModel) {
  46221. ecModel.eachComponent({
  46222. mainType: 'series',
  46223. subType: 'tree',
  46224. query: payload
  46225. }, function (seriesModel) {
  46226. var dataIndex = payload.dataIndex;
  46227. var tree = seriesModel.getData().tree;
  46228. var node = tree.getNodeByDataIndex(dataIndex);
  46229. node.isExpand = !node.isExpand;
  46230. });
  46231. });
  46232. registers.registerAction({
  46233. type: 'treeRoam',
  46234. event: 'treeRoam',
  46235. // Here we set 'none' instead of 'update', because roam action
  46236. // just need to update the transform matrix without having to recalculate
  46237. // the layout. So don't need to go through the whole update process, such
  46238. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  46239. update: 'none'
  46240. }, function (payload, ecModel) {
  46241. ecModel.eachComponent({
  46242. mainType: 'series',
  46243. subType: 'tree',
  46244. query: payload
  46245. }, function (seriesModel) {
  46246. var coordSys = seriesModel.coordinateSystem;
  46247. var res = updateCenterAndZoom(coordSys, payload);
  46248. seriesModel.setCenter && seriesModel.setCenter(res.center);
  46249. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  46250. });
  46251. });
  46252. }
  46253. function install$b(registers) {
  46254. registers.registerChartView(TreeView);
  46255. registers.registerSeriesModel(TreeSeriesModel);
  46256. registers.registerLayout(treeLayout);
  46257. registers.registerVisual(treeVisual);
  46258. installTreeAction(registers);
  46259. }
  46260. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  46261. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  46262. var root = seriesModel.getData().tree.root;
  46263. var targetNode = payload.targetNode;
  46264. if (typeof targetNode === 'string') {
  46265. targetNode = root.getNodeById(targetNode);
  46266. }
  46267. if (targetNode && root.contains(targetNode)) {
  46268. return {
  46269. node: targetNode
  46270. };
  46271. }
  46272. var targetNodeId = payload.targetNodeId;
  46273. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  46274. return {
  46275. node: targetNode
  46276. };
  46277. }
  46278. }
  46279. } // Not includes the given node at the last item.
  46280. function getPathToRoot(node) {
  46281. var path = [];
  46282. while (node) {
  46283. node = node.parentNode;
  46284. node && path.push(node);
  46285. }
  46286. return path.reverse();
  46287. }
  46288. function aboveViewRoot(viewRoot, node) {
  46289. var viewPath = getPathToRoot(viewRoot);
  46290. return indexOf(viewPath, node) >= 0;
  46291. } // From root to the input node (the input node will be included).
  46292. function wrapTreePathInfo(node, seriesModel) {
  46293. var treePathInfo = [];
  46294. while (node) {
  46295. var nodeDataIndex = node.dataIndex;
  46296. treePathInfo.push({
  46297. name: node.name,
  46298. dataIndex: nodeDataIndex,
  46299. value: seriesModel.getRawValue(nodeDataIndex)
  46300. });
  46301. node = node.parentNode;
  46302. }
  46303. treePathInfo.reverse();
  46304. return treePathInfo;
  46305. }
  46306. var noop$1 = function () {};
  46307. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  46308. function installTreemapAction(registers) {
  46309. for (var i = 0; i < actionTypes.length; i++) {
  46310. registers.registerAction({
  46311. type: actionTypes[i],
  46312. update: 'updateView'
  46313. }, noop$1);
  46314. }
  46315. registers.registerAction({
  46316. type: 'treemapRootToNode',
  46317. update: 'updateView'
  46318. }, function (payload, ecModel) {
  46319. ecModel.eachComponent({
  46320. mainType: 'series',
  46321. subType: 'treemap',
  46322. query: payload
  46323. }, handleRootToNode);
  46324. function handleRootToNode(model, index) {
  46325. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  46326. var targetInfo = retrieveTargetInfo(payload, types, model);
  46327. if (targetInfo) {
  46328. var originViewRoot = model.getViewRoot();
  46329. if (originViewRoot) {
  46330. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  46331. }
  46332. model.resetViewRoot(targetInfo.node);
  46333. }
  46334. }
  46335. });
  46336. }
  46337. function enableAriaDecalForTree(seriesModel) {
  46338. var data = seriesModel.getData();
  46339. var tree = data.tree;
  46340. var decalPaletteScope = {};
  46341. tree.eachNode(function (node) {
  46342. // Use decal of level 1 node
  46343. var current = node;
  46344. while (current && current.depth > 1) {
  46345. current = current.parentNode;
  46346. }
  46347. var decal = getDecalFromPalette(seriesModel.ecModel, current.name || current.dataIndex + '', decalPaletteScope);
  46348. node.setVisual('decal', decal);
  46349. });
  46350. }
  46351. var TreemapSeriesModel =
  46352. /** @class */
  46353. function (_super) {
  46354. __extends(TreemapSeriesModel, _super);
  46355. function TreemapSeriesModel() {
  46356. var _this = _super !== null && _super.apply(this, arguments) || this;
  46357. _this.type = TreemapSeriesModel.type;
  46358. _this.preventUsingHoverLayer = true;
  46359. return _this;
  46360. }
  46361. /**
  46362. * @override
  46363. */
  46364. TreemapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  46365. // Create a virtual root.
  46366. var root = {
  46367. name: option.name,
  46368. children: option.data
  46369. };
  46370. completeTreeValue(root);
  46371. var levels = option.levels || []; // Used in "visual priority" in `treemapVisual.js`.
  46372. // This way is a little tricky, must satisfy the precondition:
  46373. // 1. There is no `treeNode.getModel('itemStyle.xxx')` used.
  46374. // 2. The `Model.prototype.getModel()` will not use any clone-like way.
  46375. var designatedVisualItemStyle = this.designatedVisualItemStyle = {};
  46376. var designatedVisualModel = new Model({
  46377. itemStyle: designatedVisualItemStyle
  46378. }, this, ecModel);
  46379. levels = option.levels = setDefault(levels, ecModel);
  46380. var levelModels = map(levels || [], function (levelDefine) {
  46381. return new Model(levelDefine, designatedVisualModel, ecModel);
  46382. }, this); // Make sure always a new tree is created when setOption,
  46383. // in TreemapView, we check whether oldTree === newTree
  46384. // to choose mappings approach among old shapes and new shapes.
  46385. var tree = Tree.createTree(root, this, beforeLink);
  46386. function beforeLink(nodeData) {
  46387. nodeData.wrapMethod('getItemModel', function (model, idx) {
  46388. var node = tree.getNodeByDataIndex(idx);
  46389. var levelModel = levelModels[node.depth]; // If no levelModel, we also need `designatedVisualModel`.
  46390. model.parentModel = levelModel || designatedVisualModel;
  46391. return model;
  46392. });
  46393. }
  46394. return tree.data;
  46395. };
  46396. TreemapSeriesModel.prototype.optionUpdated = function () {
  46397. this.resetViewRoot();
  46398. };
  46399. /**
  46400. * @override
  46401. * @param {number} dataIndex
  46402. * @param {boolean} [mutipleSeries=false]
  46403. */
  46404. TreemapSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  46405. var data = this.getData();
  46406. var value = this.getRawValue(dataIndex);
  46407. var name = data.getName(dataIndex);
  46408. return createTooltipMarkup('nameValue', {
  46409. name: name,
  46410. value: value
  46411. });
  46412. };
  46413. /**
  46414. * Add tree path to tooltip param
  46415. *
  46416. * @override
  46417. * @param {number} dataIndex
  46418. * @return {Object}
  46419. */
  46420. TreemapSeriesModel.prototype.getDataParams = function (dataIndex) {
  46421. var params = _super.prototype.getDataParams.apply(this, arguments);
  46422. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  46423. params.treePathInfo = wrapTreePathInfo(node, this);
  46424. return params;
  46425. };
  46426. /**
  46427. * @public
  46428. * @param {Object} layoutInfo {
  46429. * x: containerGroup x
  46430. * y: containerGroup y
  46431. * width: containerGroup width
  46432. * height: containerGroup height
  46433. * }
  46434. */
  46435. TreemapSeriesModel.prototype.setLayoutInfo = function (layoutInfo) {
  46436. /**
  46437. * @readOnly
  46438. * @type {Object}
  46439. */
  46440. this.layoutInfo = this.layoutInfo || {};
  46441. extend(this.layoutInfo, layoutInfo);
  46442. };
  46443. /**
  46444. * @param {string} id
  46445. * @return {number} index
  46446. */
  46447. TreemapSeriesModel.prototype.mapIdToIndex = function (id) {
  46448. // A feature is implemented:
  46449. // index is monotone increasing with the sequence of
  46450. // input id at the first time.
  46451. // This feature can make sure that each data item and its
  46452. // mapped color have the same index between data list and
  46453. // color list at the beginning, which is useful for user
  46454. // to adjust data-color mapping.
  46455. /**
  46456. * @private
  46457. * @type {Object}
  46458. */
  46459. var idIndexMap = this._idIndexMap;
  46460. if (!idIndexMap) {
  46461. idIndexMap = this._idIndexMap = createHashMap();
  46462. /**
  46463. * @private
  46464. * @type {number}
  46465. */
  46466. this._idIndexMapCount = 0;
  46467. }
  46468. var index = idIndexMap.get(id);
  46469. if (index == null) {
  46470. idIndexMap.set(id, index = this._idIndexMapCount++);
  46471. }
  46472. return index;
  46473. };
  46474. TreemapSeriesModel.prototype.getViewRoot = function () {
  46475. return this._viewRoot;
  46476. };
  46477. TreemapSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  46478. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  46479. var root = this.getRawData().tree.root;
  46480. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  46481. this._viewRoot = root;
  46482. }
  46483. };
  46484. TreemapSeriesModel.prototype.enableAriaDecal = function () {
  46485. enableAriaDecalForTree(this);
  46486. };
  46487. TreemapSeriesModel.type = 'series.treemap';
  46488. TreemapSeriesModel.layoutMode = 'box';
  46489. TreemapSeriesModel.defaultOption = {
  46490. // Disable progressive rendering
  46491. progressive: 0,
  46492. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  46493. left: 'center',
  46494. top: 'middle',
  46495. width: '80%',
  46496. height: '80%',
  46497. sort: true,
  46498. clipWindow: 'origin',
  46499. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  46500. leafDepth: null,
  46501. drillDownIcon: '▶',
  46502. // to align specialized icon. ▷▶❒❐▼✚
  46503. zoomToNodeRatio: 0.32 * 0.32,
  46504. roam: true,
  46505. nodeClick: 'zoomToNode',
  46506. animation: true,
  46507. animationDurationUpdate: 900,
  46508. animationEasing: 'quinticInOut',
  46509. breadcrumb: {
  46510. show: true,
  46511. height: 22,
  46512. left: 'center',
  46513. top: 'bottom',
  46514. // right
  46515. // bottom
  46516. emptyItemWidth: 25,
  46517. itemStyle: {
  46518. color: 'rgba(0,0,0,0.7)',
  46519. textStyle: {
  46520. color: '#fff'
  46521. }
  46522. }
  46523. },
  46524. label: {
  46525. show: true,
  46526. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  46527. distance: 0,
  46528. padding: 5,
  46529. position: 'inside',
  46530. // formatter: null,
  46531. color: '#fff',
  46532. overflow: 'truncate' // align
  46533. // verticalAlign
  46534. },
  46535. upperLabel: {
  46536. show: false,
  46537. position: [0, '50%'],
  46538. height: 20,
  46539. // formatter: null,
  46540. // color: '#fff',
  46541. overflow: 'truncate',
  46542. // align: null,
  46543. verticalAlign: 'middle'
  46544. },
  46545. itemStyle: {
  46546. color: null,
  46547. colorAlpha: null,
  46548. colorSaturation: null,
  46549. borderWidth: 0,
  46550. gapWidth: 0,
  46551. borderColor: '#fff',
  46552. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  46553. // border color is evaluated by color of current node and
  46554. // borderColorSaturation.
  46555. },
  46556. emphasis: {
  46557. upperLabel: {
  46558. show: true,
  46559. position: [0, '50%'],
  46560. ellipsis: true,
  46561. verticalAlign: 'middle'
  46562. }
  46563. },
  46564. visualDimension: 0,
  46565. visualMin: null,
  46566. visualMax: null,
  46567. color: [],
  46568. // level[n].color (if necessary).
  46569. // + Specify color list of each level. level[0].color would be global
  46570. // color list if not specified. (see method `setDefault`).
  46571. // + But set as a empty array to forbid fetch color from global palette
  46572. // when using nodeModel.get('color'), otherwise nodes on deep level
  46573. // will always has color palette set and are not able to inherit color
  46574. // from parent node.
  46575. // + TreemapSeries.color can not be set as 'none', otherwise effect
  46576. // legend color fetching (see seriesColor.js).
  46577. colorAlpha: null,
  46578. colorSaturation: null,
  46579. colorMappingBy: 'index',
  46580. visibleMin: 10,
  46581. // be rendered. Only works when sort is 'asc' or 'desc'.
  46582. childrenVisibleMin: null,
  46583. // grandchildren will not show.
  46584. // Why grandchildren? If not grandchildren but children,
  46585. // some siblings show children and some not,
  46586. // the appearance may be mess and not consistent,
  46587. levels: [] // Each item: {
  46588. // visibleMin, itemStyle, visualDimension, label
  46589. // }
  46590. // data: {
  46591. // value: [],
  46592. // children: [],
  46593. // link: 'http://xxx.xxx.xxx',
  46594. // target: 'blank' or 'self'
  46595. // }
  46596. };
  46597. return TreemapSeriesModel;
  46598. }(SeriesModel);
  46599. /**
  46600. * @param {Object} dataNode
  46601. */
  46602. function completeTreeValue(dataNode) {
  46603. // Postorder travel tree.
  46604. // If value of none-leaf node is not set,
  46605. // calculate it by suming up the value of all children.
  46606. var sum = 0;
  46607. each(dataNode.children, function (child) {
  46608. completeTreeValue(child);
  46609. var childValue = child.value;
  46610. isArray(childValue) && (childValue = childValue[0]);
  46611. sum += childValue;
  46612. });
  46613. var thisValue = dataNode.value;
  46614. if (isArray(thisValue)) {
  46615. thisValue = thisValue[0];
  46616. }
  46617. if (thisValue == null || isNaN(thisValue)) {
  46618. thisValue = sum;
  46619. } // Value should not less than 0.
  46620. if (thisValue < 0) {
  46621. thisValue = 0;
  46622. }
  46623. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  46624. }
  46625. /**
  46626. * set default to level configuration
  46627. */
  46628. function setDefault(levels, ecModel) {
  46629. var globalColorList = normalizeToArray(ecModel.get('color'));
  46630. var globalDecalList = normalizeToArray(ecModel.get(['aria', 'decal', 'decals']));
  46631. if (!globalColorList) {
  46632. return;
  46633. }
  46634. levels = levels || [];
  46635. var hasColorDefine;
  46636. var hasDecalDefine;
  46637. each(levels, function (levelDefine) {
  46638. var model = new Model(levelDefine);
  46639. var modelColor = model.get('color');
  46640. var modelDecal = model.get('decal');
  46641. if (model.get(['itemStyle', 'color']) || modelColor && modelColor !== 'none') {
  46642. hasColorDefine = true;
  46643. }
  46644. if (model.get(['itemStyle', 'decal']) || modelDecal && modelDecal !== 'none') {
  46645. hasDecalDefine = true;
  46646. }
  46647. });
  46648. var level0 = levels[0] || (levels[0] = {});
  46649. if (!hasColorDefine) {
  46650. level0.color = globalColorList.slice();
  46651. }
  46652. if (!hasDecalDefine && globalDecalList) {
  46653. level0.decal = globalDecalList.slice();
  46654. }
  46655. return levels;
  46656. }
  46657. var TEXT_PADDING = 8;
  46658. var ITEM_GAP = 8;
  46659. var ARRAY_LENGTH = 5;
  46660. var Breadcrumb =
  46661. /** @class */
  46662. function () {
  46663. function Breadcrumb(containerGroup) {
  46664. this.group = new Group();
  46665. containerGroup.add(this.group);
  46666. }
  46667. Breadcrumb.prototype.render = function (seriesModel, api, targetNode, onSelect) {
  46668. var model = seriesModel.getModel('breadcrumb');
  46669. var thisGroup = this.group;
  46670. thisGroup.removeAll();
  46671. if (!model.get('show') || !targetNode) {
  46672. return;
  46673. }
  46674. var normalStyleModel = model.getModel('itemStyle'); // let emphasisStyleModel = model.getModel('emphasis.itemStyle');
  46675. var textStyleModel = normalStyleModel.getModel('textStyle');
  46676. var layoutParam = {
  46677. pos: {
  46678. left: model.get('left'),
  46679. right: model.get('right'),
  46680. top: model.get('top'),
  46681. bottom: model.get('bottom')
  46682. },
  46683. box: {
  46684. width: api.getWidth(),
  46685. height: api.getHeight()
  46686. },
  46687. emptyItemWidth: model.get('emptyItemWidth'),
  46688. totalWidth: 0,
  46689. renderList: []
  46690. };
  46691. this._prepare(targetNode, layoutParam, textStyleModel);
  46692. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  46693. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  46694. };
  46695. /**
  46696. * Prepare render list and total width
  46697. * @private
  46698. */
  46699. Breadcrumb.prototype._prepare = function (targetNode, layoutParam, textStyleModel) {
  46700. for (var node = targetNode; node; node = node.parentNode) {
  46701. var text = convertOptionIdName(node.getModel().get('name'), '');
  46702. var textRect = textStyleModel.getTextRect(text);
  46703. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  46704. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  46705. layoutParam.renderList.push({
  46706. node: node,
  46707. text: text,
  46708. width: itemWidth
  46709. });
  46710. }
  46711. };
  46712. /**
  46713. * @private
  46714. */
  46715. Breadcrumb.prototype._renderContent = function (seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect) {
  46716. // Start rendering.
  46717. var lastX = 0;
  46718. var emptyItemWidth = layoutParam.emptyItemWidth;
  46719. var height = seriesModel.get(['breadcrumb', 'height']);
  46720. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  46721. var totalWidth = layoutParam.totalWidth;
  46722. var renderList = layoutParam.renderList;
  46723. for (var i = renderList.length - 1; i >= 0; i--) {
  46724. var item = renderList[i];
  46725. var itemNode = item.node;
  46726. var itemWidth = item.width;
  46727. var text = item.text; // Hdie text and shorten width if necessary.
  46728. if (totalWidth > availableSize.width) {
  46729. totalWidth -= itemWidth - emptyItemWidth;
  46730. itemWidth = emptyItemWidth;
  46731. text = null;
  46732. }
  46733. var el = new Polygon({
  46734. shape: {
  46735. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  46736. },
  46737. style: defaults(normalStyleModel.getItemStyle(), {
  46738. lineJoin: 'bevel'
  46739. }),
  46740. textContent: new ZRText({
  46741. style: {
  46742. text: text,
  46743. fill: textStyleModel.getTextColor(),
  46744. font: textStyleModel.getFont()
  46745. }
  46746. }),
  46747. textConfig: {
  46748. position: 'inside'
  46749. },
  46750. z: 10,
  46751. onclick: curry(onSelect, itemNode)
  46752. });
  46753. el.disableLabelAnimation = true;
  46754. this.group.add(el);
  46755. packEventData(el, seriesModel, itemNode);
  46756. lastX += itemWidth + ITEM_GAP;
  46757. }
  46758. };
  46759. Breadcrumb.prototype.remove = function () {
  46760. this.group.removeAll();
  46761. };
  46762. return Breadcrumb;
  46763. }();
  46764. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  46765. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  46766. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  46767. !head && points.push([x, y + itemHeight / 2]);
  46768. return points;
  46769. } // Package custom mouse event.
  46770. function packEventData(el, seriesModel, itemNode) {
  46771. getECData(el).eventData = {
  46772. componentType: 'series',
  46773. componentSubType: 'treemap',
  46774. componentIndex: seriesModel.componentIndex,
  46775. seriesIndex: seriesModel.componentIndex,
  46776. seriesName: seriesModel.name,
  46777. seriesType: 'treemap',
  46778. selfType: 'breadcrumb',
  46779. nodeData: {
  46780. dataIndex: itemNode && itemNode.dataIndex,
  46781. name: itemNode && itemNode.name
  46782. },
  46783. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  46784. };
  46785. }
  46786. /*
  46787. * Licensed to the Apache Software Foundation (ASF) under one
  46788. * or more contributor license agreements. See the NOTICE file
  46789. * distributed with this work for additional information
  46790. * regarding copyright ownership. The ASF licenses this file
  46791. * to you under the Apache License, Version 2.0 (the
  46792. * "License"); you may not use this file except in compliance
  46793. * with the License. You may obtain a copy of the License at
  46794. *
  46795. * http://www.apache.org/licenses/LICENSE-2.0
  46796. *
  46797. * Unless required by applicable law or agreed to in writing,
  46798. * software distributed under the License is distributed on an
  46799. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46800. * KIND, either express or implied. See the License for the
  46801. * specific language governing permissions and limitations
  46802. * under the License.
  46803. */
  46804. /**
  46805. * AUTO-GENERATED FILE. DO NOT MODIFY.
  46806. */
  46807. /*
  46808. * Licensed to the Apache Software Foundation (ASF) under one
  46809. * or more contributor license agreements. See the NOTICE file
  46810. * distributed with this work for additional information
  46811. * regarding copyright ownership. The ASF licenses this file
  46812. * to you under the Apache License, Version 2.0 (the
  46813. * "License"); you may not use this file except in compliance
  46814. * with the License. You may obtain a copy of the License at
  46815. *
  46816. * http://www.apache.org/licenses/LICENSE-2.0
  46817. *
  46818. * Unless required by applicable law or agreed to in writing,
  46819. * software distributed under the License is distributed on an
  46820. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46821. * KIND, either express or implied. See the License for the
  46822. * specific language governing permissions and limitations
  46823. * under the License.
  46824. */
  46825. /**
  46826. * Animate multiple elements with a single done-callback.
  46827. *
  46828. * @example
  46829. * animation
  46830. * .createWrap()
  46831. * .add(el1, {x: 10, y: 10})
  46832. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  46833. * .done(function () { // done })
  46834. * .start('cubicOut');
  46835. */
  46836. var AnimationWrap =
  46837. /** @class */
  46838. function () {
  46839. function AnimationWrap() {
  46840. this._storage = [];
  46841. this._elExistsMap = {};
  46842. }
  46843. /**
  46844. * Caution: a el can only be added once, otherwise 'done'
  46845. * might not be called. This method checks this (by el.id),
  46846. * suppresses adding and returns false when existing el found.
  46847. *
  46848. * @return Whether adding succeeded.
  46849. */
  46850. AnimationWrap.prototype.add = function (el, target, duration, delay, easing) {
  46851. if (this._elExistsMap[el.id]) {
  46852. return false;
  46853. }
  46854. this._elExistsMap[el.id] = true;
  46855. this._storage.push({
  46856. el: el,
  46857. target: target,
  46858. duration: duration,
  46859. delay: delay,
  46860. easing: easing
  46861. });
  46862. return true;
  46863. };
  46864. /**
  46865. * Only execute when animation done/aborted.
  46866. */
  46867. AnimationWrap.prototype.finished = function (callback) {
  46868. this._finishedCallback = callback;
  46869. return this;
  46870. };
  46871. /**
  46872. * Will stop exist animation firstly.
  46873. */
  46874. AnimationWrap.prototype.start = function () {
  46875. var _this = this;
  46876. var count = this._storage.length;
  46877. var checkTerminate = function () {
  46878. count--;
  46879. if (count <= 0) {
  46880. // Guard.
  46881. _this._storage.length = 0;
  46882. _this._elExistsMap = {};
  46883. _this._finishedCallback && _this._finishedCallback();
  46884. }
  46885. };
  46886. for (var i = 0, len = this._storage.length; i < len; i++) {
  46887. var item = this._storage[i];
  46888. item.el.animateTo(item.target, {
  46889. duration: item.duration,
  46890. delay: item.delay,
  46891. easing: item.easing,
  46892. setToFinal: true,
  46893. done: checkTerminate,
  46894. aborted: checkTerminate
  46895. });
  46896. }
  46897. return this;
  46898. };
  46899. return AnimationWrap;
  46900. }();
  46901. function createWrap() {
  46902. return new AnimationWrap();
  46903. }
  46904. var Group$1 = Group;
  46905. var Rect$1 = Rect;
  46906. var DRAG_THRESHOLD = 3;
  46907. var PATH_LABEL_NOAMAL = 'label';
  46908. var PATH_UPPERLABEL_NORMAL = 'upperLabel';
  46909. var Z_BASE = 10; // Should bigger than every z.
  46910. var Z_BG = 1;
  46911. var Z_CONTENT = 2;
  46912. var getStateItemStyle = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  46913. // so use `stroke` to indicate the stroke of the rect.
  46914. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  46915. // So do not transfer decal directly.
  46916. ]);
  46917. var getItemStyleNormal = function (model) {
  46918. // Normal style props should include emphasis style props.
  46919. var itemStyle = getStateItemStyle(model); // Clear styles set by emphasis.
  46920. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  46921. return itemStyle;
  46922. };
  46923. var inner$9 = makeInner();
  46924. var TreemapView =
  46925. /** @class */
  46926. function (_super) {
  46927. __extends(TreemapView, _super);
  46928. function TreemapView() {
  46929. var _this = _super !== null && _super.apply(this, arguments) || this;
  46930. _this.type = TreemapView.type;
  46931. _this._state = 'ready';
  46932. _this._storage = createStorage();
  46933. return _this;
  46934. }
  46935. /**
  46936. * @override
  46937. */
  46938. TreemapView.prototype.render = function (seriesModel, ecModel, api, payload) {
  46939. var models = ecModel.findComponents({
  46940. mainType: 'series',
  46941. subType: 'treemap',
  46942. query: payload
  46943. });
  46944. if (indexOf(models, seriesModel) < 0) {
  46945. return;
  46946. }
  46947. this.seriesModel = seriesModel;
  46948. this.api = api;
  46949. this.ecModel = ecModel;
  46950. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  46951. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  46952. var payloadType = payload && payload.type;
  46953. var layoutInfo = seriesModel.layoutInfo;
  46954. var isInit = !this._oldTree;
  46955. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  46956. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  46957. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  46958. direction: payload.direction
  46959. } : null;
  46960. var containerGroup = this._giveContainerGroup(layoutInfo);
  46961. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  46962. !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  46963. this._resetController(api);
  46964. this._renderBreadcrumb(seriesModel, api, targetInfo);
  46965. };
  46966. TreemapView.prototype._giveContainerGroup = function (layoutInfo) {
  46967. var containerGroup = this._containerGroup;
  46968. if (!containerGroup) {
  46969. // FIXME
  46970. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  46971. containerGroup = this._containerGroup = new Group$1();
  46972. this._initEvents(containerGroup);
  46973. this.group.add(containerGroup);
  46974. }
  46975. containerGroup.x = layoutInfo.x;
  46976. containerGroup.y = layoutInfo.y;
  46977. return containerGroup;
  46978. };
  46979. TreemapView.prototype._doRender = function (containerGroup, seriesModel, reRoot) {
  46980. var thisTree = seriesModel.getData().tree;
  46981. var oldTree = this._oldTree; // Clear last shape records.
  46982. var lastsForAnimation = createStorage();
  46983. var thisStorage = createStorage();
  46984. var oldStorage = this._storage;
  46985. var willInvisibleEls = [];
  46986. function doRenderNode(thisNode, oldNode, parentGroup, depth) {
  46987. return renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth);
  46988. } // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  46989. // the oldTree is actually losted, so we can not find all of the old graphic
  46990. // elements from tree. So we use this stragegy: make element storage, move
  46991. // from old storage to new storage, clear old storage.
  46992. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  46993. var willDeleteEls = clearStorage(oldStorage);
  46994. this._oldTree = thisTree;
  46995. this._storage = thisStorage;
  46996. return {
  46997. lastsForAnimation: lastsForAnimation,
  46998. willDeleteEls: willDeleteEls,
  46999. renderFinally: renderFinally
  47000. };
  47001. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  47002. // When 'render' is triggered by action,
  47003. // 'this' and 'old' may be the same tree,
  47004. // we use rawIndex in that case.
  47005. if (sameTree) {
  47006. oldViewChildren = thisViewChildren;
  47007. each(thisViewChildren, function (child, index) {
  47008. !child.isRemoved() && processNode(index, index);
  47009. });
  47010. } // Diff hierarchically (diff only in each subtree, but not whole).
  47011. // because, consistency of view is important.
  47012. else {
  47013. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  47014. }
  47015. function getKey(node) {
  47016. // Identify by name or raw index.
  47017. return node.getId();
  47018. }
  47019. function processNode(newIndex, oldIndex) {
  47020. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  47021. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  47022. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  47023. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  47024. }
  47025. }
  47026. function clearStorage(storage) {
  47027. var willDeleteEls = createStorage();
  47028. storage && each(storage, function (store, storageName) {
  47029. var delEls = willDeleteEls[storageName];
  47030. each(store, function (el) {
  47031. el && (delEls.push(el), inner$9(el).willDelete = true);
  47032. });
  47033. });
  47034. return willDeleteEls;
  47035. }
  47036. function renderFinally() {
  47037. each(willDeleteEls, function (els) {
  47038. each(els, function (el) {
  47039. el.parent && el.parent.remove(el);
  47040. });
  47041. });
  47042. each(willInvisibleEls, function (el) {
  47043. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  47044. // just mark as invisible.
  47045. el.dirty();
  47046. });
  47047. }
  47048. };
  47049. TreemapView.prototype._doAnimation = function (containerGroup, renderResult, seriesModel, reRoot) {
  47050. if (!seriesModel.get('animation')) {
  47051. return;
  47052. }
  47053. var durationOption = seriesModel.get('animationDurationUpdate');
  47054. var easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary.
  47055. var duration = (isFunction(durationOption) ? 0 : durationOption) || 0;
  47056. var easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut';
  47057. var animationWrap = createWrap(); // Make delete animations.
  47058. each(renderResult.willDeleteEls, function (store, storageName) {
  47059. each(store, function (el, rawIndex) {
  47060. if (el.invisible) {
  47061. return;
  47062. }
  47063. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  47064. var target;
  47065. var innerStore = inner$9(parent);
  47066. if (reRoot && reRoot.direction === 'drillDown') {
  47067. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  47068. // Only `content` will enter this branch, because
  47069. // `background` and `nodeGroup` will not be deleted.
  47070. ? {
  47071. shape: {
  47072. x: 0,
  47073. y: 0,
  47074. width: innerStore.nodeWidth,
  47075. height: innerStore.nodeHeight
  47076. },
  47077. style: {
  47078. opacity: 0
  47079. }
  47080. } // Others.
  47081. : {
  47082. style: {
  47083. opacity: 0
  47084. }
  47085. };
  47086. } else {
  47087. var targetX = 0;
  47088. var targetY = 0;
  47089. if (!innerStore.willDelete) {
  47090. // Let node animate to right-bottom corner, cooperating with fadeout,
  47091. // which is appropriate for user understanding.
  47092. // Divided by 2 for reRoot rolling up effect.
  47093. targetX = innerStore.nodeWidth / 2;
  47094. targetY = innerStore.nodeHeight / 2;
  47095. }
  47096. target = storageName === 'nodeGroup' ? {
  47097. x: targetX,
  47098. y: targetY,
  47099. style: {
  47100. opacity: 0
  47101. }
  47102. } : {
  47103. shape: {
  47104. x: targetX,
  47105. y: targetY,
  47106. width: 0,
  47107. height: 0
  47108. },
  47109. style: {
  47110. opacity: 0
  47111. }
  47112. };
  47113. } // TODO: do not support delay until necessary.
  47114. target && animationWrap.add(el, target, duration, 0, easing);
  47115. });
  47116. }); // Make other animations
  47117. each(this._storage, function (store, storageName) {
  47118. each(store, function (el, rawIndex) {
  47119. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  47120. var target = {};
  47121. if (!last) {
  47122. return;
  47123. }
  47124. if (el instanceof Group) {
  47125. if (last.oldX != null) {
  47126. target.x = el.x;
  47127. target.y = el.y;
  47128. el.x = last.oldX;
  47129. el.y = last.oldY;
  47130. }
  47131. } else {
  47132. if (last.oldShape) {
  47133. target.shape = extend({}, el.shape);
  47134. el.setShape(last.oldShape);
  47135. }
  47136. if (last.fadein) {
  47137. el.setStyle('opacity', 0);
  47138. target.style = {
  47139. opacity: 1
  47140. };
  47141. } // When animation is stopped for succedent animation starting,
  47142. // el.style.opacity might not be 1
  47143. else if (el.style.opacity !== 1) {
  47144. target.style = {
  47145. opacity: 1
  47146. };
  47147. }
  47148. }
  47149. animationWrap.add(el, target, duration, 0, easing);
  47150. });
  47151. }, this);
  47152. this._state = 'animating';
  47153. animationWrap.finished(bind(function () {
  47154. this._state = 'ready';
  47155. renderResult.renderFinally();
  47156. }, this)).start();
  47157. };
  47158. TreemapView.prototype._resetController = function (api) {
  47159. var controller = this._controller; // Init controller.
  47160. if (!controller) {
  47161. controller = this._controller = new RoamController(api.getZr());
  47162. controller.enable(this.seriesModel.get('roam'));
  47163. controller.on('pan', bind(this._onPan, this));
  47164. controller.on('zoom', bind(this._onZoom, this));
  47165. }
  47166. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  47167. controller.setPointerChecker(function (e, x, y) {
  47168. return rect.contain(x, y);
  47169. });
  47170. };
  47171. TreemapView.prototype._clearController = function () {
  47172. var controller = this._controller;
  47173. if (controller) {
  47174. controller.dispose();
  47175. controller = null;
  47176. }
  47177. };
  47178. TreemapView.prototype._onPan = function (e) {
  47179. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  47180. // These param must not be cached.
  47181. var root = this.seriesModel.getData().tree.root;
  47182. if (!root) {
  47183. return;
  47184. }
  47185. var rootLayout = root.getLayout();
  47186. if (!rootLayout) {
  47187. return;
  47188. }
  47189. this.api.dispatchAction({
  47190. type: 'treemapMove',
  47191. from: this.uid,
  47192. seriesId: this.seriesModel.id,
  47193. rootRect: {
  47194. x: rootLayout.x + e.dx,
  47195. y: rootLayout.y + e.dy,
  47196. width: rootLayout.width,
  47197. height: rootLayout.height
  47198. }
  47199. });
  47200. }
  47201. };
  47202. TreemapView.prototype._onZoom = function (e) {
  47203. var mouseX = e.originX;
  47204. var mouseY = e.originY;
  47205. if (this._state !== 'animating') {
  47206. // These param must not be cached.
  47207. var root = this.seriesModel.getData().tree.root;
  47208. if (!root) {
  47209. return;
  47210. }
  47211. var rootLayout = root.getLayout();
  47212. if (!rootLayout) {
  47213. return;
  47214. }
  47215. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  47216. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  47217. mouseX -= layoutInfo.x;
  47218. mouseY -= layoutInfo.y; // Scale root bounding rect.
  47219. var m = create$1();
  47220. translate(m, m, [-mouseX, -mouseY]);
  47221. scale$1(m, m, [e.scale, e.scale]);
  47222. translate(m, m, [mouseX, mouseY]);
  47223. rect.applyTransform(m);
  47224. this.api.dispatchAction({
  47225. type: 'treemapRender',
  47226. from: this.uid,
  47227. seriesId: this.seriesModel.id,
  47228. rootRect: {
  47229. x: rect.x,
  47230. y: rect.y,
  47231. width: rect.width,
  47232. height: rect.height
  47233. }
  47234. });
  47235. }
  47236. };
  47237. TreemapView.prototype._initEvents = function (containerGroup) {
  47238. var _this = this;
  47239. containerGroup.on('click', function (e) {
  47240. if (_this._state !== 'ready') {
  47241. return;
  47242. }
  47243. var nodeClick = _this.seriesModel.get('nodeClick', true);
  47244. if (!nodeClick) {
  47245. return;
  47246. }
  47247. var targetInfo = _this.findTarget(e.offsetX, e.offsetY);
  47248. if (!targetInfo) {
  47249. return;
  47250. }
  47251. var node = targetInfo.node;
  47252. if (node.getLayout().isLeafRoot) {
  47253. _this._rootToNode(targetInfo);
  47254. } else {
  47255. if (nodeClick === 'zoomToNode') {
  47256. _this._zoomToNode(targetInfo);
  47257. } else if (nodeClick === 'link') {
  47258. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  47259. var link = itemModel.get('link', true);
  47260. var linkTarget = itemModel.get('target', true) || 'blank';
  47261. link && windowOpen(link, linkTarget);
  47262. }
  47263. }
  47264. }, this);
  47265. };
  47266. TreemapView.prototype._renderBreadcrumb = function (seriesModel, api, targetInfo) {
  47267. var _this = this;
  47268. if (!targetInfo) {
  47269. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  47270. node: seriesModel.getViewRoot()
  47271. } // FIXME
  47272. // better way?
  47273. // Find breadcrumb tail on center of containerGroup.
  47274. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  47275. if (!targetInfo) {
  47276. targetInfo = {
  47277. node: seriesModel.getData().tree.root
  47278. };
  47279. }
  47280. }
  47281. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, function (node) {
  47282. if (_this._state !== 'animating') {
  47283. aboveViewRoot(seriesModel.getViewRoot(), node) ? _this._rootToNode({
  47284. node: node
  47285. }) : _this._zoomToNode({
  47286. node: node
  47287. });
  47288. }
  47289. });
  47290. };
  47291. /**
  47292. * @override
  47293. */
  47294. TreemapView.prototype.remove = function () {
  47295. this._clearController();
  47296. this._containerGroup && this._containerGroup.removeAll();
  47297. this._storage = createStorage();
  47298. this._state = 'ready';
  47299. this._breadcrumb && this._breadcrumb.remove();
  47300. };
  47301. TreemapView.prototype.dispose = function () {
  47302. this._clearController();
  47303. };
  47304. TreemapView.prototype._zoomToNode = function (targetInfo) {
  47305. this.api.dispatchAction({
  47306. type: 'treemapZoomToNode',
  47307. from: this.uid,
  47308. seriesId: this.seriesModel.id,
  47309. targetNode: targetInfo.node
  47310. });
  47311. };
  47312. TreemapView.prototype._rootToNode = function (targetInfo) {
  47313. this.api.dispatchAction({
  47314. type: 'treemapRootToNode',
  47315. from: this.uid,
  47316. seriesId: this.seriesModel.id,
  47317. targetNode: targetInfo.node
  47318. });
  47319. };
  47320. /**
  47321. * @public
  47322. * @param {number} x Global coord x.
  47323. * @param {number} y Global coord y.
  47324. * @return {Object} info If not found, return undefined;
  47325. * @return {number} info.node Target node.
  47326. * @return {number} info.offsetX x refer to target node.
  47327. * @return {number} info.offsetY y refer to target node.
  47328. */
  47329. TreemapView.prototype.findTarget = function (x, y) {
  47330. var targetInfo;
  47331. var viewRoot = this.seriesModel.getViewRoot();
  47332. viewRoot.eachNode({
  47333. attr: 'viewChildren',
  47334. order: 'preorder'
  47335. }, function (node) {
  47336. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  47337. if (bgEl) {
  47338. var point = bgEl.transformCoordToLocal(x, y);
  47339. var shape = bgEl.shape; // For performance consideration, dont use 'getBoundingRect'.
  47340. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  47341. targetInfo = {
  47342. node: node,
  47343. offsetX: point[0],
  47344. offsetY: point[1]
  47345. };
  47346. } else {
  47347. return false; // Suppress visit subtree.
  47348. }
  47349. }
  47350. }, this);
  47351. return targetInfo;
  47352. };
  47353. TreemapView.type = 'treemap';
  47354. return TreemapView;
  47355. }(ChartView);
  47356. /**
  47357. * @inner
  47358. */
  47359. function createStorage() {
  47360. return {
  47361. nodeGroup: [],
  47362. background: [],
  47363. content: []
  47364. };
  47365. }
  47366. /**
  47367. * @inner
  47368. * @return Return undefined means do not travel further.
  47369. */
  47370. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  47371. // Whether under viewRoot.
  47372. if (!thisNode) {
  47373. // Deleting nodes will be performed finally. This method just find
  47374. // element from old storage, or create new element, set them to new
  47375. // storage, and set styles.
  47376. return;
  47377. } // -------------------------------------------------------------------
  47378. // Start of closure variables available in "Procedures in renderNode".
  47379. var thisLayout = thisNode.getLayout();
  47380. var data = seriesModel.getData();
  47381. var nodeModel = thisNode.getModel(); // Only for enabling highlight/downplay. Clear firstly.
  47382. // Because some node will not be rendered.
  47383. data.setItemGraphicEl(thisNode.dataIndex, null);
  47384. if (!thisLayout || !thisLayout.isInView) {
  47385. return;
  47386. }
  47387. var thisWidth = thisLayout.width;
  47388. var thisHeight = thisLayout.height;
  47389. var borderWidth = thisLayout.borderWidth;
  47390. var thisInvisible = thisLayout.invisible;
  47391. var thisRawIndex = thisNode.getRawIndex();
  47392. var oldRawIndex = oldNode && oldNode.getRawIndex();
  47393. var thisViewChildren = thisNode.viewChildren;
  47394. var upperHeight = thisLayout.upperHeight;
  47395. var isParent = thisViewChildren && thisViewChildren.length;
  47396. var itemStyleNormalModel = nodeModel.getModel('itemStyle');
  47397. var itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']);
  47398. var itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']);
  47399. var itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']);
  47400. var borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode".
  47401. // -----------------------------------------------------------------
  47402. // Node group
  47403. var group = giveGraphic('nodeGroup', Group$1);
  47404. if (!group) {
  47405. return;
  47406. }
  47407. parentGroup.add(group); // x,y are not set when el is above view root.
  47408. group.x = thisLayout.x || 0;
  47409. group.y = thisLayout.y || 0;
  47410. group.markRedraw();
  47411. inner$9(group).nodeWidth = thisWidth;
  47412. inner$9(group).nodeHeight = thisHeight;
  47413. if (thisLayout.isAboveViewRoot) {
  47414. return group;
  47415. } // Background
  47416. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  47417. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight);
  47418. var focus = nodeModel.get(['emphasis', 'focus']);
  47419. var blurScope = nodeModel.get(['emphasis', 'blurScope']);
  47420. var focusDataIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : null; // No children, render content.
  47421. if (isParent) {
  47422. // Because of the implementation about "traverse" in graphic hover style, we
  47423. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  47424. // hover event from the descendents will be listenered.
  47425. if (isHighDownDispatcher(group)) {
  47426. setAsHighDownDispatcher(group, false);
  47427. }
  47428. if (bg) {
  47429. setAsHighDownDispatcher(bg, true); // Only for enabling highlight/downplay.
  47430. data.setItemGraphicEl(thisNode.dataIndex, bg);
  47431. enableHoverFocus(bg, focusDataIndices || focus, blurScope);
  47432. }
  47433. } else {
  47434. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  47435. content && renderContent(group, content);
  47436. if (bg && isHighDownDispatcher(bg)) {
  47437. setAsHighDownDispatcher(bg, false);
  47438. }
  47439. setAsHighDownDispatcher(group, true); // Only for enabling highlight/downplay.
  47440. data.setItemGraphicEl(thisNode.dataIndex, group);
  47441. enableHoverFocus(group, focusDataIndices || focus, blurScope);
  47442. }
  47443. return group; // ----------------------------
  47444. // | Procedures in renderNode |
  47445. // ----------------------------
  47446. function renderBackground(group, bg, useUpperLabel) {
  47447. var ecData = getECData(bg); // For tooltip.
  47448. ecData.dataIndex = thisNode.dataIndex;
  47449. ecData.seriesIndex = seriesModel.seriesIndex;
  47450. bg.setShape({
  47451. x: 0,
  47452. y: 0,
  47453. width: thisWidth,
  47454. height: thisHeight,
  47455. r: borderRadius
  47456. });
  47457. if (thisInvisible) {
  47458. // If invisible, do not set visual, otherwise the element will
  47459. // change immediately before animation. We think it is OK to
  47460. // remain its origin color when moving out of the view window.
  47461. processInvisible(bg);
  47462. } else {
  47463. bg.invisible = false;
  47464. var style = thisNode.getVisual('style');
  47465. var visualBorderColor = style.stroke;
  47466. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  47467. normalStyle.fill = visualBorderColor;
  47468. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  47469. emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor');
  47470. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  47471. blurStyle.fill = itemStyleBlurModel.get('borderColor');
  47472. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  47473. selectStyle.fill = itemStyleSelectModel.get('borderColor');
  47474. if (useUpperLabel) {
  47475. var upperLabelWidth = thisWidth - 2 * borderWidth;
  47476. prepareText(bg, visualBorderColor, upperLabelWidth, upperHeight, style.opacity, {
  47477. x: borderWidth,
  47478. y: 0,
  47479. width: upperLabelWidth,
  47480. height: upperHeight
  47481. });
  47482. } // For old bg.
  47483. else {
  47484. bg.removeTextContent();
  47485. }
  47486. bg.setStyle(normalStyle);
  47487. bg.ensureState('emphasis').style = emphasisStyle;
  47488. bg.ensureState('blur').style = blurStyle;
  47489. bg.ensureState('select').style = selectStyle;
  47490. setDefaultStateProxy(bg);
  47491. }
  47492. group.add(bg);
  47493. }
  47494. function renderContent(group, content) {
  47495. var ecData = getECData(content); // For tooltip.
  47496. ecData.dataIndex = thisNode.dataIndex;
  47497. ecData.seriesIndex = seriesModel.seriesIndex;
  47498. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  47499. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  47500. content.culling = true;
  47501. content.setShape({
  47502. x: borderWidth,
  47503. y: borderWidth,
  47504. width: contentWidth,
  47505. height: contentHeight,
  47506. r: borderRadius
  47507. });
  47508. if (thisInvisible) {
  47509. // If invisible, do not set visual, otherwise the element will
  47510. // change immediately before animation. We think it is OK to
  47511. // remain its origin color when moving out of the view window.
  47512. processInvisible(content);
  47513. } else {
  47514. content.invisible = false;
  47515. var nodeStyle = thisNode.getVisual('style');
  47516. var visualColor = nodeStyle.fill;
  47517. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  47518. normalStyle.fill = visualColor;
  47519. normalStyle.decal = nodeStyle.decal;
  47520. var emphasisStyle = getStateItemStyle(itemStyleEmphasisModel);
  47521. var blurStyle = getStateItemStyle(itemStyleBlurModel);
  47522. var selectStyle = getStateItemStyle(itemStyleSelectModel);
  47523. prepareText(content, visualColor, contentWidth, nodeStyle.opacity);
  47524. content.setStyle(normalStyle);
  47525. content.ensureState('emphasis').style = emphasisStyle;
  47526. content.ensureState('blur').style = blurStyle;
  47527. content.ensureState('select').style = selectStyle;
  47528. setDefaultStateProxy(content);
  47529. }
  47530. group.add(content);
  47531. }
  47532. function processInvisible(element) {
  47533. // Delay invisible setting utill animation finished,
  47534. // avoid element vanish suddenly before animation.
  47535. !element.invisible && willInvisibleEls.push(element);
  47536. }
  47537. function prepareText(rectEl, visualColor, visualOpacity, width, height, upperLabelRect) {
  47538. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  47539. var text = retrieve(seriesModel.getFormattedLabel(thisNode.dataIndex, 'normal', null, null, normalLabelModel.get('formatter')), convertOptionIdName(nodeModel.get('name'), null));
  47540. if (!upperLabelRect && thisLayout.isLeafRoot) {
  47541. var iconChar = seriesModel.get('drillDownIcon', true);
  47542. text = iconChar ? iconChar + ' ' + text : text;
  47543. }
  47544. var isShow = normalLabelModel.getShallow('show');
  47545. setLabelStyle(rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), {
  47546. defaultText: isShow ? text : null,
  47547. inheritColor: visualColor,
  47548. defaultOpacity: visualOpacity,
  47549. labelFetcher: seriesModel,
  47550. labelDataIndex: thisNode.dataIndex
  47551. });
  47552. var textEl = rectEl.getTextContent();
  47553. var textStyle = textEl.style;
  47554. var textPadding = normalizeCssArray(textStyle.padding || 0);
  47555. if (upperLabelRect) {
  47556. rectEl.setTextConfig({
  47557. layoutRect: upperLabelRect
  47558. });
  47559. textEl.disableLabelLayout = true;
  47560. }
  47561. textEl.beforeUpdate = function () {
  47562. var width = Math.max((upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0);
  47563. var height = Math.max((upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0);
  47564. if (textStyle.width !== width || textStyle.height !== height) {
  47565. textEl.setStyle({
  47566. width: width,
  47567. height: height
  47568. });
  47569. }
  47570. };
  47571. textStyle.truncateMinChar = 2;
  47572. textStyle.lineOverflow = 'truncate';
  47573. addDrillDownIcon(textStyle, upperLabelRect, thisLayout);
  47574. var textEmphasisState = textEl.getState('emphasis');
  47575. addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout);
  47576. }
  47577. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  47578. var text = style ? style.text : null;
  47579. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  47580. var iconChar = seriesModel.get('drillDownIcon', true);
  47581. style.text = iconChar ? iconChar + ' ' + text : text;
  47582. }
  47583. }
  47584. function giveGraphic(storageName, Ctor, depth, z) {
  47585. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  47586. var lasts = lastsForAnimation[storageName];
  47587. if (element) {
  47588. // Remove from oldStorage
  47589. oldStorage[storageName][oldRawIndex] = null;
  47590. prepareAnimationWhenHasOld(lasts, element);
  47591. } // If invisible and no old element, do not create new element (for optimizing).
  47592. else if (!thisInvisible) {
  47593. element = new Ctor();
  47594. if (element instanceof Displayable) {
  47595. element.z = calculateZ(depth, z);
  47596. }
  47597. prepareAnimationWhenNoOld(lasts, element);
  47598. } // Set to thisStorage
  47599. return thisStorage[storageName][thisRawIndex] = element;
  47600. }
  47601. function prepareAnimationWhenHasOld(lasts, element) {
  47602. var lastCfg = lasts[thisRawIndex] = {};
  47603. if (element instanceof Group$1) {
  47604. lastCfg.oldX = element.x;
  47605. lastCfg.oldY = element.y;
  47606. } else {
  47607. lastCfg.oldShape = extend({}, element.shape);
  47608. }
  47609. } // If a element is new, we need to find the animation start point carefully,
  47610. // otherwise it will looks strange when 'zoomToNode'.
  47611. function prepareAnimationWhenNoOld(lasts, element) {
  47612. var lastCfg = lasts[thisRawIndex] = {};
  47613. var parentNode = thisNode.parentNode;
  47614. var isGroup = element instanceof Group;
  47615. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  47616. var parentOldX = 0;
  47617. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  47618. // For convenience, get old bounding rect from background.
  47619. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  47620. if (!reRoot && parentOldBg && parentOldBg.oldShape) {
  47621. parentOldX = parentOldBg.oldShape.width;
  47622. parentOldY = parentOldBg.oldShape.height;
  47623. } // When no parent old shape found, its parent is new too,
  47624. // so we can just use {x:0, y:0}.
  47625. if (isGroup) {
  47626. lastCfg.oldX = 0;
  47627. lastCfg.oldY = parentOldY;
  47628. } else {
  47629. lastCfg.oldShape = {
  47630. x: parentOldX,
  47631. y: parentOldY,
  47632. width: 0,
  47633. height: 0
  47634. };
  47635. }
  47636. } // Fade in, user can be aware that these nodes are new.
  47637. lastCfg.fadein = !isGroup;
  47638. }
  47639. } // We can not set all backgroud with the same z, Because the behaviour of
  47640. // drill down and roll up differ background creation sequence from tree
  47641. // hierarchy sequence, which cause that lowser background element overlap
  47642. // upper ones. So we calculate z based on depth.
  47643. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  47644. // treemap with large z overlaps other components.
  47645. function calculateZ(depth, zInLevel) {
  47646. var zb = depth * Z_BASE + zInLevel;
  47647. return (zb - 1) / zb;
  47648. }
  47649. var each$4 = each;
  47650. var isObject$4 = isObject;
  47651. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  47652. var VisualMapping =
  47653. /** @class */
  47654. function () {
  47655. function VisualMapping(option) {
  47656. var mappingMethod = option.mappingMethod;
  47657. var visualType = option.type;
  47658. var thisOption = this.option = clone(option);
  47659. this.type = visualType;
  47660. this.mappingMethod = mappingMethod;
  47661. this._normalizeData = normalizers[mappingMethod];
  47662. var visualHandler = VisualMapping.visualHandlers[visualType];
  47663. this.applyVisual = visualHandler.applyVisual;
  47664. this.getColorMapper = visualHandler.getColorMapper;
  47665. this._normalizedToVisual = visualHandler._normalizedToVisual[mappingMethod];
  47666. if (mappingMethod === 'piecewise') {
  47667. normalizeVisualRange(thisOption);
  47668. preprocessForPiecewise(thisOption);
  47669. } else if (mappingMethod === 'category') {
  47670. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  47671. // which need no more preprocess except normalize visual.
  47672. : normalizeVisualRange(thisOption, true);
  47673. } else {
  47674. // mappingMethod === 'linear' or 'fixed'
  47675. assert(mappingMethod !== 'linear' || thisOption.dataExtent);
  47676. normalizeVisualRange(thisOption);
  47677. }
  47678. }
  47679. VisualMapping.prototype.mapValueToVisual = function (value) {
  47680. var normalized = this._normalizeData(value);
  47681. return this._normalizedToVisual(normalized, value);
  47682. };
  47683. VisualMapping.prototype.getNormalizer = function () {
  47684. return bind(this._normalizeData, this);
  47685. };
  47686. /**
  47687. * List available visual types.
  47688. *
  47689. * @public
  47690. * @return {Array.<string>}
  47691. */
  47692. VisualMapping.listVisualTypes = function () {
  47693. return keys(VisualMapping.visualHandlers);
  47694. }; // /**
  47695. // * @public
  47696. // */
  47697. // static addVisualHandler(name, handler) {
  47698. // visualHandlers[name] = handler;
  47699. // }
  47700. /**
  47701. * @public
  47702. */
  47703. VisualMapping.isValidType = function (visualType) {
  47704. return VisualMapping.visualHandlers.hasOwnProperty(visualType);
  47705. };
  47706. /**
  47707. * Convinent method.
  47708. * Visual can be Object or Array or primary type.
  47709. */
  47710. VisualMapping.eachVisual = function (visual, callback, context) {
  47711. if (isObject(visual)) {
  47712. each(visual, callback, context);
  47713. } else {
  47714. callback.call(context, visual);
  47715. }
  47716. };
  47717. VisualMapping.mapVisual = function (visual, callback, context) {
  47718. var isPrimary;
  47719. var newVisual = isArray(visual) ? [] : isObject(visual) ? {} : (isPrimary = true, null);
  47720. VisualMapping.eachVisual(visual, function (v, key) {
  47721. var newVal = callback.call(context, v, key);
  47722. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  47723. });
  47724. return newVisual;
  47725. };
  47726. /**
  47727. * Retrieve visual properties from given object.
  47728. */
  47729. VisualMapping.retrieveVisuals = function (obj) {
  47730. var ret = {};
  47731. var hasVisual;
  47732. obj && each$4(VisualMapping.visualHandlers, function (h, visualType) {
  47733. if (obj.hasOwnProperty(visualType)) {
  47734. ret[visualType] = obj[visualType];
  47735. hasVisual = true;
  47736. }
  47737. });
  47738. return hasVisual ? ret : null;
  47739. };
  47740. /**
  47741. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  47742. *
  47743. * @public
  47744. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  47745. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  47746. * @return {Array.<string>} Sorted visual types.
  47747. */
  47748. VisualMapping.prepareVisualTypes = function (visualTypes) {
  47749. if (isArray(visualTypes)) {
  47750. visualTypes = visualTypes.slice();
  47751. } else if (isObject$4(visualTypes)) {
  47752. var types_1 = [];
  47753. each$4(visualTypes, function (item, type) {
  47754. types_1.push(type);
  47755. });
  47756. visualTypes = types_1;
  47757. } else {
  47758. return [];
  47759. }
  47760. visualTypes.sort(function (type1, type2) {
  47761. // color should be front of colorSaturation, colorAlpha, ...
  47762. // symbol and symbolSize do not matter.
  47763. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  47764. });
  47765. return visualTypes;
  47766. };
  47767. /**
  47768. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  47769. * Other visuals are only depends on themself.
  47770. */
  47771. VisualMapping.dependsOn = function (visualType1, visualType2) {
  47772. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  47773. };
  47774. /**
  47775. * @param value
  47776. * @param pieceList [{value: ..., interval: [min, max]}, ...]
  47777. * Always from small to big.
  47778. * @param findClosestWhenOutside Default to be false
  47779. * @return index
  47780. */
  47781. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  47782. var possibleI;
  47783. var abs = Infinity; // value has the higher priority.
  47784. for (var i = 0, len = pieceList.length; i < len; i++) {
  47785. var pieceValue = pieceList[i].value;
  47786. if (pieceValue != null) {
  47787. if (pieceValue === value // FIXME
  47788. // It is supposed to compare value according to value type of dimension,
  47789. // but currently value type can exactly be string or number.
  47790. // Compromise for numeric-like string (like '12'), especially
  47791. // in the case that visualMap.categories is ['22', '33'].
  47792. || typeof pieceValue === 'string' && pieceValue === value + '') {
  47793. return i;
  47794. }
  47795. findClosestWhenOutside && updatePossible(pieceValue, i);
  47796. }
  47797. }
  47798. for (var i = 0, len = pieceList.length; i < len; i++) {
  47799. var piece = pieceList[i];
  47800. var interval = piece.interval;
  47801. var close_1 = piece.close;
  47802. if (interval) {
  47803. if (interval[0] === -Infinity) {
  47804. if (littleThan(close_1[1], value, interval[1])) {
  47805. return i;
  47806. }
  47807. } else if (interval[1] === Infinity) {
  47808. if (littleThan(close_1[0], interval[0], value)) {
  47809. return i;
  47810. }
  47811. } else if (littleThan(close_1[0], interval[0], value) && littleThan(close_1[1], value, interval[1])) {
  47812. return i;
  47813. }
  47814. findClosestWhenOutside && updatePossible(interval[0], i);
  47815. findClosestWhenOutside && updatePossible(interval[1], i);
  47816. }
  47817. }
  47818. if (findClosestWhenOutside) {
  47819. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  47820. }
  47821. function updatePossible(val, index) {
  47822. var newAbs = Math.abs(val - value);
  47823. if (newAbs < abs) {
  47824. abs = newAbs;
  47825. possibleI = index;
  47826. }
  47827. }
  47828. };
  47829. VisualMapping.visualHandlers = {
  47830. color: {
  47831. applyVisual: makeApplyVisual('color'),
  47832. getColorMapper: function () {
  47833. var thisOption = this.option;
  47834. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  47835. !isNormalized && (value = this._normalizeData(value));
  47836. return doMapCategory.call(this, value);
  47837. } : function (value, isNormalized, out) {
  47838. // If output rgb array
  47839. // which will be much faster and useful in pixel manipulation
  47840. var returnRGBArray = !!out;
  47841. !isNormalized && (value = this._normalizeData(value));
  47842. out = fastLerp(value, thisOption.parsedVisual, out);
  47843. return returnRGBArray ? out : stringify(out, 'rgba');
  47844. }, this);
  47845. },
  47846. _normalizedToVisual: {
  47847. linear: function (normalized) {
  47848. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  47849. },
  47850. category: doMapCategory,
  47851. piecewise: function (normalized, value) {
  47852. var result = getSpecifiedVisual.call(this, value);
  47853. if (result == null) {
  47854. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  47855. }
  47856. return result;
  47857. },
  47858. fixed: doMapFixed
  47859. }
  47860. },
  47861. colorHue: makePartialColorVisualHandler(function (color$1, value) {
  47862. return modifyHSL(color$1, value);
  47863. }),
  47864. colorSaturation: makePartialColorVisualHandler(function (color$1, value) {
  47865. return modifyHSL(color$1, null, value);
  47866. }),
  47867. colorLightness: makePartialColorVisualHandler(function (color$1, value) {
  47868. return modifyHSL(color$1, null, null, value);
  47869. }),
  47870. colorAlpha: makePartialColorVisualHandler(function (color$1, value) {
  47871. return modifyAlpha(color$1, value);
  47872. }),
  47873. decal: {
  47874. applyVisual: makeApplyVisual('decal'),
  47875. _normalizedToVisual: {
  47876. linear: null,
  47877. category: doMapCategory,
  47878. piecewise: null,
  47879. fixed: null
  47880. }
  47881. },
  47882. opacity: {
  47883. applyVisual: makeApplyVisual('opacity'),
  47884. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  47885. },
  47886. liftZ: {
  47887. applyVisual: makeApplyVisual('liftZ'),
  47888. _normalizedToVisual: {
  47889. linear: doMapFixed,
  47890. category: doMapFixed,
  47891. piecewise: doMapFixed,
  47892. fixed: doMapFixed
  47893. }
  47894. },
  47895. symbol: {
  47896. applyVisual: function (value, getter, setter) {
  47897. var symbolCfg = this.mapValueToVisual(value);
  47898. setter('symbol', symbolCfg);
  47899. },
  47900. _normalizedToVisual: {
  47901. linear: doMapToArray,
  47902. category: doMapCategory,
  47903. piecewise: function (normalized, value) {
  47904. var result = getSpecifiedVisual.call(this, value);
  47905. if (result == null) {
  47906. result = doMapToArray.call(this, normalized);
  47907. }
  47908. return result;
  47909. },
  47910. fixed: doMapFixed
  47911. }
  47912. },
  47913. symbolSize: {
  47914. applyVisual: makeApplyVisual('symbolSize'),
  47915. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  47916. }
  47917. };
  47918. return VisualMapping;
  47919. }();
  47920. function preprocessForPiecewise(thisOption) {
  47921. var pieceList = thisOption.pieceList;
  47922. thisOption.hasSpecialVisual = false;
  47923. each(pieceList, function (piece, index) {
  47924. piece.originIndex = index; // piece.visual is "result visual value" but not
  47925. // a visual range, so it does not need to be normalized.
  47926. if (piece.visual != null) {
  47927. thisOption.hasSpecialVisual = true;
  47928. }
  47929. });
  47930. }
  47931. function preprocessForSpecifiedCategory(thisOption) {
  47932. // Hash categories.
  47933. var categories = thisOption.categories;
  47934. var categoryMap = thisOption.categoryMap = {};
  47935. var visual = thisOption.visual;
  47936. each$4(categories, function (cate, index) {
  47937. categoryMap[cate] = index;
  47938. }); // Process visual map input.
  47939. if (!isArray(visual)) {
  47940. var visualArr_1 = [];
  47941. if (isObject(visual)) {
  47942. each$4(visual, function (v, cate) {
  47943. var index = categoryMap[cate];
  47944. visualArr_1[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  47945. });
  47946. } else {
  47947. // Is primary type, represents default visual.
  47948. visualArr_1[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  47949. }
  47950. visual = setVisualToOption(thisOption, visualArr_1);
  47951. } // Remove categories that has no visual,
  47952. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  47953. for (var i = categories.length - 1; i >= 0; i--) {
  47954. if (visual[i] == null) {
  47955. delete categoryMap[categories[i]];
  47956. categories.pop();
  47957. }
  47958. }
  47959. }
  47960. function normalizeVisualRange(thisOption, isCategory) {
  47961. var visual = thisOption.visual;
  47962. var visualArr = [];
  47963. if (isObject(visual)) {
  47964. each$4(visual, function (v) {
  47965. visualArr.push(v);
  47966. });
  47967. } else if (visual != null) {
  47968. visualArr.push(visual);
  47969. }
  47970. var doNotNeedPair = {
  47971. color: 1,
  47972. symbol: 1
  47973. };
  47974. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  47975. // Do not care visualArr.length === 0, which is illegal.
  47976. visualArr[1] = visualArr[0];
  47977. }
  47978. setVisualToOption(thisOption, visualArr);
  47979. }
  47980. function makePartialColorVisualHandler(applyValue) {
  47981. return {
  47982. applyVisual: function (value, getter, setter) {
  47983. // Only used in HSL
  47984. var colorChannel = this.mapValueToVisual(value); // Must not be array value
  47985. setter('color', applyValue(getter('color'), colorChannel));
  47986. },
  47987. _normalizedToVisual: createNormalizedToNumericVisual([0, 1])
  47988. };
  47989. }
  47990. function doMapToArray(normalized) {
  47991. var visual = this.option.visual;
  47992. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {}; // TODO {}?
  47993. }
  47994. function makeApplyVisual(visualType) {
  47995. return function (value, getter, setter) {
  47996. setter(visualType, this.mapValueToVisual(value));
  47997. };
  47998. }
  47999. function doMapCategory(normalized) {
  48000. var visual = this.option.visual;
  48001. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  48002. }
  48003. function doMapFixed() {
  48004. // visual will be convert to array.
  48005. return this.option.visual[0];
  48006. }
  48007. /**
  48008. * Create mapped to numeric visual
  48009. */
  48010. function createNormalizedToNumericVisual(sourceExtent) {
  48011. return {
  48012. linear: function (normalized) {
  48013. return linearMap(normalized, sourceExtent, this.option.visual, true);
  48014. },
  48015. category: doMapCategory,
  48016. piecewise: function (normalized, value) {
  48017. var result = getSpecifiedVisual.call(this, value);
  48018. if (result == null) {
  48019. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  48020. }
  48021. return result;
  48022. },
  48023. fixed: doMapFixed
  48024. };
  48025. }
  48026. function getSpecifiedVisual(value) {
  48027. var thisOption = this.option;
  48028. var pieceList = thisOption.pieceList;
  48029. if (thisOption.hasSpecialVisual) {
  48030. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  48031. var piece = pieceList[pieceIndex];
  48032. if (piece && piece.visual) {
  48033. return piece.visual[this.type];
  48034. }
  48035. }
  48036. }
  48037. function setVisualToOption(thisOption, visualArr) {
  48038. thisOption.visual = visualArr;
  48039. if (thisOption.type === 'color') {
  48040. thisOption.parsedVisual = map(visualArr, function (item) {
  48041. return parse(item);
  48042. });
  48043. }
  48044. return visualArr;
  48045. }
  48046. /**
  48047. * Normalizers by mapping methods.
  48048. */
  48049. var normalizers = {
  48050. linear: function (value) {
  48051. return linearMap(value, this.option.dataExtent, [0, 1], true);
  48052. },
  48053. piecewise: function (value) {
  48054. var pieceList = this.option.pieceList;
  48055. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  48056. if (pieceIndex != null) {
  48057. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  48058. }
  48059. },
  48060. category: function (value) {
  48061. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal value
  48062. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  48063. },
  48064. fixed: noop
  48065. };
  48066. function littleThan(close, a, b) {
  48067. return close ? a <= b : a < b;
  48068. }
  48069. var ITEM_STYLE_NORMAL = 'itemStyle';
  48070. var inner$a = makeInner();
  48071. var treemapVisual = {
  48072. seriesType: 'treemap',
  48073. reset: function (seriesModel) {
  48074. var tree = seriesModel.getData().tree;
  48075. var root = tree.root;
  48076. if (root.isRemoved()) {
  48077. return;
  48078. }
  48079. travelTree(root, // Visual should calculate from tree root but not view root.
  48080. {}, seriesModel.getViewRoot().getAncestors(), seriesModel);
  48081. }
  48082. };
  48083. function travelTree(node, designatedVisual, viewRootAncestors, seriesModel) {
  48084. var nodeModel = node.getModel();
  48085. var nodeLayout = node.getLayout();
  48086. var data = node.hostTree.data; // Optimize
  48087. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  48088. return;
  48089. }
  48090. var nodeItemStyleModel = nodeModel.getModel(ITEM_STYLE_NORMAL);
  48091. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel);
  48092. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style'); // calculate border color
  48093. var borderColor = nodeItemStyleModel.get('borderColor');
  48094. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  48095. var thisNodeColor;
  48096. if (borderColorSaturation != null) {
  48097. // For performance, do not always execute 'calculateColor'.
  48098. thisNodeColor = calculateColor(visuals);
  48099. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  48100. }
  48101. existsStyle.stroke = borderColor;
  48102. var viewChildren = node.viewChildren;
  48103. if (!viewChildren || !viewChildren.length) {
  48104. thisNodeColor = calculateColor(visuals); // Apply visual to this node.
  48105. existsStyle.fill = thisNodeColor;
  48106. } else {
  48107. var mapping_1 = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  48108. each(viewChildren, function (child, index) {
  48109. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  48110. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  48111. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping_1, seriesModel);
  48112. travelTree(child, childVisual, viewRootAncestors, seriesModel);
  48113. }
  48114. });
  48115. }
  48116. }
  48117. function buildVisuals(nodeItemStyleModel, designatedVisual, seriesModel) {
  48118. var visuals = extend({}, designatedVisual);
  48119. var designatedVisualItemStyle = seriesModel.designatedVisualItemStyle;
  48120. each(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  48121. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  48122. designatedVisualItemStyle[visualName] = designatedVisual[visualName];
  48123. var val = nodeItemStyleModel.get(visualName);
  48124. designatedVisualItemStyle[visualName] = null;
  48125. val != null && (visuals[visualName] = val);
  48126. });
  48127. return visuals;
  48128. }
  48129. function calculateColor(visuals) {
  48130. var color = getValueVisualDefine(visuals, 'color');
  48131. if (color) {
  48132. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  48133. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  48134. if (colorSaturation) {
  48135. color = modifyHSL(color, null, null, colorSaturation);
  48136. }
  48137. if (colorAlpha) {
  48138. color = modifyAlpha(color, colorAlpha);
  48139. }
  48140. return color;
  48141. }
  48142. }
  48143. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  48144. return thisNodeColor != null // Can only be string
  48145. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  48146. }
  48147. function getValueVisualDefine(visuals, name) {
  48148. var value = visuals[name];
  48149. if (value != null && value !== 'none') {
  48150. return value;
  48151. }
  48152. }
  48153. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  48154. if (!viewChildren || !viewChildren.length) {
  48155. return;
  48156. }
  48157. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  48158. if (!rangeVisual) {
  48159. return;
  48160. }
  48161. var visualMin = nodeModel.get('visualMin');
  48162. var visualMax = nodeModel.get('visualMax');
  48163. var dataExtent = nodeLayout.dataExtent.slice();
  48164. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  48165. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  48166. var colorMappingBy = nodeModel.get('colorMappingBy');
  48167. var opt = {
  48168. type: rangeVisual.name,
  48169. dataExtent: dataExtent,
  48170. visual: rangeVisual.range
  48171. };
  48172. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  48173. opt.mappingMethod = 'category';
  48174. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  48175. } else {
  48176. opt.mappingMethod = 'linear';
  48177. }
  48178. var mapping = new VisualMapping(opt);
  48179. inner$a(mapping).drColorMappingBy = colorMappingBy;
  48180. return mapping;
  48181. } // Notice: If we dont have the attribute 'colorRange', but only use
  48182. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  48183. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  48184. // this problem will be encountered:
  48185. // If a level-1 node dont have children, and its siblings has children,
  48186. // and colorRange is set on level-1, then the node can not be colored.
  48187. // So we separate 'colorRange' and 'color' to different attributes.
  48188. function getRangeVisual(nodeModel, name) {
  48189. // 'colorRange', 'colorARange', 'colorSRange'.
  48190. // If not exsits on this node, fetch from levels and series.
  48191. var range = nodeModel.get(name);
  48192. return isArray(range) && range.length ? {
  48193. name: name,
  48194. range: range
  48195. } : null;
  48196. }
  48197. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  48198. var childVisuals = extend({}, visuals);
  48199. if (mapping) {
  48200. // Only support color, colorAlpha, colorSaturation.
  48201. var mappingType = mapping.type;
  48202. var colorMappingBy = mappingType === 'color' && inner$a(mapping).drColorMappingBy;
  48203. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  48204. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  48205. }
  48206. return childVisuals;
  48207. }
  48208. var mathMax$7 = Math.max;
  48209. var mathMin$7 = Math.min;
  48210. var retrieveValue = retrieve;
  48211. var each$5 = each;
  48212. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  48213. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  48214. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  48215. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  48216. /**
  48217. * @public
  48218. */
  48219. var treemapLayout = {
  48220. seriesType: 'treemap',
  48221. reset: function (seriesModel, ecModel, api, payload) {
  48222. // Layout result in each node:
  48223. // {x, y, width, height, area, borderWidth}
  48224. var ecWidth = api.getWidth();
  48225. var ecHeight = api.getHeight();
  48226. var seriesOption = seriesModel.option;
  48227. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  48228. width: api.getWidth(),
  48229. height: api.getHeight()
  48230. });
  48231. var size = seriesOption.size || []; // Compatible with ec2.
  48232. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  48233. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  48234. var payloadType = payload && payload.type;
  48235. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  48236. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  48237. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  48238. var viewRoot = seriesModel.getViewRoot();
  48239. var viewAbovePath = getPathToRoot(viewRoot);
  48240. if (payloadType !== 'treemapMove') {
  48241. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  48242. var sort_1 = seriesOption.sort;
  48243. if (sort_1 && sort_1 !== 'asc' && sort_1 !== 'desc') {
  48244. // Default to be desc order.
  48245. sort_1 = 'desc';
  48246. }
  48247. var options = {
  48248. squareRatio: seriesOption.squareRatio,
  48249. sort: sort_1,
  48250. leafDepth: seriesOption.leafDepth
  48251. }; // layout should be cleared because using updateView but not update.
  48252. viewRoot.hostTree.clearLayouts(); // TODO
  48253. // optimize: if out of view clip, do not layout.
  48254. // But take care that if do not render node out of view clip,
  48255. // how to calculate start po
  48256. var viewRootLayout_1 = {
  48257. x: 0,
  48258. y: 0,
  48259. width: rootSize[0],
  48260. height: rootSize[1],
  48261. area: rootSize[0] * rootSize[1]
  48262. };
  48263. viewRoot.setLayout(viewRootLayout_1);
  48264. squarify(viewRoot, options, false, 0); // Supplement layout.
  48265. viewRootLayout_1 = viewRoot.getLayout();
  48266. each$5(viewAbovePath, function (node, index) {
  48267. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  48268. node.setLayout(extend({
  48269. dataExtent: [childValue, childValue],
  48270. borderWidth: 0,
  48271. upperHeight: 0
  48272. }, viewRootLayout_1));
  48273. });
  48274. }
  48275. var treeRoot = seriesModel.getData().tree.root;
  48276. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  48277. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  48278. // 现在没有clip功能,暂时取ec高宽。
  48279. prunning(treeRoot, // Transform to base element coordinate system.
  48280. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  48281. }
  48282. };
  48283. /**
  48284. * Layout treemap with squarify algorithm.
  48285. * The original presentation of this algorithm
  48286. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  48287. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  48288. * The implementation of this algorithm was originally copied from "d3.js"
  48289. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  48290. * with some modifications made for this program.
  48291. * See the license statement at the head of this file.
  48292. *
  48293. * @protected
  48294. * @param {module:echarts/data/Tree~TreeNode} node
  48295. * @param {Object} options
  48296. * @param {string} options.sort 'asc' or 'desc'
  48297. * @param {number} options.squareRatio
  48298. * @param {boolean} hideChildren
  48299. * @param {number} depth
  48300. */
  48301. function squarify(node, options, hideChildren, depth) {
  48302. var width;
  48303. var height;
  48304. if (node.isRemoved()) {
  48305. return;
  48306. }
  48307. var thisLayout = node.getLayout();
  48308. width = thisLayout.width;
  48309. height = thisLayout.height; // Considering border and gap
  48310. var nodeModel = node.getModel();
  48311. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  48312. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  48313. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  48314. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  48315. var layoutOffset = borderWidth - halfGapWidth;
  48316. var layoutOffsetUpper = upperHeight - halfGapWidth;
  48317. node.setLayout({
  48318. borderWidth: borderWidth,
  48319. upperHeight: upperHeight,
  48320. upperLabelHeight: upperLabelHeight
  48321. }, true);
  48322. width = mathMax$7(width - 2 * layoutOffset, 0);
  48323. height = mathMax$7(height - layoutOffset - layoutOffsetUpper, 0);
  48324. var totalArea = width * height;
  48325. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  48326. if (!viewChildren.length) {
  48327. return;
  48328. }
  48329. var rect = {
  48330. x: layoutOffset,
  48331. y: layoutOffsetUpper,
  48332. width: width,
  48333. height: height
  48334. };
  48335. var rowFixedLength = mathMin$7(width, height);
  48336. var best = Infinity; // the best row score so far
  48337. var row = [];
  48338. row.area = 0;
  48339. for (var i = 0, len = viewChildren.length; i < len;) {
  48340. var child = viewChildren[i];
  48341. row.push(child);
  48342. row.area += child.getLayout().area;
  48343. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  48344. if (score <= best) {
  48345. i++;
  48346. best = score;
  48347. } // abort, and try a different orientation
  48348. else {
  48349. row.area -= row.pop().getLayout().area;
  48350. position(row, rowFixedLength, rect, halfGapWidth, false);
  48351. rowFixedLength = mathMin$7(rect.width, rect.height);
  48352. row.length = row.area = 0;
  48353. best = Infinity;
  48354. }
  48355. }
  48356. if (row.length) {
  48357. position(row, rowFixedLength, rect, halfGapWidth, true);
  48358. }
  48359. if (!hideChildren) {
  48360. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  48361. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  48362. hideChildren = true;
  48363. }
  48364. }
  48365. for (var i = 0, len = viewChildren.length; i < len; i++) {
  48366. squarify(viewChildren[i], options, hideChildren, depth + 1);
  48367. }
  48368. }
  48369. /**
  48370. * Set area to each child, and calculate data extent for visual coding.
  48371. */
  48372. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  48373. var viewChildren = node.children || [];
  48374. var orderBy = options.sort;
  48375. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  48376. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  48377. if (hideChildren && !overLeafDepth) {
  48378. return node.viewChildren = [];
  48379. } // Sort children, order by desc.
  48380. viewChildren = filter(viewChildren, function (child) {
  48381. return !child.isRemoved();
  48382. });
  48383. sort$1(viewChildren, orderBy);
  48384. var info = statistic(nodeModel, viewChildren, orderBy);
  48385. if (info.sum === 0) {
  48386. return node.viewChildren = [];
  48387. }
  48388. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  48389. if (info.sum === 0) {
  48390. return node.viewChildren = [];
  48391. } // Set area to each child.
  48392. for (var i = 0, len = viewChildren.length; i < len; i++) {
  48393. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  48394. viewChildren[i].setLayout({
  48395. area: area
  48396. });
  48397. }
  48398. if (overLeafDepth) {
  48399. viewChildren.length && node.setLayout({
  48400. isLeafRoot: true
  48401. }, true);
  48402. viewChildren.length = 0;
  48403. }
  48404. node.viewChildren = viewChildren;
  48405. node.setLayout({
  48406. dataExtent: info.dataExtent
  48407. }, true);
  48408. return viewChildren;
  48409. }
  48410. /**
  48411. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  48412. */
  48413. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  48414. // visibleMin is not supported yet when no option.sort.
  48415. if (!orderBy) {
  48416. return sum;
  48417. }
  48418. var visibleMin = nodeModel.get('visibleMin');
  48419. var len = orderedChildren.length;
  48420. var deletePoint = len; // Always travel from little value to big value.
  48421. for (var i = len - 1; i >= 0; i--) {
  48422. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  48423. if (value / sum * totalArea < visibleMin) {
  48424. deletePoint = i;
  48425. sum -= value;
  48426. }
  48427. }
  48428. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  48429. return sum;
  48430. }
  48431. /**
  48432. * Sort
  48433. */
  48434. function sort$1(viewChildren, orderBy) {
  48435. if (orderBy) {
  48436. viewChildren.sort(function (a, b) {
  48437. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  48438. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  48439. });
  48440. }
  48441. return viewChildren;
  48442. }
  48443. /**
  48444. * Statistic
  48445. */
  48446. function statistic(nodeModel, children, orderBy) {
  48447. // Calculate sum.
  48448. var sum = 0;
  48449. for (var i = 0, len = children.length; i < len; i++) {
  48450. sum += children[i].getValue();
  48451. } // Statistic data extent for latter visual coding.
  48452. // Notice: data extent should be calculate based on raw children
  48453. // but not filtered view children, otherwise visual mapping will not
  48454. // be stable when zoom (where children is filtered by visibleMin).
  48455. var dimension = nodeModel.get('visualDimension');
  48456. var dataExtent; // The same as area dimension.
  48457. if (!children || !children.length) {
  48458. dataExtent = [NaN, NaN];
  48459. } else if (dimension === 'value' && orderBy) {
  48460. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  48461. orderBy === 'asc' && dataExtent.reverse();
  48462. } // Other dimension.
  48463. else {
  48464. dataExtent = [Infinity, -Infinity];
  48465. each$5(children, function (child) {
  48466. var value = child.getValue(dimension);
  48467. value < dataExtent[0] && (dataExtent[0] = value);
  48468. value > dataExtent[1] && (dataExtent[1] = value);
  48469. });
  48470. }
  48471. return {
  48472. sum: sum,
  48473. dataExtent: dataExtent
  48474. };
  48475. }
  48476. /**
  48477. * Computes the score for the specified row,
  48478. * as the worst aspect ratio.
  48479. */
  48480. function worst(row, rowFixedLength, ratio) {
  48481. var areaMax = 0;
  48482. var areaMin = Infinity;
  48483. for (var i = 0, area = void 0, len = row.length; i < len; i++) {
  48484. area = row[i].getLayout().area;
  48485. if (area) {
  48486. area < areaMin && (areaMin = area);
  48487. area > areaMax && (areaMax = area);
  48488. }
  48489. }
  48490. var squareArea = row.area * row.area;
  48491. var f = rowFixedLength * rowFixedLength * ratio;
  48492. return squareArea ? mathMax$7(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  48493. }
  48494. /**
  48495. * Positions the specified row of nodes. Modifies `rect`.
  48496. */
  48497. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  48498. // When rowFixedLength === rect.width,
  48499. // it is horizontal subdivision,
  48500. // rowFixedLength is the width of the subdivision,
  48501. // rowOtherLength is the height of the subdivision,
  48502. // and nodes will be positioned from left to right.
  48503. // wh[idx0WhenH] means: when horizontal,
  48504. // wh[idx0WhenH] => wh[0] => 'width'.
  48505. // xy[idx1WhenH] => xy[1] => 'y'.
  48506. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  48507. var idx1WhenH = 1 - idx0WhenH;
  48508. var xy = ['x', 'y'];
  48509. var wh = ['width', 'height'];
  48510. var last = rect[xy[idx0WhenH]];
  48511. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  48512. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  48513. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  48514. }
  48515. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  48516. var node = row[i];
  48517. var nodeLayout = {};
  48518. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  48519. 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.
  48520. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  48521. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  48522. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$7(modWH - 2 * halfGapWidth, 0);
  48523. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$7(halfGapWidth, wh1 / 2);
  48524. nodeLayout[xy[idx0WhenH]] = last + mathMin$7(halfGapWidth, wh0 / 2);
  48525. last += modWH;
  48526. node.setLayout(nodeLayout, true);
  48527. }
  48528. rect[xy[idx1WhenH]] += rowOtherLength;
  48529. rect[wh[idx1WhenH]] -= rowOtherLength;
  48530. } // Return [containerWidth, containerHeight] as default.
  48531. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  48532. // If targetInfo.node exists, we zoom to the node,
  48533. // so estimate whold width and heigth by target node.
  48534. var currNode = (targetInfo || {}).node;
  48535. var defaultSize = [containerWidth, containerHeight];
  48536. if (!currNode || currNode === viewRoot) {
  48537. return defaultSize;
  48538. }
  48539. var parent;
  48540. var viewArea = containerWidth * containerHeight;
  48541. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  48542. while (parent = currNode.parentNode) {
  48543. // jshint ignore:line
  48544. var sum = 0;
  48545. var siblings = parent.children;
  48546. for (var i = 0, len = siblings.length; i < len; i++) {
  48547. sum += siblings[i].getValue();
  48548. }
  48549. var currNodeValue = currNode.getValue();
  48550. if (currNodeValue === 0) {
  48551. return defaultSize;
  48552. }
  48553. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  48554. var parentModel = parent.getModel();
  48555. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  48556. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel));
  48557. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  48558. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  48559. currNode = parent;
  48560. }
  48561. area < viewArea && (area = viewArea);
  48562. var scale = Math.pow(area / viewArea, 0.5);
  48563. return [containerWidth * scale, containerHeight * scale];
  48564. } // Root postion base on coord of containerGroup
  48565. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  48566. if (rootRect) {
  48567. return {
  48568. x: rootRect.x,
  48569. y: rootRect.y
  48570. };
  48571. }
  48572. var defaultPosition = {
  48573. x: 0,
  48574. y: 0
  48575. };
  48576. if (!targetInfo) {
  48577. return defaultPosition;
  48578. } // If targetInfo is fetched by 'retrieveTargetInfo',
  48579. // old tree and new tree are the same tree,
  48580. // so the node still exists and we can visit it.
  48581. var targetNode = targetInfo.node;
  48582. var layout = targetNode.getLayout();
  48583. if (!layout) {
  48584. return defaultPosition;
  48585. } // Transform coord from local to container.
  48586. var targetCenter = [layout.width / 2, layout.height / 2];
  48587. var node = targetNode;
  48588. while (node) {
  48589. var nodeLayout = node.getLayout();
  48590. targetCenter[0] += nodeLayout.x;
  48591. targetCenter[1] += nodeLayout.y;
  48592. node = node.parentNode;
  48593. }
  48594. return {
  48595. x: layoutInfo.width / 2 - targetCenter[0],
  48596. y: layoutInfo.height / 2 - targetCenter[1]
  48597. };
  48598. } // Mark nodes visible for prunning when visual coding and rendering.
  48599. // Prunning depends on layout and root position, so we have to do it after layout.
  48600. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  48601. var nodeLayout = node.getLayout();
  48602. var nodeInViewAbovePath = viewAbovePath[depth];
  48603. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  48604. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  48605. return;
  48606. }
  48607. node.setLayout({
  48608. // isInView means: viewRoot sub tree + viewAbovePath
  48609. isInView: true,
  48610. // invisible only means: outside view clip so that the node can not
  48611. // see but still layout for animation preparation but not render.
  48612. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  48613. isAboveViewRoot: isAboveViewRoot
  48614. }, true); // Transform to child coordinate.
  48615. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  48616. each$5(node.viewChildren || [], function (child) {
  48617. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  48618. });
  48619. }
  48620. function getUpperLabelHeight(model) {
  48621. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  48622. }
  48623. function install$c(registers) {
  48624. registers.registerSeriesModel(TreemapSeriesModel);
  48625. registers.registerChartView(TreemapView);
  48626. registers.registerVisual(treemapVisual);
  48627. registers.registerLayout(treemapLayout);
  48628. installTreemapAction(registers);
  48629. }
  48630. /*
  48631. * Licensed to the Apache Software Foundation (ASF) under one
  48632. * or more contributor license agreements. See the NOTICE file
  48633. * distributed with this work for additional information
  48634. * regarding copyright ownership. The ASF licenses this file
  48635. * to you under the Apache License, Version 2.0 (the
  48636. * "License"); you may not use this file except in compliance
  48637. * with the License. You may obtain a copy of the License at
  48638. *
  48639. * http://www.apache.org/licenses/LICENSE-2.0
  48640. *
  48641. * Unless required by applicable law or agreed to in writing,
  48642. * software distributed under the License is distributed on an
  48643. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48644. * KIND, either express or implied. See the License for the
  48645. * specific language governing permissions and limitations
  48646. * under the License.
  48647. */
  48648. /**
  48649. * AUTO-GENERATED FILE. DO NOT MODIFY.
  48650. */
  48651. /*
  48652. * Licensed to the Apache Software Foundation (ASF) under one
  48653. * or more contributor license agreements. See the NOTICE file
  48654. * distributed with this work for additional information
  48655. * regarding copyright ownership. The ASF licenses this file
  48656. * to you under the Apache License, Version 2.0 (the
  48657. * "License"); you may not use this file except in compliance
  48658. * with the License. You may obtain a copy of the License at
  48659. *
  48660. * http://www.apache.org/licenses/LICENSE-2.0
  48661. *
  48662. * Unless required by applicable law or agreed to in writing,
  48663. * software distributed under the License is distributed on an
  48664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48665. * KIND, either express or implied. See the License for the
  48666. * specific language governing permissions and limitations
  48667. * under the License.
  48668. */
  48669. function categoryFilter(ecModel) {
  48670. var legendModels = ecModel.findComponents({
  48671. mainType: 'legend'
  48672. });
  48673. if (!legendModels || !legendModels.length) {
  48674. return;
  48675. }
  48676. ecModel.eachSeriesByType('graph', function (graphSeries) {
  48677. var categoriesData = graphSeries.getCategoriesData();
  48678. var graph = graphSeries.getGraph();
  48679. var data = graph.data;
  48680. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  48681. data.filterSelf(function (idx) {
  48682. var model = data.getItemModel(idx);
  48683. var category = model.getShallow('category');
  48684. if (category != null) {
  48685. if (typeof category === 'number') {
  48686. category = categoryNames[category];
  48687. } // If in any legend component the status is not selected.
  48688. for (var i = 0; i < legendModels.length; i++) {
  48689. if (!legendModels[i].isSelected(category)) {
  48690. return false;
  48691. }
  48692. }
  48693. }
  48694. return true;
  48695. });
  48696. });
  48697. }
  48698. function categoryVisual(ecModel) {
  48699. var paletteScope = {};
  48700. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48701. var categoriesData = seriesModel.getCategoriesData();
  48702. var data = seriesModel.getData();
  48703. var categoryNameIdxMap = {};
  48704. categoriesData.each(function (idx) {
  48705. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  48706. categoryNameIdxMap['ec-' + name] = idx;
  48707. var itemModel = categoriesData.getItemModel(idx);
  48708. var style = itemModel.getModel('itemStyle').getItemStyle();
  48709. if (!style.fill) {
  48710. // Get color from palette.
  48711. style.fill = seriesModel.getColorFromPalette(name, paletteScope);
  48712. }
  48713. categoriesData.setItemVisual(idx, 'style', style);
  48714. var symbolVisualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  48715. for (var i = 0; i < symbolVisualList.length; i++) {
  48716. var symbolVisual = itemModel.getShallow(symbolVisualList[i], true);
  48717. if (symbolVisual != null) {
  48718. categoriesData.setItemVisual(idx, symbolVisualList[i], symbolVisual);
  48719. }
  48720. }
  48721. }); // Assign category color to visual
  48722. if (categoriesData.count()) {
  48723. data.each(function (idx) {
  48724. var model = data.getItemModel(idx);
  48725. var categoryIdx = model.getShallow('category');
  48726. if (categoryIdx != null) {
  48727. if (typeof categoryIdx === 'string') {
  48728. categoryIdx = categoryNameIdxMap['ec-' + categoryIdx];
  48729. }
  48730. var categoryStyle = categoriesData.getItemVisual(categoryIdx, 'style');
  48731. var style = data.ensureUniqueItemVisual(idx, 'style');
  48732. extend(style, categoryStyle);
  48733. var visualList = ['symbol', 'symbolSize', 'symbolKeepAspect'];
  48734. for (var i = 0; i < visualList.length; i++) {
  48735. data.setItemVisual(idx, visualList[i], categoriesData.getItemVisual(categoryIdx, visualList[i]));
  48736. }
  48737. }
  48738. });
  48739. }
  48740. });
  48741. }
  48742. function normalize$2(a) {
  48743. if (!(a instanceof Array)) {
  48744. a = [a, a];
  48745. }
  48746. return a;
  48747. }
  48748. function graphEdgeVisual(ecModel) {
  48749. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48750. var graph = seriesModel.getGraph();
  48751. var edgeData = seriesModel.getEdgeData();
  48752. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  48753. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize')); // const colorQuery = ['lineStyle', 'color'] as const;
  48754. // const opacityQuery = ['lineStyle', 'opacity'] as const;
  48755. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  48756. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  48757. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  48758. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  48759. edgeData.setVisual('style', seriesModel.getModel('lineStyle').getLineStyle());
  48760. edgeData.each(function (idx) {
  48761. var itemModel = edgeData.getItemModel(idx);
  48762. var edge = graph.getEdgeByIndex(idx);
  48763. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  48764. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  48765. var style = itemModel.getModel('lineStyle').getLineStyle();
  48766. var existsStyle = edgeData.ensureUniqueItemVisual(idx, 'style');
  48767. extend(existsStyle, style);
  48768. switch (existsStyle.stroke) {
  48769. case 'source':
  48770. {
  48771. var nodeStyle = edge.node1.getVisual('style');
  48772. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  48773. break;
  48774. }
  48775. case 'target':
  48776. {
  48777. var nodeStyle = edge.node2.getVisual('style');
  48778. existsStyle.stroke = nodeStyle && nodeStyle.fill;
  48779. break;
  48780. }
  48781. }
  48782. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  48783. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  48784. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  48785. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  48786. });
  48787. });
  48788. }
  48789. var KEY_DELIMITER = '-->';
  48790. /**
  48791. * params handler
  48792. * @param {module:echarts/model/SeriesModel} seriesModel
  48793. * @returns {*}
  48794. */
  48795. var getAutoCurvenessParams = function (seriesModel) {
  48796. return seriesModel.get('autoCurveness') || null;
  48797. };
  48798. /**
  48799. * Generate a list of edge curvatures, 20 is the default
  48800. * @param {module:echarts/model/SeriesModel} seriesModel
  48801. * @param {number} appendLength
  48802. * @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]
  48803. */
  48804. var createCurveness = function (seriesModel, appendLength) {
  48805. var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
  48806. var length = 20;
  48807. var curvenessList = []; // handler the function set
  48808. if (typeof autoCurvenessParmas === 'number') {
  48809. length = autoCurvenessParmas;
  48810. } else if (isArray(autoCurvenessParmas)) {
  48811. seriesModel.__curvenessList = autoCurvenessParmas;
  48812. return;
  48813. } // append length
  48814. if (appendLength > length) {
  48815. length = appendLength;
  48816. } // make sure the length is even
  48817. var len = length % 2 ? length + 2 : length + 3;
  48818. curvenessList = [];
  48819. for (var i = 0; i < len; i++) {
  48820. curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
  48821. }
  48822. seriesModel.__curvenessList = curvenessList;
  48823. };
  48824. /**
  48825. * Create different cache key data in the positive and negative directions, in order to set the curvature later
  48826. * @param {number|string|module:echarts/data/Graph.Node} n1
  48827. * @param {number|string|module:echarts/data/Graph.Node} n2
  48828. * @param {module:echarts/model/SeriesModel} seriesModel
  48829. * @returns {string} key
  48830. */
  48831. var getKeyOfEdges = function (n1, n2, seriesModel) {
  48832. var source = [n1.id, n1.dataIndex].join('.');
  48833. var target = [n2.id, n2.dataIndex].join('.');
  48834. return [seriesModel.uid, source, target].join(KEY_DELIMITER);
  48835. };
  48836. /**
  48837. * get opposite key
  48838. * @param {string} key
  48839. * @returns {string}
  48840. */
  48841. var getOppositeKey = function (key) {
  48842. var keys = key.split(KEY_DELIMITER);
  48843. return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
  48844. };
  48845. /**
  48846. * get edgeMap with key
  48847. * @param edge
  48848. * @param {module:echarts/model/SeriesModel} seriesModel
  48849. */
  48850. var getEdgeFromMap = function (edge, seriesModel) {
  48851. var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  48852. return seriesModel.__edgeMap[key];
  48853. };
  48854. /**
  48855. * calculate all cases total length
  48856. * @param edge
  48857. * @param seriesModel
  48858. * @returns {number}
  48859. */
  48860. var getTotalLengthBetweenNodes = function (edge, seriesModel) {
  48861. var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
  48862. var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);
  48863. return len + lenV;
  48864. };
  48865. /**
  48866. *
  48867. * @param key
  48868. */
  48869. var getEdgeMapLengthWithKey = function (key, seriesModel) {
  48870. var edgeMap = seriesModel.__edgeMap;
  48871. return edgeMap[key] ? edgeMap[key].length : 0;
  48872. };
  48873. /**
  48874. * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
  48875. * @see /graph/GraphSeries.js@getInitialData
  48876. * @param {module:echarts/model/SeriesModel} seriesModel
  48877. */
  48878. function initCurvenessList(seriesModel) {
  48879. if (!getAutoCurvenessParams(seriesModel)) {
  48880. return;
  48881. }
  48882. seriesModel.__curvenessList = [];
  48883. seriesModel.__edgeMap = {}; // calc the array of curveness List
  48884. createCurveness(seriesModel);
  48885. }
  48886. /**
  48887. * set edgeMap with key
  48888. * @param {number|string|module:echarts/data/Graph.Node} n1
  48889. * @param {number|string|module:echarts/data/Graph.Node} n2
  48890. * @param {module:echarts/model/SeriesModel} seriesModel
  48891. * @param {number} index
  48892. */
  48893. function createEdgeMapForCurveness(n1, n2, seriesModel, index) {
  48894. if (!getAutoCurvenessParams(seriesModel)) {
  48895. return;
  48896. }
  48897. var key = getKeyOfEdges(n1, n2, seriesModel);
  48898. var edgeMap = seriesModel.__edgeMap;
  48899. var oppositeEdges = edgeMap[getOppositeKey(key)]; // set direction
  48900. if (edgeMap[key] && !oppositeEdges) {
  48901. edgeMap[key].isForward = true;
  48902. } else if (oppositeEdges && edgeMap[key]) {
  48903. oppositeEdges.isForward = true;
  48904. edgeMap[key].isForward = false;
  48905. }
  48906. edgeMap[key] = edgeMap[key] || [];
  48907. edgeMap[key].push(index);
  48908. }
  48909. /**
  48910. * get curvature for edge
  48911. * @param edge
  48912. * @param {module:echarts/model/SeriesModel} seriesModel
  48913. * @param index
  48914. */
  48915. function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
  48916. var autoCurvenessParams = getAutoCurvenessParams(seriesModel);
  48917. var isArrayParam = isArray(autoCurvenessParams);
  48918. if (!autoCurvenessParams) {
  48919. return null;
  48920. }
  48921. var edgeArray = getEdgeFromMap(edge, seriesModel);
  48922. if (!edgeArray) {
  48923. return null;
  48924. }
  48925. var edgeIndex = -1;
  48926. for (var i = 0; i < edgeArray.length; i++) {
  48927. if (edgeArray[i] === index) {
  48928. edgeIndex = i;
  48929. break;
  48930. }
  48931. } // if totalLen is Longer createCurveness
  48932. var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
  48933. createCurveness(seriesModel, totalLen);
  48934. edge.lineStyle = edge.lineStyle || {}; // if is opposite edge, must set curvenss to opposite number
  48935. var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
  48936. var curvenessList = seriesModel.__curvenessList; // if pass array no need parity
  48937. var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;
  48938. if (!edgeArray.isForward) {
  48939. // the opposite edge show outside
  48940. var oppositeKey = getOppositeKey(curKey);
  48941. var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
  48942. var resValue = curvenessList[edgeIndex + len + parityCorrection]; // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
  48943. if (needReverse) {
  48944. // set as array may make the parity handle with the len of opposite
  48945. if (isArrayParam) {
  48946. if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
  48947. return (len + parityCorrection) % 2 ? resValue : -resValue;
  48948. } else {
  48949. return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
  48950. }
  48951. } else {
  48952. return (len + parityCorrection) % 2 ? resValue : -resValue;
  48953. }
  48954. } else {
  48955. return curvenessList[edgeIndex + len + parityCorrection];
  48956. }
  48957. } else {
  48958. return curvenessList[parityCorrection + edgeIndex];
  48959. }
  48960. }
  48961. function simpleLayout(seriesModel) {
  48962. var coordSys = seriesModel.coordinateSystem;
  48963. if (coordSys && coordSys.type !== 'view') {
  48964. return;
  48965. }
  48966. var graph = seriesModel.getGraph();
  48967. graph.eachNode(function (node) {
  48968. var model = node.getModel();
  48969. node.setLayout([+model.get('x'), +model.get('y')]);
  48970. });
  48971. simpleLayoutEdge(graph, seriesModel);
  48972. }
  48973. function simpleLayoutEdge(graph, seriesModel) {
  48974. graph.eachEdge(function (edge, index) {
  48975. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, seriesModel, index, true), 0);
  48976. var p1 = clone$1(edge.node1.getLayout());
  48977. var p2 = clone$1(edge.node2.getLayout());
  48978. var points = [p1, p2];
  48979. if (+curveness) {
  48980. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  48981. }
  48982. edge.setLayout(points);
  48983. });
  48984. }
  48985. function graphSimpleLayout(ecModel, api) {
  48986. ecModel.eachSeriesByType('graph', function (seriesModel) {
  48987. var layout = seriesModel.get('layout');
  48988. var coordSys = seriesModel.coordinateSystem;
  48989. if (coordSys && coordSys.type !== 'view') {
  48990. var data_1 = seriesModel.getData();
  48991. var dimensions_1 = [];
  48992. each(coordSys.dimensions, function (coordDim) {
  48993. dimensions_1 = dimensions_1.concat(data_1.mapDimensionsAll(coordDim));
  48994. });
  48995. for (var dataIndex = 0; dataIndex < data_1.count(); dataIndex++) {
  48996. var value = [];
  48997. var hasValue = false;
  48998. for (var i = 0; i < dimensions_1.length; i++) {
  48999. var val = data_1.get(dimensions_1[i], dataIndex);
  49000. if (!isNaN(val)) {
  49001. hasValue = true;
  49002. }
  49003. value.push(val);
  49004. }
  49005. if (hasValue) {
  49006. data_1.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  49007. } else {
  49008. // Also {Array.<number>}, not undefined to avoid if...else... statement
  49009. data_1.setItemLayout(dataIndex, [NaN, NaN]);
  49010. }
  49011. }
  49012. simpleLayoutEdge(data_1.graph, seriesModel);
  49013. } else if (!layout || layout === 'none') {
  49014. simpleLayout(seriesModel);
  49015. }
  49016. });
  49017. }
  49018. /*
  49019. * Licensed to the Apache Software Foundation (ASF) under one
  49020. * or more contributor license agreements. See the NOTICE file
  49021. * distributed with this work for additional information
  49022. * regarding copyright ownership. The ASF licenses this file
  49023. * to you under the Apache License, Version 2.0 (the
  49024. * "License"); you may not use this file except in compliance
  49025. * with the License. You may obtain a copy of the License at
  49026. *
  49027. * http://www.apache.org/licenses/LICENSE-2.0
  49028. *
  49029. * Unless required by applicable law or agreed to in writing,
  49030. * software distributed under the License is distributed on an
  49031. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49032. * KIND, either express or implied. See the License for the
  49033. * specific language governing permissions and limitations
  49034. * under the License.
  49035. */
  49036. /**
  49037. * AUTO-GENERATED FILE. DO NOT MODIFY.
  49038. */
  49039. /*
  49040. * Licensed to the Apache Software Foundation (ASF) under one
  49041. * or more contributor license agreements. See the NOTICE file
  49042. * distributed with this work for additional information
  49043. * regarding copyright ownership. The ASF licenses this file
  49044. * to you under the Apache License, Version 2.0 (the
  49045. * "License"); you may not use this file except in compliance
  49046. * with the License. You may obtain a copy of the License at
  49047. *
  49048. * http://www.apache.org/licenses/LICENSE-2.0
  49049. *
  49050. * Unless required by applicable law or agreed to in writing,
  49051. * software distributed under the License is distributed on an
  49052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49053. * KIND, either express or implied. See the License for the
  49054. * specific language governing permissions and limitations
  49055. * under the License.
  49056. */
  49057. function getNodeGlobalScale(seriesModel) {
  49058. var coordSys = seriesModel.coordinateSystem;
  49059. if (coordSys.type !== 'view') {
  49060. return 1;
  49061. }
  49062. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  49063. var groupZoom = coordSys.scaleX; // Scale node when zoom changes
  49064. var roamZoom = coordSys.getZoom();
  49065. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  49066. return nodeScale / groupZoom;
  49067. }
  49068. function getSymbolSize(node) {
  49069. var symbolSize = node.getVisual('symbolSize');
  49070. if (symbolSize instanceof Array) {
  49071. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  49072. }
  49073. return +symbolSize;
  49074. }
  49075. var PI$6 = Math.PI;
  49076. var _symbolRadiansHalf = [];
  49077. /**
  49078. * `basedOn` can be:
  49079. * 'value':
  49080. * This layout is not accurate and have same bad case. For example,
  49081. * if the min value is very smaller than the max value, the nodes
  49082. * with the min value probably overlap even though there is enough
  49083. * space to layout them. So we only use this approach in the as the
  49084. * init layout of the force layout.
  49085. * FIXME
  49086. * Probably we do not need this method any more but use
  49087. * `basedOn: 'symbolSize'` in force layout if
  49088. * delay its init operations to GraphView.
  49089. * 'symbolSize':
  49090. * This approach work only if all of the symbol size calculated.
  49091. * That is, the progressive rendering is not applied to graph.
  49092. * FIXME
  49093. * If progressive rendering is applied to graph some day,
  49094. * probably we have to use `basedOn: 'value'`.
  49095. */
  49096. function circularLayout(seriesModel, basedOn) {
  49097. var coordSys = seriesModel.coordinateSystem;
  49098. if (coordSys && coordSys.type !== 'view') {
  49099. return;
  49100. }
  49101. var rect = coordSys.getBoundingRect();
  49102. var nodeData = seriesModel.getData();
  49103. var graph = nodeData.graph;
  49104. var cx = rect.width / 2 + rect.x;
  49105. var cy = rect.height / 2 + rect.y;
  49106. var r = Math.min(rect.width, rect.height) / 2;
  49107. var count = nodeData.count();
  49108. nodeData.setLayout({
  49109. cx: cx,
  49110. cy: cy
  49111. });
  49112. if (!count) {
  49113. return;
  49114. }
  49115. _layoutNodesBasedOn[basedOn](seriesModel, graph, nodeData, r, cx, cy, count);
  49116. graph.eachEdge(function (edge, index) {
  49117. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), getCurvenessForEdge(edge, seriesModel, index), 0);
  49118. var p1 = clone$1(edge.node1.getLayout());
  49119. var p2 = clone$1(edge.node2.getLayout());
  49120. var cp1;
  49121. var x12 = (p1[0] + p2[0]) / 2;
  49122. var y12 = (p1[1] + p2[1]) / 2;
  49123. if (+curveness) {
  49124. curveness *= 3;
  49125. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  49126. }
  49127. edge.setLayout([p1, p2, cp1]);
  49128. });
  49129. }
  49130. var _layoutNodesBasedOn = {
  49131. value: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  49132. var angle = 0;
  49133. var sum = nodeData.getSum('value');
  49134. var unitAngle = Math.PI * 2 / (sum || count);
  49135. graph.eachNode(function (node) {
  49136. var value = node.getValue('value');
  49137. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  49138. angle += radianHalf;
  49139. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  49140. angle += radianHalf;
  49141. });
  49142. },
  49143. symbolSize: function (seriesModel, graph, nodeData, r, cx, cy, count) {
  49144. var sumRadian = 0;
  49145. _symbolRadiansHalf.length = count;
  49146. var nodeScale = getNodeGlobalScale(seriesModel);
  49147. graph.eachNode(function (node) {
  49148. var symbolSize = getSymbolSize(node); // Normally this case will not happen, but we still add
  49149. // some the defensive code (2px is an arbitrary value).
  49150. isNaN(symbolSize) && (symbolSize = 2);
  49151. symbolSize < 0 && (symbolSize = 0);
  49152. symbolSize *= nodeScale;
  49153. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  49154. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$6 / 2);
  49155. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  49156. sumRadian += symbolRadianHalf * 2;
  49157. });
  49158. var halfRemainRadian = (2 * PI$6 - sumRadian) / count / 2;
  49159. var angle = 0;
  49160. graph.eachNode(function (node) {
  49161. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  49162. angle += radianHalf;
  49163. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  49164. angle += radianHalf;
  49165. });
  49166. }
  49167. };
  49168. function graphCircularLayout(ecModel) {
  49169. ecModel.eachSeriesByType('graph', function (seriesModel) {
  49170. if (seriesModel.get('layout') === 'circular') {
  49171. circularLayout(seriesModel, 'symbolSize');
  49172. }
  49173. });
  49174. }
  49175. var scaleAndAdd$1 = scaleAndAdd; // function adjacentNode(n, e) {
  49176. // return e.n1 === n ? e.n2 : e.n1;
  49177. // }
  49178. function forceLayout(inNodes, inEdges, opts) {
  49179. var nodes = inNodes;
  49180. var edges = inEdges;
  49181. var rect = opts.rect;
  49182. var width = rect.width;
  49183. var height = rect.height;
  49184. var center = [rect.x + width / 2, rect.y + height / 2]; // let scale = opts.scale || 1;
  49185. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (let i = 0; i < edges.length; i++) {
  49186. // let e = edges[i];
  49187. // let n1 = e.n1;
  49188. // let n2 = e.n2;
  49189. // n1.edges = n1.edges || [];
  49190. // n2.edges = n2.edges || [];
  49191. // n1.edges.push(e);
  49192. // n2.edges.push(e);
  49193. // }
  49194. // Init position
  49195. for (var i = 0; i < nodes.length; i++) {
  49196. var n = nodes[i];
  49197. if (!n.p) {
  49198. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  49199. }
  49200. n.pp = clone$1(n.p);
  49201. n.edges = null;
  49202. } // Formula in 'Graph Drawing by Force-directed Placement'
  49203. // let k = scale * Math.sqrt(width * height / nodes.length);
  49204. // let k2 = k * k;
  49205. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  49206. var friction = initialFriction;
  49207. var beforeStepCallback;
  49208. var afterStepCallback;
  49209. return {
  49210. warmUp: function () {
  49211. friction = initialFriction * 0.8;
  49212. },
  49213. setFixed: function (idx) {
  49214. nodes[idx].fixed = true;
  49215. },
  49216. setUnfixed: function (idx) {
  49217. nodes[idx].fixed = false;
  49218. },
  49219. /**
  49220. * Before step hook
  49221. */
  49222. beforeStep: function (cb) {
  49223. beforeStepCallback = cb;
  49224. },
  49225. /**
  49226. * After step hook
  49227. */
  49228. afterStep: function (cb) {
  49229. afterStepCallback = cb;
  49230. },
  49231. /**
  49232. * Some formulas were originally copied from "d3.js"
  49233. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  49234. * with some modifications made for this project.
  49235. * See the license statement at the head of this file.
  49236. */
  49237. step: function (cb) {
  49238. beforeStepCallback && beforeStepCallback(nodes, edges);
  49239. var v12 = [];
  49240. var nLen = nodes.length;
  49241. for (var i = 0; i < edges.length; i++) {
  49242. var e = edges[i];
  49243. if (e.ignoreForceLayout) {
  49244. continue;
  49245. }
  49246. var n1 = e.n1;
  49247. var n2 = e.n2;
  49248. sub(v12, n2.p, n1.p);
  49249. var d = len(v12) - e.d;
  49250. var w = n2.w / (n1.w + n2.w);
  49251. if (isNaN(w)) {
  49252. w = 0;
  49253. }
  49254. normalize(v12, v12);
  49255. !n1.fixed && scaleAndAdd$1(n1.p, n1.p, v12, w * d * friction);
  49256. !n2.fixed && scaleAndAdd$1(n2.p, n2.p, v12, -(1 - w) * d * friction);
  49257. } // Gravity
  49258. for (var i = 0; i < nLen; i++) {
  49259. var n = nodes[i];
  49260. if (!n.fixed) {
  49261. sub(v12, center, n.p); // let d = vec2.len(v12);
  49262. // vec2.scale(v12, v12, 1 / d);
  49263. // let gravityFactor = gravity;
  49264. scaleAndAdd$1(n.p, n.p, v12, gravity * friction);
  49265. }
  49266. } // Repulsive
  49267. // PENDING
  49268. for (var i = 0; i < nLen; i++) {
  49269. var n1 = nodes[i];
  49270. for (var j = i + 1; j < nLen; j++) {
  49271. var n2 = nodes[j];
  49272. sub(v12, n2.p, n1.p);
  49273. var d = len(v12);
  49274. if (d === 0) {
  49275. // Random repulse
  49276. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  49277. d = 1;
  49278. }
  49279. var repFact = (n1.rep + n2.rep) / d / d;
  49280. !n1.fixed && scaleAndAdd$1(n1.pp, n1.pp, v12, repFact);
  49281. !n2.fixed && scaleAndAdd$1(n2.pp, n2.pp, v12, -repFact);
  49282. }
  49283. }
  49284. var v = [];
  49285. for (var i = 0; i < nLen; i++) {
  49286. var n = nodes[i];
  49287. if (!n.fixed) {
  49288. sub(v, n.p, n.pp);
  49289. scaleAndAdd$1(n.p, n.p, v, friction);
  49290. copy(n.pp, n.p);
  49291. }
  49292. }
  49293. friction = friction * 0.992;
  49294. var finished = friction < 0.01;
  49295. afterStepCallback && afterStepCallback(nodes, edges, finished);
  49296. cb && cb(finished);
  49297. }
  49298. };
  49299. }
  49300. function graphForceLayout(ecModel) {
  49301. ecModel.eachSeriesByType('graph', function (graphSeries) {
  49302. var coordSys = graphSeries.coordinateSystem;
  49303. if (coordSys && coordSys.type !== 'view') {
  49304. return;
  49305. }
  49306. if (graphSeries.get('layout') === 'force') {
  49307. var preservedPoints_1 = graphSeries.preservedPoints || {};
  49308. var graph_1 = graphSeries.getGraph();
  49309. var nodeData_1 = graph_1.data;
  49310. var edgeData = graph_1.edgeData;
  49311. var forceModel = graphSeries.getModel('force');
  49312. var initLayout = forceModel.get('initLayout');
  49313. if (graphSeries.preservedPoints) {
  49314. nodeData_1.each(function (idx) {
  49315. var id = nodeData_1.getId(idx);
  49316. nodeData_1.setItemLayout(idx, preservedPoints_1[id] || [NaN, NaN]);
  49317. });
  49318. } else if (!initLayout || initLayout === 'none') {
  49319. simpleLayout(graphSeries);
  49320. } else if (initLayout === 'circular') {
  49321. circularLayout(graphSeries, 'value');
  49322. }
  49323. var nodeDataExtent_1 = nodeData_1.getDataExtent('value');
  49324. var edgeDataExtent_1 = edgeData.getDataExtent('value'); // let edgeDataExtent = edgeData.getDataExtent('value');
  49325. var repulsion = forceModel.get('repulsion');
  49326. var edgeLength = forceModel.get('edgeLength');
  49327. var repulsionArr_1 = isArray(repulsion) ? repulsion : [repulsion, repulsion];
  49328. var edgeLengthArr_1 = isArray(edgeLength) ? edgeLength : [edgeLength, edgeLength]; // Larger value has smaller length
  49329. edgeLengthArr_1 = [edgeLengthArr_1[1], edgeLengthArr_1[0]];
  49330. var nodes_1 = nodeData_1.mapArray('value', function (value, idx) {
  49331. var point = nodeData_1.getItemLayout(idx);
  49332. var rep = linearMap(value, nodeDataExtent_1, repulsionArr_1);
  49333. if (isNaN(rep)) {
  49334. rep = (repulsionArr_1[0] + repulsionArr_1[1]) / 2;
  49335. }
  49336. return {
  49337. w: rep,
  49338. rep: rep,
  49339. fixed: nodeData_1.getItemModel(idx).get('fixed'),
  49340. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  49341. };
  49342. });
  49343. var edges = edgeData.mapArray('value', function (value, idx) {
  49344. var edge = graph_1.getEdgeByIndex(idx);
  49345. var d = linearMap(value, edgeDataExtent_1, edgeLengthArr_1);
  49346. if (isNaN(d)) {
  49347. d = (edgeLengthArr_1[0] + edgeLengthArr_1[1]) / 2;
  49348. }
  49349. var edgeModel = edge.getModel();
  49350. var curveness = retrieve3(edge.getModel().get(['lineStyle', 'curveness']), -getCurvenessForEdge(edge, graphSeries, idx, true), 0);
  49351. return {
  49352. n1: nodes_1[edge.node1.dataIndex],
  49353. n2: nodes_1[edge.node2.dataIndex],
  49354. d: d,
  49355. curveness: curveness,
  49356. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  49357. };
  49358. }); // let coordSys = graphSeries.coordinateSystem;
  49359. var rect = coordSys.getBoundingRect();
  49360. var forceInstance = forceLayout(nodes_1, edges, {
  49361. rect: rect,
  49362. gravity: forceModel.get('gravity'),
  49363. friction: forceModel.get('friction')
  49364. });
  49365. forceInstance.beforeStep(function (nodes, edges) {
  49366. for (var i = 0, l = nodes.length; i < l; i++) {
  49367. if (nodes[i].fixed) {
  49368. // Write back to layout instance
  49369. copy(nodes[i].p, graph_1.getNodeByIndex(i).getLayout());
  49370. }
  49371. }
  49372. });
  49373. forceInstance.afterStep(function (nodes, edges, stopped) {
  49374. for (var i = 0, l = nodes.length; i < l; i++) {
  49375. if (!nodes[i].fixed) {
  49376. graph_1.getNodeByIndex(i).setLayout(nodes[i].p);
  49377. }
  49378. preservedPoints_1[nodeData_1.getId(i)] = nodes[i].p;
  49379. }
  49380. for (var i = 0, l = edges.length; i < l; i++) {
  49381. var e = edges[i];
  49382. var edge = graph_1.getEdgeByIndex(i);
  49383. var p1 = e.n1.p;
  49384. var p2 = e.n2.p;
  49385. var points = edge.getLayout();
  49386. points = points ? points.slice() : [];
  49387. points[0] = points[0] || [];
  49388. points[1] = points[1] || [];
  49389. copy(points[0], p1);
  49390. copy(points[1], p2);
  49391. if (+e.curveness) {
  49392. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  49393. }
  49394. edge.setLayout(points);
  49395. }
  49396. });
  49397. graphSeries.forceLayout = forceInstance;
  49398. graphSeries.preservedPoints = preservedPoints_1; // Step to get the layout
  49399. forceInstance.step();
  49400. } else {
  49401. // Remove prev injected forceLayout instance
  49402. graphSeries.forceLayout = null;
  49403. }
  49404. });
  49405. }
  49406. function getViewRect$2(seriesModel, api, aspect) {
  49407. var option = extend(seriesModel.getBoxLayoutParams(), {
  49408. aspect: aspect
  49409. });
  49410. return getLayoutRect(option, {
  49411. width: api.getWidth(),
  49412. height: api.getHeight()
  49413. });
  49414. }
  49415. function createViewCoordSys(ecModel, api) {
  49416. var viewList = [];
  49417. ecModel.eachSeriesByType('graph', function (seriesModel) {
  49418. var coordSysType = seriesModel.get('coordinateSystem');
  49419. if (!coordSysType || coordSysType === 'view') {
  49420. var data_1 = seriesModel.getData();
  49421. var positions = data_1.mapArray(function (idx) {
  49422. var itemModel = data_1.getItemModel(idx);
  49423. return [+itemModel.get('x'), +itemModel.get('y')];
  49424. });
  49425. var min = [];
  49426. var max = [];
  49427. fromPoints(positions, min, max); // If width or height is 0
  49428. if (max[0] - min[0] === 0) {
  49429. max[0] += 1;
  49430. min[0] -= 1;
  49431. }
  49432. if (max[1] - min[1] === 0) {
  49433. max[1] += 1;
  49434. min[1] -= 1;
  49435. }
  49436. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  49437. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  49438. if (isNaN(aspect)) {
  49439. min = [viewRect.x, viewRect.y];
  49440. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  49441. }
  49442. var bbWidth = max[0] - min[0];
  49443. var bbHeight = max[1] - min[1];
  49444. var viewWidth = viewRect.width;
  49445. var viewHeight = viewRect.height;
  49446. var viewCoordSys = seriesModel.coordinateSystem = new View();
  49447. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  49448. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  49449. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  49450. viewCoordSys.setCenter(seriesModel.get('center'));
  49451. viewCoordSys.setZoom(seriesModel.get('zoom'));
  49452. viewList.push(viewCoordSys);
  49453. }
  49454. });
  49455. return viewList;
  49456. }
  49457. var straightLineProto = Line.prototype;
  49458. var bezierCurveProto = BezierCurve.prototype;
  49459. var StraightLineShape =
  49460. /** @class */
  49461. function () {
  49462. function StraightLineShape() {
  49463. // Start point
  49464. this.x1 = 0;
  49465. this.y1 = 0; // End point
  49466. this.x2 = 0;
  49467. this.y2 = 0;
  49468. this.percent = 1;
  49469. }
  49470. return StraightLineShape;
  49471. }();
  49472. var CurveShape =
  49473. /** @class */
  49474. function (_super) {
  49475. __extends(CurveShape, _super);
  49476. function CurveShape() {
  49477. return _super !== null && _super.apply(this, arguments) || this;
  49478. }
  49479. return CurveShape;
  49480. }(StraightLineShape);
  49481. function isStraightLine(shape) {
  49482. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  49483. }
  49484. var ECLinePath =
  49485. /** @class */
  49486. function (_super) {
  49487. __extends(ECLinePath, _super);
  49488. function ECLinePath(opts) {
  49489. var _this = _super.call(this, opts) || this;
  49490. _this.type = 'ec-line';
  49491. return _this;
  49492. }
  49493. ECLinePath.prototype.getDefaultStyle = function () {
  49494. return {
  49495. stroke: '#000',
  49496. fill: null
  49497. };
  49498. };
  49499. ECLinePath.prototype.getDefaultShape = function () {
  49500. return new StraightLineShape();
  49501. };
  49502. ECLinePath.prototype.buildPath = function (ctx, shape) {
  49503. if (isStraightLine(shape)) {
  49504. straightLineProto.buildPath.call(this, ctx, shape);
  49505. } else {
  49506. bezierCurveProto.buildPath.call(this, ctx, shape);
  49507. }
  49508. };
  49509. ECLinePath.prototype.pointAt = function (t) {
  49510. if (isStraightLine(this.shape)) {
  49511. return straightLineProto.pointAt.call(this, t);
  49512. } else {
  49513. return bezierCurveProto.pointAt.call(this, t);
  49514. }
  49515. };
  49516. ECLinePath.prototype.tangentAt = function (t) {
  49517. var shape = this.shape;
  49518. var p = isStraightLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : bezierCurveProto.tangentAt.call(this, t);
  49519. return normalize(p, p);
  49520. };
  49521. return ECLinePath;
  49522. }(Path);
  49523. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  49524. function makeSymbolTypeKey(symbolCategory) {
  49525. return '_' + symbolCategory + 'Type';
  49526. }
  49527. /**
  49528. * @inner
  49529. */
  49530. function createSymbol$1(name, lineData, idx) {
  49531. var symbolType = lineData.getItemVisual(idx, name);
  49532. if (!symbolType || symbolType === 'none') {
  49533. return;
  49534. }
  49535. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  49536. var symbolRotate = lineData.getItemVisual(idx, name + 'Rotate');
  49537. var symbolSizeArr = isArray(symbolSize) ? symbolSize : [symbolSize, symbolSize];
  49538. var symbolPath = createSymbol(symbolType, -symbolSizeArr[0] / 2, -symbolSizeArr[1] / 2, symbolSizeArr[0], symbolSizeArr[1]);
  49539. symbolPath.__specifiedRotation = symbolRotate == null || isNaN(symbolRotate) ? void 0 : +symbolRotate * Math.PI / 180 || 0;
  49540. symbolPath.name = name;
  49541. return symbolPath;
  49542. }
  49543. function createLine(points) {
  49544. var line = new ECLinePath({
  49545. name: 'line',
  49546. subPixelOptimize: true
  49547. });
  49548. setLinePoints(line.shape, points);
  49549. return line;
  49550. }
  49551. function setLinePoints(targetShape, points) {
  49552. targetShape.x1 = points[0][0];
  49553. targetShape.y1 = points[0][1];
  49554. targetShape.x2 = points[1][0];
  49555. targetShape.y2 = points[1][1];
  49556. targetShape.percent = 1;
  49557. var cp1 = points[2];
  49558. if (cp1) {
  49559. targetShape.cpx1 = cp1[0];
  49560. targetShape.cpy1 = cp1[1];
  49561. } else {
  49562. targetShape.cpx1 = NaN;
  49563. targetShape.cpy1 = NaN;
  49564. }
  49565. }
  49566. var Line$1 =
  49567. /** @class */
  49568. function (_super) {
  49569. __extends(Line, _super);
  49570. function Line(lineData, idx, seriesScope) {
  49571. var _this = _super.call(this) || this;
  49572. _this._createLine(lineData, idx, seriesScope);
  49573. return _this;
  49574. }
  49575. Line.prototype._createLine = function (lineData, idx, seriesScope) {
  49576. var seriesModel = lineData.hostModel;
  49577. var linePoints = lineData.getItemLayout(idx);
  49578. var line = createLine(linePoints);
  49579. line.shape.percent = 0;
  49580. initProps(line, {
  49581. shape: {
  49582. percent: 1
  49583. }
  49584. }, seriesModel, idx);
  49585. this.add(line);
  49586. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  49587. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  49588. // it will be updated after line#update.
  49589. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  49590. this.add(symbol);
  49591. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  49592. }, this);
  49593. this._updateCommonStl(lineData, idx, seriesScope);
  49594. }; // TODO More strict on the List type in parameters?
  49595. Line.prototype.updateData = function (lineData, idx, seriesScope) {
  49596. var seriesModel = lineData.hostModel;
  49597. var line = this.childOfName('line');
  49598. var linePoints = lineData.getItemLayout(idx);
  49599. var target = {
  49600. shape: {}
  49601. };
  49602. setLinePoints(target.shape, linePoints);
  49603. updateProps(line, target, seriesModel, idx);
  49604. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  49605. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  49606. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  49607. if (this[key] !== symbolType) {
  49608. this.remove(this.childOfName(symbolCategory));
  49609. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  49610. this.add(symbol);
  49611. }
  49612. this[key] = symbolType;
  49613. }, this);
  49614. this._updateCommonStl(lineData, idx, seriesScope);
  49615. };
  49616. Line.prototype.getLinePath = function () {
  49617. return this.childAt(0);
  49618. };
  49619. Line.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  49620. var seriesModel = lineData.hostModel;
  49621. var line = this.childOfName('line');
  49622. var emphasisLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  49623. var blurLineStyle = seriesScope && seriesScope.blurLineStyle;
  49624. var selectLineStyle = seriesScope && seriesScope.selectLineStyle;
  49625. var labelStatesModels = seriesScope && seriesScope.labelStatesModels; // Optimization for large dataset
  49626. if (!seriesScope || lineData.hasItemOption) {
  49627. var itemModel = lineData.getItemModel(idx);
  49628. emphasisLineStyle = itemModel.getModel(['emphasis', 'lineStyle']).getLineStyle();
  49629. blurLineStyle = itemModel.getModel(['blur', 'lineStyle']).getLineStyle();
  49630. selectLineStyle = itemModel.getModel(['select', 'lineStyle']).getLineStyle();
  49631. labelStatesModels = getLabelStatesModels(itemModel);
  49632. }
  49633. var lineStyle = lineData.getItemVisual(idx, 'style');
  49634. var visualColor = lineStyle.stroke;
  49635. line.useStyle(lineStyle);
  49636. line.style.fill = null;
  49637. line.style.strokeNoScale = true;
  49638. line.ensureState('emphasis').style = emphasisLineStyle;
  49639. line.ensureState('blur').style = blurLineStyle;
  49640. line.ensureState('select').style = selectLineStyle; // Update symbol
  49641. each(SYMBOL_CATEGORIES, function (symbolCategory) {
  49642. var symbol = this.childOfName(symbolCategory);
  49643. if (symbol) {
  49644. // Share opacity and color with line.
  49645. symbol.setColor(visualColor);
  49646. symbol.style.opacity = lineStyle.opacity;
  49647. for (var i = 0; i < SPECIAL_STATES.length; i++) {
  49648. var stateName = SPECIAL_STATES[i];
  49649. var lineState = line.getState(stateName);
  49650. if (lineState) {
  49651. var lineStateStyle = lineState.style || {};
  49652. var state = symbol.ensureState(stateName);
  49653. var stateStyle = state.style || (state.style = {});
  49654. if (lineStateStyle.stroke != null) {
  49655. stateStyle[symbol.__isEmptyBrush ? 'stroke' : 'fill'] = lineStateStyle.stroke;
  49656. }
  49657. if (lineStateStyle.opacity != null) {
  49658. stateStyle.opacity = lineStateStyle.opacity;
  49659. }
  49660. }
  49661. }
  49662. symbol.markRedraw();
  49663. }
  49664. }, this);
  49665. var rawVal = seriesModel.getRawValue(idx);
  49666. setLabelStyle(this, labelStatesModels, {
  49667. labelDataIndex: idx,
  49668. labelFetcher: {
  49669. getFormattedLabel: function (dataIndex, stateName) {
  49670. return seriesModel.getFormattedLabel(dataIndex, stateName, lineData.dataType);
  49671. }
  49672. },
  49673. inheritColor: visualColor || '#000',
  49674. defaultOpacity: lineStyle.opacity,
  49675. defaultText: (rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round(rawVal) : rawVal) + ''
  49676. });
  49677. var label = this.getTextContent(); // Always set `textStyle` even if `normalStyle.text` is null, because default
  49678. // values have to be set on `normalStyle`.
  49679. if (label) {
  49680. var labelNormalModel = labelStatesModels.normal;
  49681. label.__align = label.style.align;
  49682. label.__verticalAlign = label.style.verticalAlign; // 'start', 'middle', 'end'
  49683. label.__position = labelNormalModel.get('position') || 'middle';
  49684. var distance = labelNormalModel.get('distance');
  49685. if (!isArray(distance)) {
  49686. distance = [distance, distance];
  49687. }
  49688. label.__labelDistance = distance;
  49689. }
  49690. this.setTextConfig({
  49691. position: null,
  49692. local: true,
  49693. inside: false // Can't be inside for stroke element.
  49694. });
  49695. enableHoverEmphasis(this);
  49696. };
  49697. Line.prototype.highlight = function () {
  49698. enterEmphasis(this);
  49699. };
  49700. Line.prototype.downplay = function () {
  49701. leaveEmphasis(this);
  49702. };
  49703. Line.prototype.updateLayout = function (lineData, idx) {
  49704. this.setLinePoints(lineData.getItemLayout(idx));
  49705. };
  49706. Line.prototype.setLinePoints = function (points) {
  49707. var linePath = this.childOfName('line');
  49708. setLinePoints(linePath.shape, points);
  49709. linePath.dirty();
  49710. };
  49711. Line.prototype.beforeUpdate = function () {
  49712. var lineGroup = this;
  49713. var symbolFrom = lineGroup.childOfName('fromSymbol');
  49714. var symbolTo = lineGroup.childOfName('toSymbol');
  49715. var label = lineGroup.getTextContent(); // Quick reject
  49716. if (!symbolFrom && !symbolTo && (!label || label.ignore)) {
  49717. return;
  49718. }
  49719. var invScale = 1;
  49720. var parentNode = this.parent;
  49721. while (parentNode) {
  49722. if (parentNode.scaleX) {
  49723. invScale /= parentNode.scaleX;
  49724. }
  49725. parentNode = parentNode.parent;
  49726. }
  49727. var line = lineGroup.childOfName('line'); // If line not changed
  49728. // FIXME Parent scale changed
  49729. if (!this.__dirty && !line.__dirty) {
  49730. return;
  49731. }
  49732. var percent = line.shape.percent;
  49733. var fromPos = line.pointAt(0);
  49734. var toPos = line.pointAt(percent);
  49735. var d = sub([], toPos, fromPos);
  49736. normalize(d, d);
  49737. function setSymbolRotation(symbol, percent) {
  49738. // Fix #12388
  49739. // when symbol is set to be 'arrow' in markLine,
  49740. // symbolRotate value will be ignored, and compulsively use tangent angle.
  49741. // rotate by default if symbol rotation is not specified
  49742. var specifiedRotation = symbol.__specifiedRotation;
  49743. if (specifiedRotation == null) {
  49744. var tangent = line.tangentAt(percent);
  49745. symbol.attr('rotation', (percent === 1 ? -1 : 1) * Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  49746. } else {
  49747. symbol.attr('rotation', specifiedRotation);
  49748. }
  49749. }
  49750. if (symbolFrom) {
  49751. symbolFrom.setPosition(fromPos);
  49752. setSymbolRotation(symbolFrom, 0);
  49753. symbolFrom.scaleX = symbolFrom.scaleY = invScale * percent;
  49754. symbolFrom.markRedraw();
  49755. }
  49756. if (symbolTo) {
  49757. symbolTo.setPosition(toPos);
  49758. setSymbolRotation(symbolTo, 1);
  49759. symbolTo.scaleX = symbolTo.scaleY = invScale * percent;
  49760. symbolTo.markRedraw();
  49761. }
  49762. if (label && !label.ignore) {
  49763. label.x = label.y = 0;
  49764. label.originX = label.originY = 0;
  49765. var textAlign = void 0;
  49766. var textVerticalAlign = void 0;
  49767. var distance = label.__labelDistance;
  49768. var distanceX = distance[0] * invScale;
  49769. var distanceY = distance[1] * invScale;
  49770. var halfPercent = percent / 2;
  49771. var tangent = line.tangentAt(halfPercent);
  49772. var n = [tangent[1], -tangent[0]];
  49773. var cp = line.pointAt(halfPercent);
  49774. if (n[1] > 0) {
  49775. n[0] = -n[0];
  49776. n[1] = -n[1];
  49777. }
  49778. var dir = tangent[0] < 0 ? -1 : 1;
  49779. if (label.__position !== 'start' && label.__position !== 'end') {
  49780. var rotation = -Math.atan2(tangent[1], tangent[0]);
  49781. if (toPos[0] < fromPos[0]) {
  49782. rotation = Math.PI + rotation;
  49783. }
  49784. label.rotation = rotation;
  49785. }
  49786. var dy = void 0;
  49787. switch (label.__position) {
  49788. case 'insideStartTop':
  49789. case 'insideMiddleTop':
  49790. case 'insideEndTop':
  49791. case 'middle':
  49792. dy = -distanceY;
  49793. textVerticalAlign = 'bottom';
  49794. break;
  49795. case 'insideStartBottom':
  49796. case 'insideMiddleBottom':
  49797. case 'insideEndBottom':
  49798. dy = distanceY;
  49799. textVerticalAlign = 'top';
  49800. break;
  49801. default:
  49802. dy = 0;
  49803. textVerticalAlign = 'middle';
  49804. }
  49805. switch (label.__position) {
  49806. case 'end':
  49807. label.x = d[0] * distanceX + toPos[0];
  49808. label.y = d[1] * distanceY + toPos[1];
  49809. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  49810. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  49811. break;
  49812. case 'start':
  49813. label.x = -d[0] * distanceX + fromPos[0];
  49814. label.y = -d[1] * distanceY + fromPos[1];
  49815. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  49816. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  49817. break;
  49818. case 'insideStartTop':
  49819. case 'insideStart':
  49820. case 'insideStartBottom':
  49821. label.x = distanceX * dir + fromPos[0];
  49822. label.y = fromPos[1] + dy;
  49823. textAlign = tangent[0] < 0 ? 'right' : 'left';
  49824. label.originX = -distanceX * dir;
  49825. label.originY = -dy;
  49826. break;
  49827. case 'insideMiddleTop':
  49828. case 'insideMiddle':
  49829. case 'insideMiddleBottom':
  49830. case 'middle':
  49831. label.x = cp[0];
  49832. label.y = cp[1] + dy;
  49833. textAlign = 'center';
  49834. label.originY = -dy;
  49835. break;
  49836. case 'insideEndTop':
  49837. case 'insideEnd':
  49838. case 'insideEndBottom':
  49839. label.x = -distanceX * dir + toPos[0];
  49840. label.y = toPos[1] + dy;
  49841. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  49842. label.originX = distanceX * dir;
  49843. label.originY = -dy;
  49844. break;
  49845. }
  49846. label.scaleX = label.scaleY = invScale;
  49847. label.setStyle({
  49848. // Use the user specified text align and baseline first
  49849. verticalAlign: label.__verticalAlign || textVerticalAlign,
  49850. align: label.__align || textAlign
  49851. });
  49852. }
  49853. };
  49854. return Line;
  49855. }(Group);
  49856. var LineDraw =
  49857. /** @class */
  49858. function () {
  49859. function LineDraw(LineCtor) {
  49860. this.group = new Group();
  49861. this._LineCtor = LineCtor || Line$1;
  49862. }
  49863. LineDraw.prototype.isPersistent = function () {
  49864. return true;
  49865. };
  49866. LineDraw.prototype.updateData = function (lineData) {
  49867. var _this = this;
  49868. var lineDraw = this;
  49869. var group = lineDraw.group;
  49870. var oldLineData = lineDraw._lineData;
  49871. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  49872. // stream mode to normal mode, where previous elements should be removed.
  49873. if (!oldLineData) {
  49874. group.removeAll();
  49875. }
  49876. var seriesScope = makeSeriesScope$1(lineData);
  49877. lineData.diff(oldLineData).add(function (idx) {
  49878. _this._doAdd(lineData, idx, seriesScope);
  49879. }).update(function (newIdx, oldIdx) {
  49880. _this._doUpdate(oldLineData, lineData, oldIdx, newIdx, seriesScope);
  49881. }).remove(function (idx) {
  49882. group.remove(oldLineData.getItemGraphicEl(idx));
  49883. }).execute();
  49884. };
  49885. LineDraw.prototype.updateLayout = function () {
  49886. var lineData = this._lineData; // Do not support update layout in incremental mode.
  49887. if (!lineData) {
  49888. return;
  49889. }
  49890. lineData.eachItemGraphicEl(function (el, idx) {
  49891. el.updateLayout(lineData, idx);
  49892. }, this);
  49893. };
  49894. LineDraw.prototype.incrementalPrepareUpdate = function (lineData) {
  49895. this._seriesScope = makeSeriesScope$1(lineData);
  49896. this._lineData = null;
  49897. this.group.removeAll();
  49898. };
  49899. LineDraw.prototype.incrementalUpdate = function (taskParams, lineData) {
  49900. function updateIncrementalAndHover(el) {
  49901. if (!el.isGroup && !isEffectObject(el)) {
  49902. el.incremental = true;
  49903. el.ensureState('emphasis').hoverLayer = true;
  49904. }
  49905. }
  49906. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  49907. var itemLayout = lineData.getItemLayout(idx);
  49908. if (lineNeedsDraw(itemLayout)) {
  49909. var el = new this._LineCtor(lineData, idx, this._seriesScope);
  49910. el.traverse(updateIncrementalAndHover);
  49911. this.group.add(el);
  49912. lineData.setItemGraphicEl(idx, el);
  49913. }
  49914. }
  49915. };
  49916. LineDraw.prototype.remove = function () {
  49917. this.group.removeAll();
  49918. };
  49919. LineDraw.prototype._doAdd = function (lineData, idx, seriesScope) {
  49920. var itemLayout = lineData.getItemLayout(idx);
  49921. if (!lineNeedsDraw(itemLayout)) {
  49922. return;
  49923. }
  49924. var el = new this._LineCtor(lineData, idx, seriesScope);
  49925. lineData.setItemGraphicEl(idx, el);
  49926. this.group.add(el);
  49927. };
  49928. LineDraw.prototype._doUpdate = function (oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  49929. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  49930. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  49931. this.group.remove(itemEl);
  49932. return;
  49933. }
  49934. if (!itemEl) {
  49935. itemEl = new this._LineCtor(newLineData, newIdx, seriesScope);
  49936. } else {
  49937. itemEl.updateData(newLineData, newIdx, seriesScope);
  49938. }
  49939. newLineData.setItemGraphicEl(newIdx, itemEl);
  49940. this.group.add(itemEl);
  49941. };
  49942. return LineDraw;
  49943. }();
  49944. function isEffectObject(el) {
  49945. return el.animators && el.animators.length > 0;
  49946. }
  49947. function makeSeriesScope$1(lineData) {
  49948. var hostModel = lineData.hostModel;
  49949. return {
  49950. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  49951. emphasisLineStyle: hostModel.getModel(['emphasis', 'lineStyle']).getLineStyle(),
  49952. blurLineStyle: hostModel.getModel(['blur', 'lineStyle']).getLineStyle(),
  49953. selectLineStyle: hostModel.getModel(['select', 'lineStyle']).getLineStyle(),
  49954. labelStatesModels: getLabelStatesModels(hostModel)
  49955. };
  49956. }
  49957. function isPointNaN(pt) {
  49958. return isNaN(pt[0]) || isNaN(pt[1]);
  49959. }
  49960. function lineNeedsDraw(pts) {
  49961. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  49962. }
  49963. var v1 = [];
  49964. var v2 = [];
  49965. var v3 = [];
  49966. var quadraticAt$1 = quadraticAt;
  49967. var v2DistSquare = distSquare;
  49968. var mathAbs$2 = Math.abs;
  49969. function intersectCurveCircle(curvePoints, center, radius) {
  49970. var p0 = curvePoints[0];
  49971. var p1 = curvePoints[1];
  49972. var p2 = curvePoints[2];
  49973. var d = Infinity;
  49974. var t;
  49975. var radiusSquare = radius * radius;
  49976. var interval = 0.1;
  49977. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  49978. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  49979. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  49980. var diff = mathAbs$2(v2DistSquare(v1, center) - radiusSquare);
  49981. if (diff < d) {
  49982. d = diff;
  49983. t = _t;
  49984. }
  49985. } // Assume the segment is monotone,Find root through Bisection method
  49986. // At most 32 iteration
  49987. for (var i = 0; i < 32; i++) {
  49988. // let prev = t - interval;
  49989. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  49990. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  49991. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  49992. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  49993. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  49994. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  49995. var diff = v2DistSquare(v2, center) - radiusSquare;
  49996. if (mathAbs$2(diff) < 1e-2) {
  49997. break;
  49998. } // let prevDiff = v2DistSquare(v1, center) - radiusSquare;
  49999. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  50000. interval /= 2;
  50001. if (diff < 0) {
  50002. if (nextDiff >= 0) {
  50003. t = t + interval;
  50004. } else {
  50005. t = t - interval;
  50006. }
  50007. } else {
  50008. if (nextDiff >= 0) {
  50009. t = t - interval;
  50010. } else {
  50011. t = t + interval;
  50012. }
  50013. }
  50014. }
  50015. return t;
  50016. } // Adjust edge to avoid
  50017. function adjustEdge(graph, scale) {
  50018. var tmp0 = [];
  50019. var quadraticSubdivide$1 = quadraticSubdivide;
  50020. var pts = [[], [], []];
  50021. var pts2 = [[], []];
  50022. var v = [];
  50023. scale /= 2;
  50024. graph.eachEdge(function (edge, idx) {
  50025. var linePoints = edge.getLayout();
  50026. var fromSymbol = edge.getVisual('fromSymbol');
  50027. var toSymbol = edge.getVisual('toSymbol');
  50028. if (!linePoints.__original) {
  50029. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  50030. if (linePoints[2]) {
  50031. linePoints.__original.push(clone$1(linePoints[2]));
  50032. }
  50033. }
  50034. var originalPoints = linePoints.__original; // Quadratic curve
  50035. if (linePoints[2] != null) {
  50036. copy(pts[0], originalPoints[0]);
  50037. copy(pts[1], originalPoints[2]);
  50038. copy(pts[2], originalPoints[1]);
  50039. if (fromSymbol && fromSymbol !== 'none') {
  50040. var symbolSize = getSymbolSize(edge.node1);
  50041. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale); // Subdivide and get the second
  50042. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  50043. pts[0][0] = tmp0[3];
  50044. pts[1][0] = tmp0[4];
  50045. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  50046. pts[0][1] = tmp0[3];
  50047. pts[1][1] = tmp0[4];
  50048. }
  50049. if (toSymbol && toSymbol !== 'none') {
  50050. var symbolSize = getSymbolSize(edge.node2);
  50051. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale); // Subdivide and get the first
  50052. quadraticSubdivide$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  50053. pts[1][0] = tmp0[1];
  50054. pts[2][0] = tmp0[2];
  50055. quadraticSubdivide$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  50056. pts[1][1] = tmp0[1];
  50057. pts[2][1] = tmp0[2];
  50058. } // Copy back to layout
  50059. copy(linePoints[0], pts[0]);
  50060. copy(linePoints[1], pts[2]);
  50061. copy(linePoints[2], pts[1]);
  50062. } // Line
  50063. else {
  50064. copy(pts2[0], originalPoints[0]);
  50065. copy(pts2[1], originalPoints[1]);
  50066. sub(v, pts2[1], pts2[0]);
  50067. normalize(v, v);
  50068. if (fromSymbol && fromSymbol !== 'none') {
  50069. var symbolSize = getSymbolSize(edge.node1);
  50070. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale);
  50071. }
  50072. if (toSymbol && toSymbol !== 'none') {
  50073. var symbolSize = getSymbolSize(edge.node2);
  50074. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale);
  50075. }
  50076. copy(linePoints[0], pts2[0]);
  50077. copy(linePoints[1], pts2[1]);
  50078. }
  50079. });
  50080. }
  50081. function isViewCoordSys(coordSys) {
  50082. return coordSys.type === 'view';
  50083. }
  50084. var GraphView =
  50085. /** @class */
  50086. function (_super) {
  50087. __extends(GraphView, _super);
  50088. function GraphView() {
  50089. var _this = _super !== null && _super.apply(this, arguments) || this;
  50090. _this.type = GraphView.type;
  50091. return _this;
  50092. }
  50093. GraphView.prototype.init = function (ecModel, api) {
  50094. var symbolDraw = new SymbolDraw();
  50095. var lineDraw = new LineDraw();
  50096. var group = this.group;
  50097. this._controller = new RoamController(api.getZr());
  50098. this._controllerHost = {
  50099. target: group
  50100. };
  50101. group.add(symbolDraw.group);
  50102. group.add(lineDraw.group);
  50103. this._symbolDraw = symbolDraw;
  50104. this._lineDraw = lineDraw;
  50105. this._firstRender = true;
  50106. };
  50107. GraphView.prototype.render = function (seriesModel, ecModel, api) {
  50108. var _this = this;
  50109. var coordSys = seriesModel.coordinateSystem;
  50110. this._model = seriesModel;
  50111. var symbolDraw = this._symbolDraw;
  50112. var lineDraw = this._lineDraw;
  50113. var group = this.group;
  50114. if (isViewCoordSys(coordSys)) {
  50115. var groupNewProp = {
  50116. x: coordSys.x,
  50117. y: coordSys.y,
  50118. scaleX: coordSys.scaleX,
  50119. scaleY: coordSys.scaleY
  50120. };
  50121. if (this._firstRender) {
  50122. group.attr(groupNewProp);
  50123. } else {
  50124. updateProps(group, groupNewProp, seriesModel);
  50125. }
  50126. } // Fix edge contact point with node
  50127. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50128. var data = seriesModel.getData();
  50129. symbolDraw.updateData(data);
  50130. var edgeData = seriesModel.getEdgeData(); // TODO: TYPE
  50131. lineDraw.updateData(edgeData);
  50132. this._updateNodeAndLinkScale();
  50133. this._updateController(seriesModel, ecModel, api);
  50134. clearTimeout(this._layoutTimeout);
  50135. var forceLayout = seriesModel.forceLayout;
  50136. var layoutAnimation = seriesModel.get(['force', 'layoutAnimation']);
  50137. if (forceLayout) {
  50138. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  50139. }
  50140. data.graph.eachNode(function (node) {
  50141. var idx = node.dataIndex;
  50142. var el = node.getGraphicEl();
  50143. var itemModel = node.getModel(); // Update draggable
  50144. el.off('drag').off('dragend');
  50145. var draggable = itemModel.get('draggable');
  50146. if (draggable) {
  50147. el.on('drag', function () {
  50148. if (forceLayout) {
  50149. forceLayout.warmUp();
  50150. !_this._layouting && _this._startForceLayoutIteration(forceLayout, layoutAnimation);
  50151. forceLayout.setFixed(idx); // Write position back to layout
  50152. data.setItemLayout(idx, [el.x, el.y]);
  50153. }
  50154. }).on('dragend', function () {
  50155. if (forceLayout) {
  50156. forceLayout.setUnfixed(idx);
  50157. }
  50158. });
  50159. }
  50160. el.setDraggable(draggable && !!forceLayout);
  50161. var focus = itemModel.get(['emphasis', 'focus']);
  50162. if (focus === 'adjacency') {
  50163. getECData(el).focus = node.getAdjacentDataIndices();
  50164. }
  50165. });
  50166. data.graph.eachEdge(function (edge) {
  50167. var el = edge.getGraphicEl();
  50168. var focus = edge.getModel().get(['emphasis', 'focus']);
  50169. if (focus === 'adjacency') {
  50170. getECData(el).focus = {
  50171. edge: [edge.dataIndex],
  50172. node: [edge.node1.dataIndex, edge.node2.dataIndex]
  50173. };
  50174. }
  50175. });
  50176. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']);
  50177. var cx = data.getLayout('cx');
  50178. var cy = data.getLayout('cy');
  50179. data.eachItemGraphicEl(function (el, idx) {
  50180. var itemModel = data.getItemModel(idx);
  50181. var labelRotate = itemModel.get(['label', 'rotate']) || 0;
  50182. var symbolPath = el.getSymbolPath();
  50183. if (circularRotateLabel) {
  50184. var pos = data.getItemLayout(idx);
  50185. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  50186. if (rad < 0) {
  50187. rad = Math.PI * 2 + rad;
  50188. }
  50189. var isLeft = pos[0] < cx;
  50190. if (isLeft) {
  50191. rad = rad - Math.PI;
  50192. }
  50193. var textPosition = isLeft ? 'left' : 'right';
  50194. symbolPath.setTextConfig({
  50195. rotation: -rad,
  50196. position: textPosition,
  50197. origin: 'center'
  50198. });
  50199. var emphasisState = symbolPath.ensureState('emphasis');
  50200. extend(emphasisState.textConfig || (emphasisState.textConfig = {}), {
  50201. position: textPosition
  50202. });
  50203. } else {
  50204. symbolPath.setTextConfig({
  50205. rotation: labelRotate *= Math.PI / 180
  50206. });
  50207. }
  50208. });
  50209. this._firstRender = false;
  50210. };
  50211. GraphView.prototype.dispose = function () {
  50212. this._controller && this._controller.dispose();
  50213. this._controllerHost = null;
  50214. };
  50215. GraphView.prototype._startForceLayoutIteration = function (forceLayout, layoutAnimation) {
  50216. var self = this;
  50217. (function step() {
  50218. forceLayout.step(function (stopped) {
  50219. self.updateLayout(self._model);
  50220. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  50221. });
  50222. })();
  50223. };
  50224. GraphView.prototype._updateController = function (seriesModel, ecModel, api) {
  50225. var _this = this;
  50226. var controller = this._controller;
  50227. var controllerHost = this._controllerHost;
  50228. var group = this.group;
  50229. controller.setPointerChecker(function (e, x, y) {
  50230. var rect = group.getBoundingRect();
  50231. rect.applyTransform(group.transform);
  50232. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  50233. });
  50234. if (!isViewCoordSys(seriesModel.coordinateSystem)) {
  50235. controller.disable();
  50236. return;
  50237. }
  50238. controller.enable(seriesModel.get('roam'));
  50239. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  50240. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  50241. controller.off('pan').off('zoom').on('pan', function (e) {
  50242. updateViewOnPan(controllerHost, e.dx, e.dy);
  50243. api.dispatchAction({
  50244. seriesId: seriesModel.id,
  50245. type: 'graphRoam',
  50246. dx: e.dx,
  50247. dy: e.dy
  50248. });
  50249. }).on('zoom', function (e) {
  50250. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  50251. api.dispatchAction({
  50252. seriesId: seriesModel.id,
  50253. type: 'graphRoam',
  50254. zoom: e.scale,
  50255. originX: e.originX,
  50256. originY: e.originY
  50257. });
  50258. _this._updateNodeAndLinkScale();
  50259. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50260. _this._lineDraw.updateLayout(); // Only update label layout on zoom
  50261. api.updateLabelLayout();
  50262. });
  50263. };
  50264. GraphView.prototype._updateNodeAndLinkScale = function () {
  50265. var seriesModel = this._model;
  50266. var data = seriesModel.getData();
  50267. var nodeScale = getNodeGlobalScale(seriesModel);
  50268. data.eachItemGraphicEl(function (el, idx) {
  50269. el.setSymbolScale(nodeScale);
  50270. });
  50271. };
  50272. GraphView.prototype.updateLayout = function (seriesModel) {
  50273. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  50274. this._symbolDraw.updateLayout();
  50275. this._lineDraw.updateLayout();
  50276. };
  50277. GraphView.prototype.remove = function (ecModel, api) {
  50278. this._symbolDraw && this._symbolDraw.remove();
  50279. this._lineDraw && this._lineDraw.remove();
  50280. };
  50281. GraphView.type = 'graph';
  50282. return GraphView;
  50283. }(ChartView);
  50284. function generateNodeKey(id) {
  50285. return '_EC_' + id;
  50286. }
  50287. var Graph =
  50288. /** @class */
  50289. function () {
  50290. function Graph(directed) {
  50291. this.type = 'graph';
  50292. this.nodes = [];
  50293. this.edges = [];
  50294. this._nodesMap = {};
  50295. /**
  50296. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  50297. * @private
  50298. */
  50299. this._edgesMap = {};
  50300. this._directed = directed || false;
  50301. }
  50302. /**
  50303. * If is directed graph
  50304. */
  50305. Graph.prototype.isDirected = function () {
  50306. return this._directed;
  50307. };
  50308. /**
  50309. * Add a new node
  50310. */
  50311. Graph.prototype.addNode = function (id, dataIndex) {
  50312. id = id == null ? '' + dataIndex : '' + id;
  50313. var nodesMap = this._nodesMap;
  50314. if (nodesMap[generateNodeKey(id)]) {
  50315. if ("development" !== 'production') {
  50316. console.error('Graph nodes have duplicate name or id');
  50317. }
  50318. return;
  50319. }
  50320. var node = new GraphNode(id, dataIndex);
  50321. node.hostGraph = this;
  50322. this.nodes.push(node);
  50323. nodesMap[generateNodeKey(id)] = node;
  50324. return node;
  50325. };
  50326. /**
  50327. * Get node by data index
  50328. */
  50329. Graph.prototype.getNodeByIndex = function (dataIndex) {
  50330. var rawIdx = this.data.getRawIndex(dataIndex);
  50331. return this.nodes[rawIdx];
  50332. };
  50333. /**
  50334. * Get node by id
  50335. */
  50336. Graph.prototype.getNodeById = function (id) {
  50337. return this._nodesMap[generateNodeKey(id)];
  50338. };
  50339. /**
  50340. * Add a new edge
  50341. */
  50342. Graph.prototype.addEdge = function (n1, n2, dataIndex) {
  50343. var nodesMap = this._nodesMap;
  50344. var edgesMap = this._edgesMap; // PNEDING
  50345. if (typeof n1 === 'number') {
  50346. n1 = this.nodes[n1];
  50347. }
  50348. if (typeof n2 === 'number') {
  50349. n2 = this.nodes[n2];
  50350. }
  50351. if (!(n1 instanceof GraphNode)) {
  50352. n1 = nodesMap[generateNodeKey(n1)];
  50353. }
  50354. if (!(n2 instanceof GraphNode)) {
  50355. n2 = nodesMap[generateNodeKey(n2)];
  50356. }
  50357. if (!n1 || !n2) {
  50358. return;
  50359. }
  50360. var key = n1.id + '-' + n2.id;
  50361. var edge = new GraphEdge(n1, n2, dataIndex);
  50362. edge.hostGraph = this;
  50363. if (this._directed) {
  50364. n1.outEdges.push(edge);
  50365. n2.inEdges.push(edge);
  50366. }
  50367. n1.edges.push(edge);
  50368. if (n1 !== n2) {
  50369. n2.edges.push(edge);
  50370. }
  50371. this.edges.push(edge);
  50372. edgesMap[key] = edge;
  50373. return edge;
  50374. };
  50375. /**
  50376. * Get edge by data index
  50377. */
  50378. Graph.prototype.getEdgeByIndex = function (dataIndex) {
  50379. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  50380. return this.edges[rawIdx];
  50381. };
  50382. /**
  50383. * Get edge by two linked nodes
  50384. */
  50385. Graph.prototype.getEdge = function (n1, n2) {
  50386. if (n1 instanceof GraphNode) {
  50387. n1 = n1.id;
  50388. }
  50389. if (n2 instanceof GraphNode) {
  50390. n2 = n2.id;
  50391. }
  50392. var edgesMap = this._edgesMap;
  50393. if (this._directed) {
  50394. return edgesMap[n1 + '-' + n2];
  50395. } else {
  50396. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  50397. }
  50398. };
  50399. /**
  50400. * Iterate all nodes
  50401. */
  50402. Graph.prototype.eachNode = function (cb, context) {
  50403. var nodes = this.nodes;
  50404. var len = nodes.length;
  50405. for (var i = 0; i < len; i++) {
  50406. if (nodes[i].dataIndex >= 0) {
  50407. cb.call(context, nodes[i], i);
  50408. }
  50409. }
  50410. };
  50411. /**
  50412. * Iterate all edges
  50413. */
  50414. Graph.prototype.eachEdge = function (cb, context) {
  50415. var edges = this.edges;
  50416. var len = edges.length;
  50417. for (var i = 0; i < len; i++) {
  50418. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  50419. cb.call(context, edges[i], i);
  50420. }
  50421. }
  50422. };
  50423. /**
  50424. * Breadth first traverse
  50425. * Return true to stop traversing
  50426. */
  50427. Graph.prototype.breadthFirstTraverse = function (cb, startNode, direction, context) {
  50428. if (!(startNode instanceof GraphNode)) {
  50429. startNode = this._nodesMap[generateNodeKey(startNode)];
  50430. }
  50431. if (!startNode) {
  50432. return;
  50433. }
  50434. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  50435. for (var i = 0; i < this.nodes.length; i++) {
  50436. this.nodes[i].__visited = false;
  50437. }
  50438. if (cb.call(context, startNode, null)) {
  50439. return;
  50440. }
  50441. var queue = [startNode];
  50442. while (queue.length) {
  50443. var currentNode = queue.shift();
  50444. var edges = currentNode[edgeType];
  50445. for (var i = 0; i < edges.length; i++) {
  50446. var e = edges[i];
  50447. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  50448. if (!otherNode.__visited) {
  50449. if (cb.call(context, otherNode, currentNode)) {
  50450. // Stop traversing
  50451. return;
  50452. }
  50453. queue.push(otherNode);
  50454. otherNode.__visited = true;
  50455. }
  50456. }
  50457. }
  50458. };
  50459. // depthFirstTraverse(
  50460. // cb, startNode, direction, context
  50461. // ) {
  50462. // };
  50463. // Filter update
  50464. Graph.prototype.update = function () {
  50465. var data = this.data;
  50466. var edgeData = this.edgeData;
  50467. var nodes = this.nodes;
  50468. var edges = this.edges;
  50469. for (var i = 0, len = nodes.length; i < len; i++) {
  50470. nodes[i].dataIndex = -1;
  50471. }
  50472. for (var i = 0, len = data.count(); i < len; i++) {
  50473. nodes[data.getRawIndex(i)].dataIndex = i;
  50474. }
  50475. edgeData.filterSelf(function (idx) {
  50476. var edge = edges[edgeData.getRawIndex(idx)];
  50477. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  50478. }); // Update edge
  50479. for (var i = 0, len = edges.length; i < len; i++) {
  50480. edges[i].dataIndex = -1;
  50481. }
  50482. for (var i = 0, len = edgeData.count(); i < len; i++) {
  50483. edges[edgeData.getRawIndex(i)].dataIndex = i;
  50484. }
  50485. };
  50486. /**
  50487. * @return {module:echarts/data/Graph}
  50488. */
  50489. Graph.prototype.clone = function () {
  50490. var graph = new Graph(this._directed);
  50491. var nodes = this.nodes;
  50492. var edges = this.edges;
  50493. for (var i = 0; i < nodes.length; i++) {
  50494. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  50495. }
  50496. for (var i = 0; i < edges.length; i++) {
  50497. var e = edges[i];
  50498. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  50499. }
  50500. return graph;
  50501. };
  50502. return Graph;
  50503. }();
  50504. var GraphNode =
  50505. /** @class */
  50506. function () {
  50507. function GraphNode(id, dataIndex) {
  50508. this.inEdges = [];
  50509. this.outEdges = [];
  50510. this.edges = [];
  50511. this.dataIndex = -1;
  50512. this.id = id == null ? '' : id;
  50513. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  50514. }
  50515. /**
  50516. * @return {number}
  50517. */
  50518. GraphNode.prototype.degree = function () {
  50519. return this.edges.length;
  50520. };
  50521. /**
  50522. * @return {number}
  50523. */
  50524. GraphNode.prototype.inDegree = function () {
  50525. return this.inEdges.length;
  50526. };
  50527. /**
  50528. * @return {number}
  50529. */
  50530. GraphNode.prototype.outDegree = function () {
  50531. return this.outEdges.length;
  50532. };
  50533. GraphNode.prototype.getModel = function (path) {
  50534. if (this.dataIndex < 0) {
  50535. return;
  50536. }
  50537. var graph = this.hostGraph;
  50538. var itemModel = graph.data.getItemModel(this.dataIndex);
  50539. return itemModel.getModel(path);
  50540. };
  50541. GraphNode.prototype.getAdjacentDataIndices = function () {
  50542. var dataIndices = {
  50543. edge: [],
  50544. node: []
  50545. };
  50546. for (var i = 0; i < this.edges.length; i++) {
  50547. var adjacentEdge = this.edges[i];
  50548. if (adjacentEdge.dataIndex < 0) {
  50549. continue;
  50550. }
  50551. dataIndices.edge.push(adjacentEdge.dataIndex);
  50552. dataIndices.node.push(adjacentEdge.node1.dataIndex, adjacentEdge.node2.dataIndex);
  50553. }
  50554. return dataIndices;
  50555. };
  50556. return GraphNode;
  50557. }();
  50558. var GraphEdge =
  50559. /** @class */
  50560. function () {
  50561. function GraphEdge(n1, n2, dataIndex) {
  50562. this.dataIndex = -1;
  50563. this.node1 = n1;
  50564. this.node2 = n2;
  50565. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  50566. }
  50567. GraphEdge.prototype.getModel = function (path) {
  50568. if (this.dataIndex < 0) {
  50569. return;
  50570. }
  50571. var graph = this.hostGraph;
  50572. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  50573. return itemModel.getModel(path);
  50574. };
  50575. GraphEdge.prototype.getAdjacentDataIndices = function () {
  50576. return {
  50577. edge: [this.dataIndex],
  50578. node: [this.node1.dataIndex, this.node2.dataIndex]
  50579. };
  50580. };
  50581. return GraphEdge;
  50582. }();
  50583. function createGraphDataProxyMixin(hostName, dataName) {
  50584. return {
  50585. /**
  50586. * @param Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  50587. */
  50588. getValue: function (dimension) {
  50589. var data = this[hostName][dataName];
  50590. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  50591. },
  50592. // TODO: TYPE stricter type.
  50593. setVisual: function (key, value) {
  50594. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  50595. },
  50596. getVisual: function (key) {
  50597. return this[hostName][dataName].getItemVisual(this.dataIndex, key);
  50598. },
  50599. setLayout: function (layout, merge) {
  50600. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge);
  50601. },
  50602. getLayout: function () {
  50603. return this[hostName][dataName].getItemLayout(this.dataIndex);
  50604. },
  50605. getGraphicEl: function () {
  50606. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  50607. },
  50608. getRawIndex: function () {
  50609. return this[hostName][dataName].getRawIndex(this.dataIndex);
  50610. }
  50611. };
  50612. }
  50613. mixin(GraphNode, createGraphDataProxyMixin('hostGraph', 'data'));
  50614. mixin(GraphEdge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  50615. function createGraphFromNodeEdge(nodes, edges, seriesModel, directed, beforeLink) {
  50616. // ??? TODO
  50617. // support dataset?
  50618. var graph = new Graph(directed);
  50619. for (var i = 0; i < nodes.length; i++) {
  50620. graph.addNode(retrieve( // Id, name, dataIndex
  50621. nodes[i].id, nodes[i].name, i), i);
  50622. }
  50623. var linkNameList = [];
  50624. var validEdges = [];
  50625. var linkCount = 0;
  50626. for (var i = 0; i < edges.length; i++) {
  50627. var link = edges[i];
  50628. var source = link.source;
  50629. var target = link.target; // addEdge may fail when source or target not exists
  50630. if (graph.addEdge(source, target, linkCount)) {
  50631. validEdges.push(link);
  50632. linkNameList.push(retrieve(convertOptionIdName(link.id, null), source + ' > ' + target));
  50633. linkCount++;
  50634. }
  50635. }
  50636. var coordSys = seriesModel.get('coordinateSystem');
  50637. var nodeData;
  50638. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  50639. nodeData = createListFromArray(nodes, seriesModel);
  50640. } else {
  50641. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  50642. var coordDimensions = coordSysCtor ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  50643. // `value` dimension, but graph need `value` dimension. It's better to
  50644. // uniform this behavior.
  50645. if (indexOf(coordDimensions, 'value') < 0) {
  50646. coordDimensions.concat(['value']);
  50647. }
  50648. var dimensionNames = createDimensions(nodes, {
  50649. coordDimensions: coordDimensions
  50650. });
  50651. nodeData = new List(dimensionNames, seriesModel);
  50652. nodeData.initData(nodes);
  50653. }
  50654. var edgeData = new List(['value'], seriesModel);
  50655. edgeData.initData(validEdges, linkNameList);
  50656. beforeLink && beforeLink(nodeData, edgeData);
  50657. linkList({
  50658. mainData: nodeData,
  50659. struct: graph,
  50660. structAttr: 'graph',
  50661. datas: {
  50662. node: nodeData,
  50663. edge: edgeData
  50664. },
  50665. datasAttr: {
  50666. node: 'data',
  50667. edge: 'edgeData'
  50668. }
  50669. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  50670. graph.update();
  50671. return graph;
  50672. }
  50673. var GraphSeriesModel =
  50674. /** @class */
  50675. function (_super) {
  50676. __extends(GraphSeriesModel, _super);
  50677. function GraphSeriesModel() {
  50678. var _this = _super !== null && _super.apply(this, arguments) || this;
  50679. _this.type = GraphSeriesModel.type;
  50680. _this.hasSymbolVisual = true;
  50681. return _this;
  50682. }
  50683. GraphSeriesModel.prototype.init = function (option) {
  50684. _super.prototype.init.apply(this, arguments);
  50685. var self = this;
  50686. function getCategoriesData() {
  50687. return self._categoriesData;
  50688. } // Provide data for legend select
  50689. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  50690. this.fillDataTextStyle(option.edges || option.links);
  50691. this._updateCategoriesData();
  50692. };
  50693. GraphSeriesModel.prototype.mergeOption = function (option) {
  50694. _super.prototype.mergeOption.apply(this, arguments);
  50695. this.fillDataTextStyle(option.edges || option.links);
  50696. this._updateCategoriesData();
  50697. };
  50698. GraphSeriesModel.prototype.mergeDefaultAndTheme = function (option) {
  50699. _super.prototype.mergeDefaultAndTheme.apply(this, arguments);
  50700. defaultEmphasis(option, 'edgeLabel', ['show']);
  50701. };
  50702. GraphSeriesModel.prototype.getInitialData = function (option, ecModel) {
  50703. var edges = option.edges || option.links || [];
  50704. var nodes = option.data || option.nodes || [];
  50705. var self = this;
  50706. if (nodes && edges) {
  50707. // auto curveness
  50708. initCurvenessList(this);
  50709. var graph = createGraphFromNodeEdge(nodes, edges, this, true, beforeLink);
  50710. each(graph.edges, function (edge) {
  50711. createEdgeMapForCurveness(edge.node1, edge.node2, this, edge.dataIndex);
  50712. }, this);
  50713. return graph.data;
  50714. }
  50715. function beforeLink(nodeData, edgeData) {
  50716. // Overwrite nodeData.getItemModel to
  50717. nodeData.wrapMethod('getItemModel', function (model) {
  50718. var categoriesModels = self._categoriesModels;
  50719. var categoryIdx = model.getShallow('category');
  50720. var categoryModel = categoriesModels[categoryIdx];
  50721. if (categoryModel) {
  50722. categoryModel.parentModel = model.parentModel;
  50723. model.parentModel = categoryModel;
  50724. }
  50725. return model;
  50726. }); // TODO Inherit resolveParentPath by default in Model#getModel?
  50727. var oldGetModel = Model.prototype.getModel;
  50728. function newGetModel(path, parentModel) {
  50729. var model = oldGetModel.call(this, path, parentModel);
  50730. model.resolveParentPath = resolveParentPath;
  50731. return model;
  50732. }
  50733. edgeData.wrapMethod('getItemModel', function (model) {
  50734. model.resolveParentPath = resolveParentPath;
  50735. model.getModel = newGetModel;
  50736. return model;
  50737. });
  50738. function resolveParentPath(pathArr) {
  50739. if (pathArr && (pathArr[0] === 'label' || pathArr[1] === 'label')) {
  50740. var newPathArr = pathArr.slice();
  50741. if (pathArr[0] === 'label') {
  50742. newPathArr[0] = 'edgeLabel';
  50743. } else if (pathArr[1] === 'label') {
  50744. newPathArr[1] = 'edgeLabel';
  50745. }
  50746. return newPathArr;
  50747. }
  50748. return pathArr;
  50749. }
  50750. }
  50751. };
  50752. GraphSeriesModel.prototype.getGraph = function () {
  50753. return this.getData().graph;
  50754. };
  50755. GraphSeriesModel.prototype.getEdgeData = function () {
  50756. return this.getGraph().edgeData;
  50757. };
  50758. GraphSeriesModel.prototype.getCategoriesData = function () {
  50759. return this._categoriesData;
  50760. };
  50761. GraphSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  50762. if (dataType === 'edge') {
  50763. var nodeData = this.getData();
  50764. var params = this.getDataParams(dataIndex, dataType);
  50765. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  50766. var sourceName = nodeData.getName(edge.node1.dataIndex);
  50767. var targetName = nodeData.getName(edge.node2.dataIndex);
  50768. var nameArr = [];
  50769. sourceName != null && nameArr.push(sourceName);
  50770. targetName != null && nameArr.push(targetName);
  50771. return createTooltipMarkup('nameValue', {
  50772. name: nameArr.join(' > '),
  50773. value: params.value,
  50774. noValue: params.value == null
  50775. });
  50776. } // dataType === 'node' or empty
  50777. var nodeMarkup = defaultSeriesFormatTooltip({
  50778. series: this,
  50779. dataIndex: dataIndex,
  50780. multipleSeries: multipleSeries
  50781. });
  50782. return nodeMarkup;
  50783. };
  50784. GraphSeriesModel.prototype._updateCategoriesData = function () {
  50785. var categories = map(this.option.categories || [], function (category) {
  50786. // Data must has value
  50787. return category.value != null ? category : extend({
  50788. value: 0
  50789. }, category);
  50790. });
  50791. var categoriesData = new List(['value'], this);
  50792. categoriesData.initData(categories);
  50793. this._categoriesData = categoriesData;
  50794. this._categoriesModels = categoriesData.mapArray(function (idx) {
  50795. return categoriesData.getItemModel(idx);
  50796. });
  50797. };
  50798. GraphSeriesModel.prototype.setZoom = function (zoom) {
  50799. this.option.zoom = zoom;
  50800. };
  50801. GraphSeriesModel.prototype.setCenter = function (center) {
  50802. this.option.center = center;
  50803. };
  50804. GraphSeriesModel.prototype.isAnimationEnabled = function () {
  50805. return _super.prototype.isAnimationEnabled.call(this) // Not enable animation when do force layout
  50806. && !(this.get('layout') === 'force' && this.get(['force', 'layoutAnimation']));
  50807. };
  50808. GraphSeriesModel.type = 'series.graph';
  50809. GraphSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  50810. GraphSeriesModel.defaultOption = {
  50811. zlevel: 0,
  50812. z: 2,
  50813. coordinateSystem: 'view',
  50814. // Default option for all coordinate systems
  50815. // xAxisIndex: 0,
  50816. // yAxisIndex: 0,
  50817. // polarIndex: 0,
  50818. // geoIndex: 0,
  50819. legendHoverLink: true,
  50820. layout: null,
  50821. // Configuration of circular layout
  50822. circular: {
  50823. rotateLabel: false
  50824. },
  50825. // Configuration of force directed layout
  50826. force: {
  50827. initLayout: null,
  50828. // Node repulsion. Can be an array to represent range.
  50829. repulsion: [0, 50],
  50830. gravity: 0.1,
  50831. // Initial friction
  50832. friction: 0.6,
  50833. // Edge length. Can be an array to represent range.
  50834. edgeLength: 30,
  50835. layoutAnimation: true
  50836. },
  50837. left: 'center',
  50838. top: 'center',
  50839. // right: null,
  50840. // bottom: null,
  50841. // width: '80%',
  50842. // height: '80%',
  50843. symbol: 'circle',
  50844. symbolSize: 10,
  50845. edgeSymbol: ['none', 'none'],
  50846. edgeSymbolSize: 10,
  50847. edgeLabel: {
  50848. position: 'middle',
  50849. distance: 5
  50850. },
  50851. draggable: false,
  50852. roam: false,
  50853. // Default on center of graph
  50854. center: null,
  50855. zoom: 1,
  50856. // Symbol size scale ratio in roam
  50857. nodeScaleRatio: 0.6,
  50858. // cursor: null,
  50859. // categories: [],
  50860. // data: []
  50861. // Or
  50862. // nodes: []
  50863. //
  50864. // links: []
  50865. // Or
  50866. // edges: []
  50867. label: {
  50868. show: false,
  50869. formatter: '{b}'
  50870. },
  50871. itemStyle: {},
  50872. lineStyle: {
  50873. color: '#aaa',
  50874. width: 1,
  50875. opacity: 0.5
  50876. },
  50877. emphasis: {
  50878. scale: true,
  50879. label: {
  50880. show: true
  50881. }
  50882. },
  50883. select: {
  50884. itemStyle: {
  50885. borderColor: '#212121'
  50886. }
  50887. }
  50888. };
  50889. return GraphSeriesModel;
  50890. }(SeriesModel);
  50891. var actionInfo = {
  50892. type: 'graphRoam',
  50893. event: 'graphRoam',
  50894. update: 'none'
  50895. };
  50896. function install$d(registers) {
  50897. registers.registerChartView(GraphView);
  50898. registers.registerSeriesModel(GraphSeriesModel);
  50899. registers.registerProcessor(categoryFilter);
  50900. registers.registerVisual(categoryVisual);
  50901. registers.registerVisual(graphEdgeVisual);
  50902. registers.registerLayout(graphSimpleLayout);
  50903. registers.registerLayout(registers.PRIORITY.VISUAL.POST_CHART_LAYOUT, graphCircularLayout);
  50904. registers.registerLayout(graphForceLayout);
  50905. registers.registerCoordinateSystem('graphView', {
  50906. dimensions: View.dimensions,
  50907. create: createViewCoordSys
  50908. }); // Register legacy focus actions
  50909. registers.registerAction({
  50910. type: 'focusNodeAdjacency',
  50911. event: 'focusNodeAdjacency',
  50912. update: 'series:focusNodeAdjacency'
  50913. }, function () {});
  50914. registers.registerAction({
  50915. type: 'unfocusNodeAdjacency',
  50916. event: 'unfocusNodeAdjacency',
  50917. update: 'series:unfocusNodeAdjacency'
  50918. }, function () {}); // Register roam action.
  50919. registers.registerAction(actionInfo, function (payload, ecModel) {
  50920. ecModel.eachComponent({
  50921. mainType: 'series',
  50922. query: payload
  50923. }, function (seriesModel) {
  50924. var coordSys = seriesModel.coordinateSystem;
  50925. var res = updateCenterAndZoom(coordSys, payload);
  50926. seriesModel.setCenter && seriesModel.setCenter(res.center);
  50927. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  50928. });
  50929. });
  50930. }
  50931. var PointerShape =
  50932. /** @class */
  50933. function () {
  50934. function PointerShape() {
  50935. this.angle = 0;
  50936. this.width = 10;
  50937. this.r = 10;
  50938. this.x = 0;
  50939. this.y = 0;
  50940. }
  50941. return PointerShape;
  50942. }();
  50943. var PointerPath =
  50944. /** @class */
  50945. function (_super) {
  50946. __extends(PointerPath, _super);
  50947. function PointerPath(opts) {
  50948. var _this = _super.call(this, opts) || this;
  50949. _this.type = 'pointer';
  50950. return _this;
  50951. }
  50952. PointerPath.prototype.getDefaultShape = function () {
  50953. return new PointerShape();
  50954. };
  50955. PointerPath.prototype.buildPath = function (ctx, shape) {
  50956. var mathCos = Math.cos;
  50957. var mathSin = Math.sin;
  50958. var r = shape.r;
  50959. var width = shape.width;
  50960. var angle = shape.angle;
  50961. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  50962. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  50963. angle = shape.angle - Math.PI / 2;
  50964. ctx.moveTo(x, y);
  50965. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  50966. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  50967. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  50968. ctx.lineTo(x, y);
  50969. };
  50970. return PointerPath;
  50971. }(Path);
  50972. function parsePosition(seriesModel, api) {
  50973. var center = seriesModel.get('center');
  50974. var width = api.getWidth();
  50975. var height = api.getHeight();
  50976. var size = Math.min(width, height);
  50977. var cx = parsePercent$1(center[0], api.getWidth());
  50978. var cy = parsePercent$1(center[1], api.getHeight());
  50979. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  50980. return {
  50981. cx: cx,
  50982. cy: cy,
  50983. r: r
  50984. };
  50985. }
  50986. function formatLabel(value, labelFormatter) {
  50987. var label = value == null ? '' : value + '';
  50988. if (labelFormatter) {
  50989. if (typeof labelFormatter === 'string') {
  50990. label = labelFormatter.replace('{value}', label);
  50991. } else if (typeof labelFormatter === 'function') {
  50992. label = labelFormatter(value);
  50993. }
  50994. }
  50995. return label;
  50996. }
  50997. var PI2$9 = Math.PI * 2;
  50998. var GaugeView =
  50999. /** @class */
  51000. function (_super) {
  51001. __extends(GaugeView, _super);
  51002. function GaugeView() {
  51003. var _this = _super !== null && _super.apply(this, arguments) || this;
  51004. _this.type = GaugeView.type;
  51005. return _this;
  51006. }
  51007. GaugeView.prototype.render = function (seriesModel, ecModel, api) {
  51008. this.group.removeAll();
  51009. var colorList = seriesModel.get(['axisLine', 'lineStyle', 'color']);
  51010. var posInfo = parsePosition(seriesModel, api);
  51011. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  51012. this._data = seriesModel.getData();
  51013. };
  51014. GaugeView.prototype.dispose = function () {};
  51015. GaugeView.prototype._renderMain = function (seriesModel, ecModel, api, colorList, posInfo) {
  51016. var group = this.group;
  51017. var clockwise = seriesModel.get('clockwise');
  51018. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  51019. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  51020. var axisLineModel = seriesModel.getModel('axisLine');
  51021. var roundCap = axisLineModel.get('roundCap');
  51022. var MainPath = roundCap ? SausagePath : Sector;
  51023. var showAxis = axisLineModel.get('show');
  51024. var lineStyleModel = axisLineModel.getModel('lineStyle');
  51025. var axisLineWidth = lineStyleModel.get('width');
  51026. var angleRangeSpan = !((endAngle - startAngle) % PI2$9) && endAngle !== startAngle ? PI2$9 : (endAngle - startAngle) % PI2$9;
  51027. var prevEndAngle = startAngle;
  51028. for (var i = 0; showAxis && i < colorList.length; i++) {
  51029. // Clamp
  51030. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  51031. endAngle = startAngle + angleRangeSpan * percent;
  51032. var sector = new MainPath({
  51033. shape: {
  51034. startAngle: prevEndAngle,
  51035. endAngle: endAngle,
  51036. cx: posInfo.cx,
  51037. cy: posInfo.cy,
  51038. clockwise: clockwise,
  51039. r0: posInfo.r - axisLineWidth,
  51040. r: posInfo.r
  51041. },
  51042. silent: true
  51043. });
  51044. sector.setStyle({
  51045. fill: colorList[i][1]
  51046. });
  51047. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  51048. // so the properties for stroking are useless
  51049. ['color', 'width']));
  51050. group.add(sector);
  51051. prevEndAngle = endAngle;
  51052. }
  51053. var getColor = function (percent) {
  51054. // Less than 0
  51055. if (percent <= 0) {
  51056. return colorList[0][1];
  51057. }
  51058. var i;
  51059. for (i = 0; i < colorList.length; i++) {
  51060. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  51061. return colorList[i][1];
  51062. }
  51063. } // More than 1
  51064. return colorList[i - 1][1];
  51065. };
  51066. if (!clockwise) {
  51067. var tmp = startAngle;
  51068. startAngle = endAngle;
  51069. endAngle = tmp;
  51070. }
  51071. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  51072. this._renderTitleAndDetail(seriesModel, ecModel, api, getColor, posInfo);
  51073. this._renderAnchor(seriesModel, posInfo);
  51074. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth);
  51075. };
  51076. GaugeView.prototype._renderTicks = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  51077. var group = this.group;
  51078. var cx = posInfo.cx;
  51079. var cy = posInfo.cy;
  51080. var r = posInfo.r;
  51081. var minVal = +seriesModel.get('min');
  51082. var maxVal = +seriesModel.get('max');
  51083. var splitLineModel = seriesModel.getModel('splitLine');
  51084. var tickModel = seriesModel.getModel('axisTick');
  51085. var labelModel = seriesModel.getModel('axisLabel');
  51086. var splitNumber = seriesModel.get('splitNumber');
  51087. var subSplitNumber = tickModel.get('splitNumber');
  51088. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  51089. var tickLen = parsePercent$1(tickModel.get('length'), r);
  51090. var angle = startAngle;
  51091. var step = (endAngle - startAngle) / splitNumber;
  51092. var subStep = step / subSplitNumber;
  51093. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  51094. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  51095. var splitLineDistance = splitLineModel.get('distance');
  51096. var unitX;
  51097. var unitY;
  51098. for (var i = 0; i <= splitNumber; i++) {
  51099. unitX = Math.cos(angle);
  51100. unitY = Math.sin(angle); // Split line
  51101. if (splitLineModel.get('show')) {
  51102. var distance = splitLineDistance ? splitLineDistance + axisLineWidth : axisLineWidth;
  51103. var splitLine = new Line({
  51104. shape: {
  51105. x1: unitX * (r - distance) + cx,
  51106. y1: unitY * (r - distance) + cy,
  51107. x2: unitX * (r - splitLineLen - distance) + cx,
  51108. y2: unitY * (r - splitLineLen - distance) + cy
  51109. },
  51110. style: splitLineStyle,
  51111. silent: true
  51112. });
  51113. if (splitLineStyle.stroke === 'auto') {
  51114. splitLine.setStyle({
  51115. stroke: getColor(i / splitNumber)
  51116. });
  51117. }
  51118. group.add(splitLine);
  51119. } // Label
  51120. if (labelModel.get('show')) {
  51121. var distance = labelModel.get('distance') + splitLineDistance;
  51122. var label = formatLabel(round(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  51123. var autoColor = getColor(i / splitNumber);
  51124. group.add(new ZRText({
  51125. style: createTextStyle(labelModel, {
  51126. text: label,
  51127. x: unitX * (r - splitLineLen - distance) + cx,
  51128. y: unitY * (r - splitLineLen - distance) + cy,
  51129. verticalAlign: unitY < -0.8 ? 'top' : unitY > 0.8 ? 'bottom' : 'middle',
  51130. align: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  51131. }, {
  51132. inheritColor: autoColor
  51133. }),
  51134. silent: true
  51135. }));
  51136. } // Axis tick
  51137. if (tickModel.get('show') && i !== splitNumber) {
  51138. var distance = tickModel.get('distance');
  51139. distance = distance ? distance + axisLineWidth : axisLineWidth;
  51140. for (var j = 0; j <= subSplitNumber; j++) {
  51141. unitX = Math.cos(angle);
  51142. unitY = Math.sin(angle);
  51143. var tickLine = new Line({
  51144. shape: {
  51145. x1: unitX * (r - distance) + cx,
  51146. y1: unitY * (r - distance) + cy,
  51147. x2: unitX * (r - tickLen - distance) + cx,
  51148. y2: unitY * (r - tickLen - distance) + cy
  51149. },
  51150. silent: true,
  51151. style: tickLineStyle
  51152. });
  51153. if (tickLineStyle.stroke === 'auto') {
  51154. tickLine.setStyle({
  51155. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  51156. });
  51157. }
  51158. group.add(tickLine);
  51159. angle += subStep;
  51160. }
  51161. angle -= subStep;
  51162. } else {
  51163. angle += step;
  51164. }
  51165. }
  51166. };
  51167. GaugeView.prototype._renderPointer = function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise, axisLineWidth) {
  51168. var group = this.group;
  51169. var oldData = this._data;
  51170. var oldProgressData = this._progressEls;
  51171. var progressList = [];
  51172. var showPointer = seriesModel.get(['pointer', 'show']);
  51173. var progressModel = seriesModel.getModel('progress');
  51174. var showProgress = progressModel.get('show');
  51175. var data = seriesModel.getData();
  51176. var valueDim = data.mapDimension('value');
  51177. var minVal = +seriesModel.get('min');
  51178. var maxVal = +seriesModel.get('max');
  51179. var valueExtent = [minVal, maxVal];
  51180. var angleExtent = [startAngle, endAngle];
  51181. function createPointer(idx, angle) {
  51182. var itemModel = data.getItemModel(idx);
  51183. var pointerModel = itemModel.getModel('pointer');
  51184. var pointerWidth = parsePercent$1(pointerModel.get('width'), posInfo.r);
  51185. var pointerLength = parsePercent$1(pointerModel.get('length'), posInfo.r);
  51186. var pointerStr = seriesModel.get(['pointer', 'icon']);
  51187. var pointerOffset = pointerModel.get('offsetCenter');
  51188. var pointerOffsetX = parsePercent$1(pointerOffset[0], posInfo.r);
  51189. var pointerOffsetY = parsePercent$1(pointerOffset[1], posInfo.r);
  51190. var pointerKeepAspect = pointerModel.get('keepAspect');
  51191. var pointer; // not exist icon type will be set 'rect'
  51192. if (pointerStr) {
  51193. pointer = createSymbol(pointerStr, pointerOffsetX - pointerWidth / 2, pointerOffsetY - pointerLength, pointerWidth, pointerLength, null, pointerKeepAspect);
  51194. } else {
  51195. pointer = new PointerPath({
  51196. shape: {
  51197. angle: -Math.PI / 2,
  51198. width: pointerWidth,
  51199. r: pointerLength,
  51200. x: pointerOffsetX,
  51201. y: pointerOffsetY
  51202. }
  51203. });
  51204. }
  51205. pointer.rotation = -(angle + Math.PI / 2);
  51206. pointer.x = posInfo.cx;
  51207. pointer.y = posInfo.cy;
  51208. return pointer;
  51209. }
  51210. function createProgress(idx, endAngle) {
  51211. var roundCap = progressModel.get('roundCap');
  51212. var ProgressPath = roundCap ? SausagePath : Sector;
  51213. var isOverlap = progressModel.get('overlap');
  51214. var progressWidth = isOverlap ? progressModel.get('width') : axisLineWidth / data.count();
  51215. var r0 = isOverlap ? posInfo.r - progressWidth : posInfo.r - (idx + 1) * progressWidth;
  51216. var r = isOverlap ? posInfo.r : posInfo.r - idx * progressWidth;
  51217. var progress = new ProgressPath({
  51218. shape: {
  51219. startAngle: startAngle,
  51220. endAngle: endAngle,
  51221. cx: posInfo.cx,
  51222. cy: posInfo.cy,
  51223. clockwise: clockwise,
  51224. r0: r0,
  51225. r: r
  51226. }
  51227. });
  51228. isOverlap && (progress.z2 = maxVal - data.get(valueDim, idx) % maxVal);
  51229. return progress;
  51230. }
  51231. if (showProgress || showPointer) {
  51232. data.diff(oldData).add(function (idx) {
  51233. if (showPointer) {
  51234. var pointer = createPointer(idx, startAngle);
  51235. initProps(pointer, {
  51236. rotation: -(linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true) + Math.PI / 2)
  51237. }, seriesModel);
  51238. group.add(pointer);
  51239. data.setItemGraphicEl(idx, pointer);
  51240. }
  51241. if (showProgress) {
  51242. var progress = createProgress(idx, startAngle);
  51243. var isClip = progressModel.get('clip');
  51244. initProps(progress, {
  51245. shape: {
  51246. endAngle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, isClip)
  51247. }
  51248. }, seriesModel);
  51249. group.add(progress);
  51250. progressList[idx] = progress;
  51251. }
  51252. }).update(function (newIdx, oldIdx) {
  51253. if (showPointer) {
  51254. var previousPointer = oldData.getItemGraphicEl(oldIdx);
  51255. var previousRotate = previousPointer ? previousPointer.rotation : startAngle;
  51256. var pointer = createPointer(newIdx, previousRotate);
  51257. pointer.rotation = previousRotate;
  51258. updateProps(pointer, {
  51259. rotation: -(linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true) + Math.PI / 2)
  51260. }, seriesModel);
  51261. group.add(pointer);
  51262. data.setItemGraphicEl(newIdx, pointer);
  51263. }
  51264. if (showProgress) {
  51265. var previousProgress = oldProgressData[oldIdx];
  51266. var previousEndAngle = previousProgress ? previousProgress.shape.endAngle : startAngle;
  51267. var progress = createProgress(newIdx, previousEndAngle);
  51268. var isClip = progressModel.get('clip');
  51269. updateProps(progress, {
  51270. shape: {
  51271. endAngle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, isClip)
  51272. }
  51273. }, seriesModel);
  51274. group.add(progress);
  51275. progressList[newIdx] = progress;
  51276. }
  51277. }).execute();
  51278. data.each(function (idx) {
  51279. var itemModel = data.getItemModel(idx);
  51280. var emphasisModel = itemModel.getModel('emphasis');
  51281. if (showPointer) {
  51282. var pointer = data.getItemGraphicEl(idx);
  51283. pointer.useStyle(data.getItemVisual(idx, 'style'));
  51284. pointer.setStyle(itemModel.getModel(['pointer', 'itemStyle']).getItemStyle());
  51285. if (pointer.style.fill === 'auto') {
  51286. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  51287. }
  51288. pointer.z2EmphasisLift = 0;
  51289. setStatesStylesFromModel(pointer, itemModel);
  51290. enableHoverEmphasis(pointer, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  51291. }
  51292. if (showProgress) {
  51293. var progress = progressList[idx];
  51294. progress.useStyle(data.getItemVisual(idx, 'style'));
  51295. progress.setStyle(itemModel.getModel(['progress', 'itemStyle']).getItemStyle());
  51296. progress.z2EmphasisLift = 0;
  51297. setStatesStylesFromModel(progress, itemModel);
  51298. enableHoverEmphasis(progress, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  51299. }
  51300. });
  51301. this._progressEls = progressList;
  51302. }
  51303. };
  51304. GaugeView.prototype._renderAnchor = function (seriesModel, posInfo) {
  51305. var anchorModel = seriesModel.getModel('anchor');
  51306. var showAnchor = anchorModel.get('show');
  51307. if (showAnchor) {
  51308. var anchorSize = anchorModel.get('size');
  51309. var anchorType = anchorModel.get('icon');
  51310. var offsetCenter = anchorModel.get('offsetCenter');
  51311. var anchorKeepAspect = anchorModel.get('keepAspect');
  51312. 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);
  51313. anchor.z2 = anchorModel.get('showAbove') ? 1 : 0;
  51314. anchor.setStyle(anchorModel.getModel('itemStyle').getItemStyle());
  51315. this.group.add(anchor);
  51316. }
  51317. };
  51318. GaugeView.prototype._renderTitleAndDetail = function (seriesModel, ecModel, api, getColor, posInfo) {
  51319. var _this = this;
  51320. var data = seriesModel.getData();
  51321. var valueDim = data.mapDimension('value');
  51322. var minVal = +seriesModel.get('min');
  51323. var maxVal = +seriesModel.get('max');
  51324. var contentGroup = new Group();
  51325. var newTitleEls = [];
  51326. var newDetailEls = [];
  51327. var hasAnimation = seriesModel.isAnimationEnabled();
  51328. data.diff(this._data).add(function (idx) {
  51329. newTitleEls[idx] = new ZRText({
  51330. silent: true
  51331. });
  51332. newDetailEls[idx] = new ZRText({
  51333. silent: true
  51334. });
  51335. }).update(function (idx, oldIdx) {
  51336. newTitleEls[idx] = _this._titleEls[oldIdx];
  51337. newDetailEls[idx] = _this._detailEls[oldIdx];
  51338. }).execute();
  51339. data.each(function (idx) {
  51340. var itemModel = data.getItemModel(idx);
  51341. var value = data.get(valueDim, idx);
  51342. var itemGroup = new Group();
  51343. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  51344. var itemTitleModel = itemModel.getModel('title');
  51345. if (itemTitleModel.get('show')) {
  51346. var titleOffsetCenter = itemTitleModel.get('offsetCenter');
  51347. var titleX = posInfo.cx + parsePercent$1(titleOffsetCenter[0], posInfo.r);
  51348. var titleY = posInfo.cy + parsePercent$1(titleOffsetCenter[1], posInfo.r);
  51349. var labelEl = newTitleEls[idx];
  51350. labelEl.attr({
  51351. style: createTextStyle(itemTitleModel, {
  51352. x: titleX,
  51353. y: titleY,
  51354. text: data.getName(idx),
  51355. align: 'center',
  51356. verticalAlign: 'middle'
  51357. }, {
  51358. inheritColor: autoColor
  51359. })
  51360. });
  51361. itemGroup.add(labelEl);
  51362. }
  51363. var itemDetailModel = itemModel.getModel('detail');
  51364. if (itemDetailModel.get('show')) {
  51365. var detailOffsetCenter = itemDetailModel.get('offsetCenter');
  51366. var detailX = posInfo.cx + parsePercent$1(detailOffsetCenter[0], posInfo.r);
  51367. var detailY = posInfo.cy + parsePercent$1(detailOffsetCenter[1], posInfo.r);
  51368. var width = parsePercent$1(itemDetailModel.get('width'), posInfo.r);
  51369. var height = parsePercent$1(itemDetailModel.get('height'), posInfo.r);
  51370. var detailColor = seriesModel.get(['progress', 'show']) ? data.getItemVisual(idx, 'style').fill : autoColor;
  51371. var labelEl = newDetailEls[idx];
  51372. var formatter_1 = itemDetailModel.get('formatter');
  51373. labelEl.attr({
  51374. style: createTextStyle(itemDetailModel, {
  51375. x: detailX,
  51376. y: detailY,
  51377. text: formatLabel(value, formatter_1),
  51378. width: isNaN(width) ? null : width,
  51379. height: isNaN(height) ? null : height,
  51380. align: 'center',
  51381. verticalAlign: 'middle'
  51382. }, {
  51383. inheritColor: detailColor
  51384. })
  51385. });
  51386. setLabelValueAnimation(labelEl, {
  51387. normal: itemDetailModel
  51388. }, value, function (value) {
  51389. return formatLabel(value, formatter_1);
  51390. });
  51391. hasAnimation && animateLabelValue(labelEl, idx, data, seriesModel, {
  51392. getFormattedLabel: function (labelDataIndex, status, dataType, labelDimIndex, fmt, extendParams) {
  51393. return formatLabel(extendParams ? extendParams.interpolatedValue : value, formatter_1);
  51394. }
  51395. });
  51396. itemGroup.add(labelEl);
  51397. }
  51398. contentGroup.add(itemGroup);
  51399. });
  51400. this.group.add(contentGroup);
  51401. this._titleEls = newTitleEls;
  51402. this._detailEls = newDetailEls;
  51403. };
  51404. GaugeView.type = 'gauge';
  51405. return GaugeView;
  51406. }(ChartView);
  51407. var GaugeSeriesModel =
  51408. /** @class */
  51409. function (_super) {
  51410. __extends(GaugeSeriesModel, _super);
  51411. function GaugeSeriesModel() {
  51412. var _this = _super !== null && _super.apply(this, arguments) || this;
  51413. _this.type = GaugeSeriesModel.type;
  51414. _this.visualStyleAccessPath = 'itemStyle';
  51415. _this.useColorPaletteOnData = true;
  51416. return _this;
  51417. }
  51418. GaugeSeriesModel.prototype.getInitialData = function (option, ecModel) {
  51419. return createListSimply(this, ['value']);
  51420. };
  51421. GaugeSeriesModel.type = 'series.gauge';
  51422. GaugeSeriesModel.defaultOption = {
  51423. zlevel: 0,
  51424. z: 2,
  51425. // 默认全局居中
  51426. center: ['50%', '50%'],
  51427. legendHoverLink: true,
  51428. radius: '75%',
  51429. startAngle: 225,
  51430. endAngle: -45,
  51431. clockwise: true,
  51432. // 最小值
  51433. min: 0,
  51434. // 最大值
  51435. max: 100,
  51436. // 分割段数,默认为10
  51437. splitNumber: 10,
  51438. // 坐标轴线
  51439. axisLine: {
  51440. // 默认显示,属性show控制显示与否
  51441. show: true,
  51442. roundCap: false,
  51443. lineStyle: {
  51444. color: [[1, '#E6EBF8']],
  51445. width: 10
  51446. }
  51447. },
  51448. // 坐标轴线
  51449. progress: {
  51450. // 默认显示,属性show控制显示与否
  51451. show: false,
  51452. overlap: true,
  51453. width: 10,
  51454. roundCap: false,
  51455. clip: true
  51456. },
  51457. // 分隔线
  51458. splitLine: {
  51459. // 默认显示,属性show控制显示与否
  51460. show: true,
  51461. // 属性length控制线长
  51462. length: 10,
  51463. distance: 10,
  51464. // 属性lineStyle(详见lineStyle)控制线条样式
  51465. lineStyle: {
  51466. color: '#63677A',
  51467. width: 3,
  51468. type: 'solid'
  51469. }
  51470. },
  51471. // 坐标轴小标记
  51472. axisTick: {
  51473. // 属性show控制显示与否,默认不显示
  51474. show: true,
  51475. // 每份split细分多少段
  51476. splitNumber: 5,
  51477. // 属性length控制线长
  51478. length: 6,
  51479. distance: 10,
  51480. // 属性lineStyle控制线条样式
  51481. lineStyle: {
  51482. color: '#63677A',
  51483. width: 1,
  51484. type: 'solid'
  51485. }
  51486. },
  51487. axisLabel: {
  51488. show: true,
  51489. distance: 15,
  51490. // formatter: null,
  51491. color: '#464646',
  51492. fontSize: 12
  51493. },
  51494. pointer: {
  51495. icon: null,
  51496. offsetCenter: [0, 0],
  51497. show: true,
  51498. length: '60%',
  51499. width: 6,
  51500. keepAspect: false
  51501. },
  51502. anchor: {
  51503. show: false,
  51504. showAbove: false,
  51505. size: 6,
  51506. icon: 'circle',
  51507. offsetCenter: [0, 0],
  51508. keepAspect: false,
  51509. itemStyle: {
  51510. color: '#fff',
  51511. borderWidth: 0,
  51512. borderColor: '#5470c6'
  51513. }
  51514. },
  51515. title: {
  51516. show: true,
  51517. // x, y,单位px
  51518. offsetCenter: [0, '20%'],
  51519. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  51520. color: '#464646',
  51521. fontSize: 16,
  51522. valueAnimation: false
  51523. },
  51524. detail: {
  51525. show: true,
  51526. backgroundColor: 'rgba(0,0,0,0)',
  51527. borderWidth: 0,
  51528. borderColor: '#ccc',
  51529. width: 100,
  51530. height: null,
  51531. padding: [5, 10],
  51532. // x, y,单位px
  51533. offsetCenter: [0, '40%'],
  51534. // formatter: null,
  51535. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  51536. color: '#464646',
  51537. fontSize: 30,
  51538. fontWeight: 'bold',
  51539. lineHeight: 30,
  51540. valueAnimation: false
  51541. }
  51542. };
  51543. return GaugeSeriesModel;
  51544. }(SeriesModel);
  51545. function install$e(registers) {
  51546. registers.registerChartView(GaugeView);
  51547. registers.registerSeriesModel(GaugeSeriesModel);
  51548. }
  51549. var opacityAccessPath = ['itemStyle', 'opacity'];
  51550. /**
  51551. * Piece of pie including Sector, Label, LabelLine
  51552. */
  51553. var FunnelPiece =
  51554. /** @class */
  51555. function (_super) {
  51556. __extends(FunnelPiece, _super);
  51557. function FunnelPiece(data, idx) {
  51558. var _this = _super.call(this) || this;
  51559. var polygon = _this;
  51560. var labelLine = new Polyline();
  51561. var text = new ZRText();
  51562. polygon.setTextContent(text);
  51563. _this.setTextGuideLine(labelLine);
  51564. _this.updateData(data, idx, true);
  51565. return _this;
  51566. }
  51567. FunnelPiece.prototype.updateData = function (data, idx, firstCreate) {
  51568. var polygon = this;
  51569. var seriesModel = data.hostModel;
  51570. var itemModel = data.getItemModel(idx);
  51571. var layout = data.getItemLayout(idx);
  51572. var emphasisModel = itemModel.getModel('emphasis');
  51573. var opacity = itemModel.get(opacityAccessPath);
  51574. opacity = opacity == null ? 1 : opacity; // Update common style
  51575. polygon.useStyle(data.getItemVisual(idx, 'style'));
  51576. polygon.style.lineJoin = 'round';
  51577. if (firstCreate) {
  51578. polygon.setShape({
  51579. points: layout.points
  51580. });
  51581. polygon.style.opacity = 0;
  51582. initProps(polygon, {
  51583. style: {
  51584. opacity: opacity
  51585. }
  51586. }, seriesModel, idx);
  51587. } else {
  51588. updateProps(polygon, {
  51589. style: {
  51590. opacity: opacity
  51591. },
  51592. shape: {
  51593. points: layout.points
  51594. }
  51595. }, seriesModel, idx);
  51596. }
  51597. setStatesStylesFromModel(polygon, itemModel);
  51598. this._updateLabel(data, idx);
  51599. enableHoverEmphasis(this, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  51600. };
  51601. FunnelPiece.prototype._updateLabel = function (data, idx) {
  51602. var polygon = this;
  51603. var labelLine = this.getTextGuideLine();
  51604. var labelText = polygon.getTextContent();
  51605. var seriesModel = data.hostModel;
  51606. var itemModel = data.getItemModel(idx);
  51607. var layout = data.getItemLayout(idx);
  51608. var labelLayout = layout.label;
  51609. var style = data.getItemVisual(idx, 'style');
  51610. var visualColor = style.fill;
  51611. setLabelStyle( // position will not be used in setLabelStyle
  51612. labelText, getLabelStatesModels(itemModel), {
  51613. labelFetcher: data.hostModel,
  51614. labelDataIndex: idx,
  51615. defaultOpacity: style.opacity,
  51616. defaultText: data.getName(idx)
  51617. }, {
  51618. normal: {
  51619. align: labelLayout.textAlign,
  51620. verticalAlign: labelLayout.verticalAlign
  51621. }
  51622. });
  51623. polygon.setTextConfig({
  51624. local: true,
  51625. inside: !!labelLayout.inside,
  51626. insideStroke: visualColor,
  51627. // insideFill: 'auto',
  51628. outsideFill: visualColor
  51629. });
  51630. var linePoints = labelLayout.linePoints;
  51631. labelLine.setShape({
  51632. points: linePoints
  51633. });
  51634. polygon.textGuideLineConfig = {
  51635. anchor: linePoints ? new Point(linePoints[0][0], linePoints[0][1]) : null
  51636. }; // Make sure update style on labelText after setLabelStyle.
  51637. // Because setLabelStyle will replace a new style on it.
  51638. updateProps(labelText, {
  51639. style: {
  51640. x: labelLayout.x,
  51641. y: labelLayout.y
  51642. }
  51643. }, seriesModel, idx);
  51644. labelText.attr({
  51645. rotation: labelLayout.rotation,
  51646. originX: labelLayout.x,
  51647. originY: labelLayout.y,
  51648. z2: 10
  51649. });
  51650. setLabelLineStyle(polygon, getLabelLineStatesModels(itemModel), {
  51651. // Default use item visual color
  51652. stroke: visualColor
  51653. });
  51654. };
  51655. return FunnelPiece;
  51656. }(Polygon);
  51657. var FunnelView =
  51658. /** @class */
  51659. function (_super) {
  51660. __extends(FunnelView, _super);
  51661. function FunnelView() {
  51662. var _this = _super !== null && _super.apply(this, arguments) || this;
  51663. _this.type = FunnelView.type;
  51664. _this.ignoreLabelLineUpdate = true;
  51665. return _this;
  51666. }
  51667. FunnelView.prototype.render = function (seriesModel, ecModel, api) {
  51668. var data = seriesModel.getData();
  51669. var oldData = this._data;
  51670. var group = this.group;
  51671. data.diff(oldData).add(function (idx) {
  51672. var funnelPiece = new FunnelPiece(data, idx);
  51673. data.setItemGraphicEl(idx, funnelPiece);
  51674. group.add(funnelPiece);
  51675. }).update(function (newIdx, oldIdx) {
  51676. var piece = oldData.getItemGraphicEl(oldIdx);
  51677. piece.updateData(data, newIdx);
  51678. group.add(piece);
  51679. data.setItemGraphicEl(newIdx, piece);
  51680. }).remove(function (idx) {
  51681. var piece = oldData.getItemGraphicEl(idx);
  51682. removeElementWithFadeOut(piece, seriesModel, idx);
  51683. }).execute();
  51684. this._data = data;
  51685. };
  51686. FunnelView.prototype.remove = function () {
  51687. this.group.removeAll();
  51688. this._data = null;
  51689. };
  51690. FunnelView.prototype.dispose = function () {};
  51691. FunnelView.type = 'funnel';
  51692. return FunnelView;
  51693. }(ChartView);
  51694. var FunnelSeriesModel =
  51695. /** @class */
  51696. function (_super) {
  51697. __extends(FunnelSeriesModel, _super);
  51698. function FunnelSeriesModel() {
  51699. var _this = _super !== null && _super.apply(this, arguments) || this;
  51700. _this.type = FunnelSeriesModel.type;
  51701. _this.useColorPaletteOnData = true;
  51702. return _this;
  51703. }
  51704. FunnelSeriesModel.prototype.init = function (option) {
  51705. _super.prototype.init.apply(this, arguments); // Enable legend selection for each data item
  51706. // Use a function instead of direct access because data reference may changed
  51707. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  51708. this._defaultLabelLine(option);
  51709. };
  51710. FunnelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  51711. return createListSimply(this, {
  51712. coordDimensions: ['value'],
  51713. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  51714. });
  51715. };
  51716. FunnelSeriesModel.prototype._defaultLabelLine = function (option) {
  51717. // Extend labelLine emphasis
  51718. defaultEmphasis(option, 'labelLine', ['show']);
  51719. var labelLineNormalOpt = option.labelLine;
  51720. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  51721. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  51722. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  51723. }; // Overwrite
  51724. FunnelSeriesModel.prototype.getDataParams = function (dataIndex) {
  51725. var data = this.getData();
  51726. var params = _super.prototype.getDataParams.call(this, dataIndex);
  51727. var valueDim = data.mapDimension('value');
  51728. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  51729. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  51730. params.$vars.push('percent');
  51731. return params;
  51732. };
  51733. FunnelSeriesModel.type = 'series.funnel';
  51734. FunnelSeriesModel.defaultOption = {
  51735. zlevel: 0,
  51736. z: 2,
  51737. legendHoverLink: true,
  51738. left: 80,
  51739. top: 60,
  51740. right: 80,
  51741. bottom: 60,
  51742. // width: {totalWidth} - left - right,
  51743. // height: {totalHeight} - top - bottom,
  51744. // 默认取数据最小最大值
  51745. // min: 0,
  51746. // max: 100,
  51747. minSize: '0%',
  51748. maxSize: '100%',
  51749. sort: 'descending',
  51750. orient: 'vertical',
  51751. gap: 0,
  51752. funnelAlign: 'center',
  51753. label: {
  51754. show: true,
  51755. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  51756. },
  51757. labelLine: {
  51758. show: true,
  51759. length: 20,
  51760. lineStyle: {
  51761. // color: 各异,
  51762. width: 1
  51763. }
  51764. },
  51765. itemStyle: {
  51766. // color: 各异,
  51767. borderColor: '#fff',
  51768. borderWidth: 1
  51769. },
  51770. emphasis: {
  51771. label: {
  51772. show: true
  51773. }
  51774. },
  51775. select: {
  51776. itemStyle: {
  51777. borderColor: '#212121'
  51778. }
  51779. }
  51780. };
  51781. return FunnelSeriesModel;
  51782. }(SeriesModel);
  51783. function getViewRect$3(seriesModel, api) {
  51784. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  51785. width: api.getWidth(),
  51786. height: api.getHeight()
  51787. });
  51788. }
  51789. function getSortedIndices(data, sort) {
  51790. var valueDim = data.mapDimension('value');
  51791. var valueArr = data.mapArray(valueDim, function (val) {
  51792. return val;
  51793. });
  51794. var indices = [];
  51795. var isAscending = sort === 'ascending';
  51796. for (var i = 0, len = data.count(); i < len; i++) {
  51797. indices[i] = i;
  51798. } // Add custom sortable function & none sortable opetion by "options.sort"
  51799. if (typeof sort === 'function') {
  51800. indices.sort(sort);
  51801. } else if (sort !== 'none') {
  51802. indices.sort(function (a, b) {
  51803. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  51804. });
  51805. }
  51806. return indices;
  51807. }
  51808. function labelLayout(data) {
  51809. var seriesModel = data.hostModel;
  51810. var orient = seriesModel.get('orient');
  51811. data.each(function (idx) {
  51812. var itemModel = data.getItemModel(idx);
  51813. var labelModel = itemModel.getModel('label');
  51814. var labelPosition = labelModel.get('position');
  51815. var labelLineModel = itemModel.getModel('labelLine');
  51816. var layout = data.getItemLayout(idx);
  51817. var points = layout.points;
  51818. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  51819. var textAlign;
  51820. var textX;
  51821. var textY;
  51822. var linePoints;
  51823. if (isLabelInside) {
  51824. if (labelPosition === 'insideLeft') {
  51825. textX = (points[0][0] + points[3][0]) / 2 + 5;
  51826. textY = (points[0][1] + points[3][1]) / 2;
  51827. textAlign = 'left';
  51828. } else if (labelPosition === 'insideRight') {
  51829. textX = (points[1][0] + points[2][0]) / 2 - 5;
  51830. textY = (points[1][1] + points[2][1]) / 2;
  51831. textAlign = 'right';
  51832. } else {
  51833. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  51834. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  51835. textAlign = 'center';
  51836. }
  51837. linePoints = [[textX, textY], [textX, textY]];
  51838. } else {
  51839. var x1 = void 0;
  51840. var y1 = void 0;
  51841. var x2 = void 0;
  51842. var y2 = void 0;
  51843. var labelLineLen = labelLineModel.get('length');
  51844. if ("development" !== 'production') {
  51845. if (orient === 'vertical' && ['top', 'bottom'].indexOf(labelPosition) > -1) {
  51846. labelPosition = 'left';
  51847. console.warn('Position error: Funnel chart on vertical orient dose not support top and bottom.');
  51848. }
  51849. if (orient === 'horizontal' && ['left', 'right'].indexOf(labelPosition) > -1) {
  51850. labelPosition = 'bottom';
  51851. console.warn('Position error: Funnel chart on horizontal orient dose not support left and right.');
  51852. }
  51853. }
  51854. if (labelPosition === 'left') {
  51855. // Left side
  51856. x1 = (points[3][0] + points[0][0]) / 2;
  51857. y1 = (points[3][1] + points[0][1]) / 2;
  51858. x2 = x1 - labelLineLen;
  51859. textX = x2 - 5;
  51860. textAlign = 'right';
  51861. } else if (labelPosition === 'right') {
  51862. // Right side
  51863. x1 = (points[1][0] + points[2][0]) / 2;
  51864. y1 = (points[1][1] + points[2][1]) / 2;
  51865. x2 = x1 + labelLineLen;
  51866. textX = x2 + 5;
  51867. textAlign = 'left';
  51868. } else if (labelPosition === 'top') {
  51869. // Top side
  51870. x1 = (points[3][0] + points[0][0]) / 2;
  51871. y1 = (points[3][1] + points[0][1]) / 2;
  51872. y2 = y1 - labelLineLen;
  51873. textY = y2 - 5;
  51874. textAlign = 'center';
  51875. } else if (labelPosition === 'bottom') {
  51876. // Bottom side
  51877. x1 = (points[1][0] + points[2][0]) / 2;
  51878. y1 = (points[1][1] + points[2][1]) / 2;
  51879. y2 = y1 + labelLineLen;
  51880. textY = y2 + 5;
  51881. textAlign = 'center';
  51882. } else if (labelPosition === 'rightTop') {
  51883. // RightTop side
  51884. x1 = orient === 'horizontal' ? points[3][0] : points[1][0];
  51885. y1 = orient === 'horizontal' ? points[3][1] : points[1][1];
  51886. if (orient === 'horizontal') {
  51887. y2 = y1 - labelLineLen;
  51888. textY = y2 - 5;
  51889. textAlign = 'center';
  51890. } else {
  51891. x2 = x1 + labelLineLen;
  51892. textX = x2 + 5;
  51893. textAlign = 'top';
  51894. }
  51895. } else if (labelPosition === 'rightBottom') {
  51896. // RightBottom side
  51897. x1 = points[2][0];
  51898. y1 = points[2][1];
  51899. if (orient === 'horizontal') {
  51900. y2 = y1 + labelLineLen;
  51901. textY = y2 + 5;
  51902. textAlign = 'center';
  51903. } else {
  51904. x2 = x1 + labelLineLen;
  51905. textX = x2 + 5;
  51906. textAlign = 'bottom';
  51907. }
  51908. } else if (labelPosition === 'leftTop') {
  51909. // LeftTop side
  51910. x1 = points[0][0];
  51911. y1 = orient === 'horizontal' ? points[0][1] : points[1][1];
  51912. if (orient === 'horizontal') {
  51913. y2 = y1 - labelLineLen;
  51914. textY = y2 - 5;
  51915. textAlign = 'center';
  51916. } else {
  51917. x2 = x1 - labelLineLen;
  51918. textX = x2 - 5;
  51919. textAlign = 'right';
  51920. }
  51921. } else if (labelPosition === 'leftBottom') {
  51922. // LeftBottom side
  51923. x1 = orient === 'horizontal' ? points[1][0] : points[3][0];
  51924. y1 = orient === 'horizontal' ? points[1][1] : points[2][1];
  51925. if (orient === 'horizontal') {
  51926. y2 = y1 + labelLineLen;
  51927. textY = y2 + 5;
  51928. textAlign = 'center';
  51929. } else {
  51930. x2 = x1 - labelLineLen;
  51931. textX = x2 - 5;
  51932. textAlign = 'right';
  51933. }
  51934. } else {
  51935. // Right side or Bottom side
  51936. x1 = (points[1][0] + points[2][0]) / 2;
  51937. y1 = (points[1][1] + points[2][1]) / 2;
  51938. if (orient === 'horizontal') {
  51939. y2 = y1 + labelLineLen;
  51940. textY = y2 + 5;
  51941. textAlign = 'center';
  51942. } else {
  51943. x2 = x1 + labelLineLen;
  51944. textX = x2 + 5;
  51945. textAlign = 'left';
  51946. }
  51947. }
  51948. if (orient === 'horizontal') {
  51949. x2 = x1;
  51950. textX = x2;
  51951. } else {
  51952. y2 = y1;
  51953. textY = y2;
  51954. }
  51955. linePoints = [[x1, y1], [x2, y2]];
  51956. }
  51957. layout.label = {
  51958. linePoints: linePoints,
  51959. x: textX,
  51960. y: textY,
  51961. verticalAlign: 'middle',
  51962. textAlign: textAlign,
  51963. inside: isLabelInside
  51964. };
  51965. });
  51966. }
  51967. function funnelLayout(ecModel, api) {
  51968. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  51969. var data = seriesModel.getData();
  51970. var valueDim = data.mapDimension('value');
  51971. var sort = seriesModel.get('sort');
  51972. var viewRect = getViewRect$3(seriesModel, api);
  51973. var orient = seriesModel.get('orient');
  51974. var viewWidth = viewRect.width;
  51975. var viewHeight = viewRect.height;
  51976. var indices = getSortedIndices(data, sort);
  51977. var x = viewRect.x;
  51978. var y = viewRect.y;
  51979. 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)];
  51980. var dataExtent = data.getDataExtent(valueDim);
  51981. var min = seriesModel.get('min');
  51982. var max = seriesModel.get('max');
  51983. if (min == null) {
  51984. min = Math.min(dataExtent[0], 0);
  51985. }
  51986. if (max == null) {
  51987. max = dataExtent[1];
  51988. }
  51989. var funnelAlign = seriesModel.get('funnelAlign');
  51990. var gap = seriesModel.get('gap');
  51991. var viewSize = orient === 'horizontal' ? viewWidth : viewHeight;
  51992. var itemSize = (viewSize - gap * (data.count() - 1)) / data.count();
  51993. var getLinePoints = function (idx, offset) {
  51994. // End point index is data.count() and we assign it 0
  51995. if (orient === 'horizontal') {
  51996. var val_1 = data.get(valueDim, idx) || 0;
  51997. var itemHeight = linearMap(val_1, [min, max], sizeExtent, true);
  51998. var y0 = void 0;
  51999. switch (funnelAlign) {
  52000. case 'top':
  52001. y0 = y;
  52002. break;
  52003. case 'center':
  52004. y0 = y + (viewHeight - itemHeight) / 2;
  52005. break;
  52006. case 'bottom':
  52007. y0 = y + (viewHeight - itemHeight);
  52008. break;
  52009. }
  52010. return [[offset, y0], [offset, y0 + itemHeight]];
  52011. }
  52012. var val = data.get(valueDim, idx) || 0;
  52013. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  52014. var x0;
  52015. switch (funnelAlign) {
  52016. case 'left':
  52017. x0 = x;
  52018. break;
  52019. case 'center':
  52020. x0 = x + (viewWidth - itemWidth) / 2;
  52021. break;
  52022. case 'right':
  52023. x0 = x + viewWidth - itemWidth;
  52024. break;
  52025. }
  52026. return [[x0, offset], [x0 + itemWidth, offset]];
  52027. };
  52028. if (sort === 'ascending') {
  52029. // From bottom to top
  52030. itemSize = -itemSize;
  52031. gap = -gap;
  52032. if (orient === 'horizontal') {
  52033. x += viewWidth;
  52034. } else {
  52035. y += viewHeight;
  52036. }
  52037. indices = indices.reverse();
  52038. }
  52039. for (var i = 0; i < indices.length; i++) {
  52040. var idx = indices[i];
  52041. var nextIdx = indices[i + 1];
  52042. var itemModel = data.getItemModel(idx);
  52043. if (orient === 'horizontal') {
  52044. var width = itemModel.get(['itemStyle', 'width']);
  52045. if (width == null) {
  52046. width = itemSize;
  52047. } else {
  52048. width = parsePercent$1(width, viewWidth);
  52049. if (sort === 'ascending') {
  52050. width = -width;
  52051. }
  52052. }
  52053. var start = getLinePoints(idx, x);
  52054. var end = getLinePoints(nextIdx, x + width);
  52055. x += width + gap;
  52056. data.setItemLayout(idx, {
  52057. points: start.concat(end.slice().reverse())
  52058. });
  52059. } else {
  52060. var height = itemModel.get(['itemStyle', 'height']);
  52061. if (height == null) {
  52062. height = itemSize;
  52063. } else {
  52064. height = parsePercent$1(height, viewHeight);
  52065. if (sort === 'ascending') {
  52066. height = -height;
  52067. }
  52068. }
  52069. var start = getLinePoints(idx, y);
  52070. var end = getLinePoints(nextIdx, y + height);
  52071. y += height + gap;
  52072. data.setItemLayout(idx, {
  52073. points: start.concat(end.slice().reverse())
  52074. });
  52075. }
  52076. }
  52077. labelLayout(data);
  52078. });
  52079. }
  52080. function install$f(registers) {
  52081. registers.registerChartView(FunnelView);
  52082. registers.registerSeriesModel(FunnelSeriesModel);
  52083. registers.registerLayout(funnelLayout);
  52084. registers.registerProcessor(dataFilter('funnel'));
  52085. }
  52086. var DEFAULT_SMOOTH = 0.3;
  52087. var ParallelView =
  52088. /** @class */
  52089. function (_super) {
  52090. __extends(ParallelView, _super);
  52091. function ParallelView() {
  52092. var _this = _super !== null && _super.apply(this, arguments) || this;
  52093. _this.type = ParallelView.type;
  52094. _this._dataGroup = new Group();
  52095. _this._initialized = false;
  52096. return _this;
  52097. }
  52098. ParallelView.prototype.init = function () {
  52099. this.group.add(this._dataGroup);
  52100. };
  52101. /**
  52102. * @override
  52103. */
  52104. ParallelView.prototype.render = function (seriesModel, ecModel, api, payload) {
  52105. var dataGroup = this._dataGroup;
  52106. var data = seriesModel.getData();
  52107. var oldData = this._data;
  52108. var coordSys = seriesModel.coordinateSystem;
  52109. var dimensions = coordSys.dimensions;
  52110. var seriesScope = makeSeriesScope$2(seriesModel);
  52111. data.diff(oldData).add(add).update(update).remove(remove).execute();
  52112. function add(newDataIndex) {
  52113. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  52114. updateElCommon(line, data, newDataIndex, seriesScope);
  52115. }
  52116. function update(newDataIndex, oldDataIndex) {
  52117. var line = oldData.getItemGraphicEl(oldDataIndex);
  52118. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  52119. data.setItemGraphicEl(newDataIndex, line);
  52120. updateProps(line, {
  52121. shape: {
  52122. points: points
  52123. }
  52124. }, seriesModel, newDataIndex);
  52125. updateElCommon(line, data, newDataIndex, seriesScope);
  52126. }
  52127. function remove(oldDataIndex) {
  52128. var line = oldData.getItemGraphicEl(oldDataIndex);
  52129. dataGroup.remove(line);
  52130. } // First create
  52131. if (!this._initialized) {
  52132. this._initialized = true;
  52133. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  52134. // Callback will be invoked immediately if there is no animation
  52135. setTimeout(function () {
  52136. dataGroup.removeClipPath();
  52137. });
  52138. });
  52139. dataGroup.setClipPath(clipPath);
  52140. }
  52141. this._data = data;
  52142. };
  52143. ParallelView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  52144. this._initialized = true;
  52145. this._data = null;
  52146. this._dataGroup.removeAll();
  52147. };
  52148. ParallelView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  52149. var data = seriesModel.getData();
  52150. var coordSys = seriesModel.coordinateSystem;
  52151. var dimensions = coordSys.dimensions;
  52152. var seriesScope = makeSeriesScope$2(seriesModel);
  52153. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  52154. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  52155. line.incremental = true;
  52156. updateElCommon(line, data, dataIndex, seriesScope);
  52157. }
  52158. };
  52159. ParallelView.prototype.remove = function () {
  52160. this._dataGroup && this._dataGroup.removeAll();
  52161. this._data = null;
  52162. };
  52163. ParallelView.type = 'parallel';
  52164. return ParallelView;
  52165. }(ChartView);
  52166. function createGridClipShape(coordSys, seriesModel, cb) {
  52167. var parallelModel = coordSys.model;
  52168. var rect = coordSys.getRect();
  52169. var rectEl = new Rect({
  52170. shape: {
  52171. x: rect.x,
  52172. y: rect.y,
  52173. width: rect.width,
  52174. height: rect.height
  52175. }
  52176. });
  52177. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  52178. rectEl.setShape(dim, 0);
  52179. initProps(rectEl, {
  52180. shape: {
  52181. width: rect.width,
  52182. height: rect.height
  52183. }
  52184. }, seriesModel, cb);
  52185. return rectEl;
  52186. }
  52187. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  52188. var points = [];
  52189. for (var i = 0; i < dimensions.length; i++) {
  52190. var dimName = dimensions[i];
  52191. var value = data.get(data.mapDimension(dimName), dataIndex);
  52192. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  52193. points.push(coordSys.dataToPoint(value, dimName));
  52194. }
  52195. }
  52196. return points;
  52197. }
  52198. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  52199. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  52200. var line = new Polyline({
  52201. shape: {
  52202. points: points
  52203. },
  52204. // silent: true,
  52205. z2: 10
  52206. });
  52207. dataGroup.add(line);
  52208. data.setItemGraphicEl(dataIndex, line);
  52209. return line;
  52210. }
  52211. function makeSeriesScope$2(seriesModel) {
  52212. var smooth = seriesModel.get('smooth', true);
  52213. smooth === true && (smooth = DEFAULT_SMOOTH);
  52214. smooth = numericToNumber(smooth);
  52215. eqNaN(smooth) && (smooth = 0);
  52216. return {
  52217. smooth: smooth
  52218. };
  52219. }
  52220. function updateElCommon(el, data, dataIndex, seriesScope) {
  52221. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  52222. el.style.fill = null;
  52223. el.setShape('smooth', seriesScope.smooth);
  52224. var itemModel = data.getItemModel(dataIndex);
  52225. var emphasisModel = itemModel.getModel('emphasis');
  52226. setStatesStylesFromModel(el, itemModel, 'lineStyle');
  52227. enableHoverEmphasis(el, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  52228. } // function simpleDiff(oldData, newData, dimensions) {
  52229. // let oldLen;
  52230. // if (!oldData
  52231. // || !oldData.__plProgressive
  52232. // || (oldLen = oldData.count()) !== newData.count()
  52233. // ) {
  52234. // return true;
  52235. // }
  52236. // let dimLen = dimensions.length;
  52237. // for (let i = 0; i < oldLen; i++) {
  52238. // for (let j = 0; j < dimLen; j++) {
  52239. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  52240. // return true;
  52241. // }
  52242. // }
  52243. // }
  52244. // return false;
  52245. // }
  52246. // FIXME put in common util?
  52247. function isEmptyValue(val, axisType) {
  52248. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  52249. }
  52250. var ParallelSeriesModel =
  52251. /** @class */
  52252. function (_super) {
  52253. __extends(ParallelSeriesModel, _super);
  52254. function ParallelSeriesModel() {
  52255. var _this = _super !== null && _super.apply(this, arguments) || this;
  52256. _this.type = ParallelSeriesModel.type;
  52257. _this.visualStyleAccessPath = 'lineStyle';
  52258. _this.visualDrawType = 'stroke';
  52259. return _this;
  52260. }
  52261. ParallelSeriesModel.prototype.getInitialData = function (option, ecModel) {
  52262. return createListFromArray(this.getSource(), this, {
  52263. useEncodeDefaulter: bind(makeDefaultEncode, null, this)
  52264. });
  52265. };
  52266. /**
  52267. * User can get data raw indices on 'axisAreaSelected' event received.
  52268. *
  52269. * @return Raw indices
  52270. */
  52271. ParallelSeriesModel.prototype.getRawIndicesByActiveState = function (activeState) {
  52272. var coordSys = this.coordinateSystem;
  52273. var data = this.getData();
  52274. var indices = [];
  52275. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  52276. if (activeState === theActiveState) {
  52277. indices.push(data.getRawIndex(dataIndex));
  52278. }
  52279. });
  52280. return indices;
  52281. };
  52282. ParallelSeriesModel.type = 'series.parallel';
  52283. ParallelSeriesModel.dependencies = ['parallel'];
  52284. ParallelSeriesModel.defaultOption = {
  52285. zlevel: 0,
  52286. z: 2,
  52287. coordinateSystem: 'parallel',
  52288. parallelIndex: 0,
  52289. label: {
  52290. show: false
  52291. },
  52292. inactiveOpacity: 0.05,
  52293. activeOpacity: 1,
  52294. lineStyle: {
  52295. width: 1,
  52296. opacity: 0.45,
  52297. type: 'solid'
  52298. },
  52299. emphasis: {
  52300. label: {
  52301. show: false
  52302. }
  52303. },
  52304. progressive: 500,
  52305. smooth: false,
  52306. animationEasing: 'linear'
  52307. };
  52308. return ParallelSeriesModel;
  52309. }(SeriesModel);
  52310. function makeDefaultEncode(seriesModel) {
  52311. // The mapping of parallelAxis dimension to data dimension can
  52312. // be specified in parallelAxis.option.dim. For example, if
  52313. // parallelAxis.option.dim is 'dim3', it mapping to the third
  52314. // dimension of data. But `data.encode` has higher priority.
  52315. // Moreover, parallelModel.dimension should not be regarded as data
  52316. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  52317. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  52318. if (!parallelModel) {
  52319. return;
  52320. }
  52321. var encodeDefine = {};
  52322. each(parallelModel.dimensions, function (axisDim) {
  52323. var dataDimIndex = convertDimNameToNumber(axisDim);
  52324. encodeDefine[axisDim] = dataDimIndex;
  52325. });
  52326. return encodeDefine;
  52327. }
  52328. function convertDimNameToNumber(dimName) {
  52329. return +dimName.replace('dim', '');
  52330. }
  52331. /*
  52332. * Licensed to the Apache Software Foundation (ASF) under one
  52333. * or more contributor license agreements. See the NOTICE file
  52334. * distributed with this work for additional information
  52335. * regarding copyright ownership. The ASF licenses this file
  52336. * to you under the Apache License, Version 2.0 (the
  52337. * "License"); you may not use this file except in compliance
  52338. * with the License. You may obtain a copy of the License at
  52339. *
  52340. * http://www.apache.org/licenses/LICENSE-2.0
  52341. *
  52342. * Unless required by applicable law or agreed to in writing,
  52343. * software distributed under the License is distributed on an
  52344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52345. * KIND, either express or implied. See the License for the
  52346. * specific language governing permissions and limitations
  52347. * under the License.
  52348. */
  52349. /**
  52350. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52351. */
  52352. /*
  52353. * Licensed to the Apache Software Foundation (ASF) under one
  52354. * or more contributor license agreements. See the NOTICE file
  52355. * distributed with this work for additional information
  52356. * regarding copyright ownership. The ASF licenses this file
  52357. * to you under the Apache License, Version 2.0 (the
  52358. * "License"); you may not use this file except in compliance
  52359. * with the License. You may obtain a copy of the License at
  52360. *
  52361. * http://www.apache.org/licenses/LICENSE-2.0
  52362. *
  52363. * Unless required by applicable law or agreed to in writing,
  52364. * software distributed under the License is distributed on an
  52365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52366. * KIND, either express or implied. See the License for the
  52367. * specific language governing permissions and limitations
  52368. * under the License.
  52369. */
  52370. var opacityAccessPath$1 = ['lineStyle', 'opacity'];
  52371. var parallelVisual = {
  52372. seriesType: 'parallel',
  52373. reset: function (seriesModel, ecModel) {
  52374. var coordSys = seriesModel.coordinateSystem;
  52375. var opacityMap = {
  52376. normal: seriesModel.get(['lineStyle', 'opacity']),
  52377. active: seriesModel.get('activeOpacity'),
  52378. inactive: seriesModel.get('inactiveOpacity')
  52379. };
  52380. return {
  52381. progress: function (params, data) {
  52382. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  52383. var opacity = opacityMap[activeState];
  52384. if (activeState === 'normal' && data.hasItemOption) {
  52385. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  52386. itemOpacity != null && (opacity = itemOpacity);
  52387. }
  52388. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  52389. existsStyle.opacity = opacity;
  52390. }, params.start, params.end);
  52391. }
  52392. };
  52393. }
  52394. };
  52395. function parallelPreprocessor(option) {
  52396. createParallelIfNeeded(option);
  52397. mergeAxisOptionFromParallel(option);
  52398. }
  52399. /**
  52400. * Create a parallel coordinate if not exists.
  52401. * @inner
  52402. */
  52403. function createParallelIfNeeded(option) {
  52404. if (option.parallel) {
  52405. return;
  52406. }
  52407. var hasParallelSeries = false;
  52408. each(option.series, function (seriesOpt) {
  52409. if (seriesOpt && seriesOpt.type === 'parallel') {
  52410. hasParallelSeries = true;
  52411. }
  52412. });
  52413. if (hasParallelSeries) {
  52414. option.parallel = [{}];
  52415. }
  52416. }
  52417. /**
  52418. * Merge aixs definition from parallel option (if exists) to axis option.
  52419. * @inner
  52420. */
  52421. function mergeAxisOptionFromParallel(option) {
  52422. var axes = normalizeToArray(option.parallelAxis);
  52423. each(axes, function (axisOption) {
  52424. if (!isObject(axisOption)) {
  52425. return;
  52426. }
  52427. var parallelIndex = axisOption.parallelIndex || 0;
  52428. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  52429. if (parallelOption && parallelOption.parallelAxisDefault) {
  52430. merge(axisOption, parallelOption.parallelAxisDefault, false);
  52431. }
  52432. });
  52433. }
  52434. var CLICK_THRESHOLD = 5; // > 4
  52435. var ParallelView$1 =
  52436. /** @class */
  52437. function (_super) {
  52438. __extends(ParallelView, _super);
  52439. function ParallelView() {
  52440. var _this = _super !== null && _super.apply(this, arguments) || this;
  52441. _this.type = ParallelView.type;
  52442. return _this;
  52443. }
  52444. ParallelView.prototype.render = function (parallelModel, ecModel, api) {
  52445. this._model = parallelModel;
  52446. this._api = api;
  52447. if (!this._handlers) {
  52448. this._handlers = {};
  52449. each(handlers, function (handler, eventName) {
  52450. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  52451. }, this);
  52452. }
  52453. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  52454. };
  52455. ParallelView.prototype.dispose = function (ecModel, api) {
  52456. each(this._handlers, function (handler, eventName) {
  52457. api.getZr().off(eventName, handler);
  52458. });
  52459. this._handlers = null;
  52460. };
  52461. /**
  52462. * @internal
  52463. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  52464. */
  52465. ParallelView.prototype._throttledDispatchExpand = function (opt) {
  52466. this._dispatchExpand(opt);
  52467. };
  52468. /**
  52469. * @internal
  52470. */
  52471. ParallelView.prototype._dispatchExpand = function (opt) {
  52472. opt && this._api.dispatchAction(extend({
  52473. type: 'parallelAxisExpand'
  52474. }, opt));
  52475. };
  52476. ParallelView.type = 'parallel';
  52477. return ParallelView;
  52478. }(ComponentView);
  52479. var handlers = {
  52480. mousedown: function (e) {
  52481. if (checkTrigger(this, 'click')) {
  52482. this._mouseDownPoint = [e.offsetX, e.offsetY];
  52483. }
  52484. },
  52485. mouseup: function (e) {
  52486. var mouseDownPoint = this._mouseDownPoint;
  52487. if (checkTrigger(this, 'click') && mouseDownPoint) {
  52488. var point = [e.offsetX, e.offsetY];
  52489. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  52490. if (dist > CLICK_THRESHOLD) {
  52491. return;
  52492. }
  52493. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  52494. result.behavior !== 'none' && this._dispatchExpand({
  52495. axisExpandWindow: result.axisExpandWindow
  52496. });
  52497. }
  52498. this._mouseDownPoint = null;
  52499. },
  52500. mousemove: function (e) {
  52501. // Should do nothing when brushing.
  52502. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  52503. return;
  52504. }
  52505. var model = this._model;
  52506. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  52507. var behavior = result.behavior;
  52508. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  52509. this._throttledDispatchExpand(behavior === 'none' ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  52510. : {
  52511. axisExpandWindow: result.axisExpandWindow,
  52512. // Jumping uses animation, and sliding suppresses animation.
  52513. animation: behavior === 'jump' ? null : {
  52514. duration: 0 // Disable animation.
  52515. }
  52516. });
  52517. }
  52518. };
  52519. function checkTrigger(view, triggerOn) {
  52520. var model = view._model;
  52521. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  52522. }
  52523. var ParallelModel =
  52524. /** @class */
  52525. function (_super) {
  52526. __extends(ParallelModel, _super);
  52527. function ParallelModel() {
  52528. var _this = _super !== null && _super.apply(this, arguments) || this;
  52529. _this.type = ParallelModel.type;
  52530. return _this;
  52531. }
  52532. ParallelModel.prototype.init = function () {
  52533. _super.prototype.init.apply(this, arguments);
  52534. this.mergeOption({});
  52535. };
  52536. ParallelModel.prototype.mergeOption = function (newOption) {
  52537. var thisOption = this.option;
  52538. newOption && merge(thisOption, newOption, true);
  52539. this._initDimensions();
  52540. };
  52541. /**
  52542. * Whether series or axis is in this coordinate system.
  52543. */
  52544. ParallelModel.prototype.contains = function (model, ecModel) {
  52545. var parallelIndex = model.get('parallelIndex');
  52546. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  52547. };
  52548. ParallelModel.prototype.setAxisExpand = function (opt) {
  52549. each(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  52550. if (opt.hasOwnProperty(name)) {
  52551. // @ts-ignore FIXME: why "never" inferred in this.option[name]?
  52552. this.option[name] = opt[name];
  52553. }
  52554. }, this);
  52555. };
  52556. ParallelModel.prototype._initDimensions = function () {
  52557. var dimensions = this.dimensions = [];
  52558. var parallelAxisIndex = this.parallelAxisIndex = [];
  52559. var axisModels = filter(this.ecModel.queryComponents({
  52560. mainType: 'parallelAxis'
  52561. }), function (axisModel) {
  52562. // Can not use this.contains here, because
  52563. // initialization has not been completed yet.
  52564. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  52565. }, this);
  52566. each(axisModels, function (axisModel) {
  52567. dimensions.push('dim' + axisModel.get('dim'));
  52568. parallelAxisIndex.push(axisModel.componentIndex);
  52569. });
  52570. };
  52571. ParallelModel.type = 'parallel';
  52572. ParallelModel.dependencies = ['parallelAxis'];
  52573. ParallelModel.layoutMode = 'box';
  52574. ParallelModel.defaultOption = {
  52575. zlevel: 0,
  52576. z: 0,
  52577. left: 80,
  52578. top: 60,
  52579. right: 80,
  52580. bottom: 60,
  52581. // width: {totalWidth} - left - right,
  52582. // height: {totalHeight} - top - bottom,
  52583. layout: 'horizontal',
  52584. // FIXME
  52585. // naming?
  52586. axisExpandable: false,
  52587. axisExpandCenter: null,
  52588. axisExpandCount: 0,
  52589. axisExpandWidth: 50,
  52590. axisExpandRate: 17,
  52591. axisExpandDebounce: 50,
  52592. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  52593. // Do not doc to user until necessary.
  52594. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  52595. axisExpandTriggerOn: 'click',
  52596. parallelAxisDefault: null
  52597. };
  52598. return ParallelModel;
  52599. }(ComponentModel);
  52600. var ParallelAxis =
  52601. /** @class */
  52602. function (_super) {
  52603. __extends(ParallelAxis, _super);
  52604. function ParallelAxis(dim, scale, coordExtent, axisType, axisIndex) {
  52605. var _this = _super.call(this, dim, scale, coordExtent) || this;
  52606. _this.type = axisType || 'value';
  52607. _this.axisIndex = axisIndex;
  52608. return _this;
  52609. }
  52610. ParallelAxis.prototype.isHorizontal = function () {
  52611. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  52612. };
  52613. return ParallelAxis;
  52614. }(Axis);
  52615. /*
  52616. * Licensed to the Apache Software Foundation (ASF) under one
  52617. * or more contributor license agreements. See the NOTICE file
  52618. * distributed with this work for additional information
  52619. * regarding copyright ownership. The ASF licenses this file
  52620. * to you under the Apache License, Version 2.0 (the
  52621. * "License"); you may not use this file except in compliance
  52622. * with the License. You may obtain a copy of the License at
  52623. *
  52624. * http://www.apache.org/licenses/LICENSE-2.0
  52625. *
  52626. * Unless required by applicable law or agreed to in writing,
  52627. * software distributed under the License is distributed on an
  52628. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52629. * KIND, either express or implied. See the License for the
  52630. * specific language governing permissions and limitations
  52631. * under the License.
  52632. */
  52633. /**
  52634. * AUTO-GENERATED FILE. DO NOT MODIFY.
  52635. */
  52636. /*
  52637. * Licensed to the Apache Software Foundation (ASF) under one
  52638. * or more contributor license agreements. See the NOTICE file
  52639. * distributed with this work for additional information
  52640. * regarding copyright ownership. The ASF licenses this file
  52641. * to you under the Apache License, Version 2.0 (the
  52642. * "License"); you may not use this file except in compliance
  52643. * with the License. You may obtain a copy of the License at
  52644. *
  52645. * http://www.apache.org/licenses/LICENSE-2.0
  52646. *
  52647. * Unless required by applicable law or agreed to in writing,
  52648. * software distributed under the License is distributed on an
  52649. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52650. * KIND, either express or implied. See the License for the
  52651. * specific language governing permissions and limitations
  52652. * under the License.
  52653. */
  52654. /**
  52655. * Calculate slider move result.
  52656. * Usage:
  52657. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  52658. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  52659. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  52660. *
  52661. * @param delta Move length.
  52662. * @param handleEnds handleEnds[0] can be bigger then handleEnds[1].
  52663. * handleEnds will be modified in this method.
  52664. * @param extent handleEnds is restricted by extent.
  52665. * extent[0] should less or equals than extent[1].
  52666. * @param handleIndex Can be 'all', means that both move the two handleEnds.
  52667. * @param minSpan The range of dataZoom can not be smaller than that.
  52668. * If not set, handle0 and cross handle1. If set as a non-negative
  52669. * number (including `0`), handles will push each other when reaching
  52670. * the minSpan.
  52671. * @param maxSpan The range of dataZoom can not be larger than that.
  52672. * @return The input handleEnds.
  52673. */
  52674. function sliderMove(delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  52675. delta = delta || 0;
  52676. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  52677. if (minSpan != null) {
  52678. minSpan = restrict(minSpan, [0, extentSpan]);
  52679. }
  52680. if (maxSpan != null) {
  52681. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  52682. }
  52683. if (handleIndex === 'all') {
  52684. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  52685. handleSpan = restrict(handleSpan, [0, extentSpan]);
  52686. minSpan = maxSpan = restrict(handleSpan, [minSpan, maxSpan]);
  52687. handleIndex = 0;
  52688. }
  52689. handleEnds[0] = restrict(handleEnds[0], extent);
  52690. handleEnds[1] = restrict(handleEnds[1], extent);
  52691. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  52692. handleEnds[handleIndex] += delta; // Restrict in extent.
  52693. var extentMinSpan = minSpan || 0;
  52694. var realExtent = extent.slice();
  52695. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  52696. handleEnds[handleIndex] = restrict(handleEnds[handleIndex], realExtent); // Expand span.
  52697. var currDistSign;
  52698. currDistSign = getSpanSign(handleEnds, handleIndex);
  52699. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  52700. // If minSpan exists, 'cross' is forbidden.
  52701. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  52702. } // Shrink span.
  52703. currDistSign = getSpanSign(handleEnds, handleIndex);
  52704. if (maxSpan != null && currDistSign.span > maxSpan) {
  52705. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  52706. }
  52707. return handleEnds;
  52708. }
  52709. function getSpanSign(handleEnds, handleIndex) {
  52710. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  52711. // is at left of handleEnds[1] for non-cross case.
  52712. return {
  52713. span: Math.abs(dist),
  52714. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  52715. };
  52716. }
  52717. function restrict(value, extend) {
  52718. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  52719. }
  52720. var each$6 = each;
  52721. var mathMin$8 = Math.min;
  52722. var mathMax$8 = Math.max;
  52723. var mathFloor$2 = Math.floor;
  52724. var mathCeil$1 = Math.ceil;
  52725. var round$2 = round;
  52726. var PI$7 = Math.PI;
  52727. var Parallel =
  52728. /** @class */
  52729. function () {
  52730. function Parallel(parallelModel, ecModel, api) {
  52731. this.type = 'parallel';
  52732. /**
  52733. * key: dimension
  52734. */
  52735. this._axesMap = createHashMap();
  52736. /**
  52737. * key: dimension
  52738. * value: {position: [], rotation, }
  52739. */
  52740. this._axesLayout = {};
  52741. this.dimensions = parallelModel.dimensions;
  52742. this._model = parallelModel;
  52743. this._init(parallelModel, ecModel, api);
  52744. }
  52745. Parallel.prototype._init = function (parallelModel, ecModel, api) {
  52746. var dimensions = parallelModel.dimensions;
  52747. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  52748. each$6(dimensions, function (dim, idx) {
  52749. var axisIndex = parallelAxisIndex[idx];
  52750. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  52751. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  52752. var isCategory = axis.type === 'category';
  52753. axis.onBand = isCategory && axisModel.get('boundaryGap');
  52754. axis.inverse = axisModel.get('inverse'); // Injection
  52755. axisModel.axis = axis;
  52756. axis.model = axisModel;
  52757. axis.coordinateSystem = axisModel.coordinateSystem = this;
  52758. }, this);
  52759. };
  52760. /**
  52761. * Update axis scale after data processed
  52762. */
  52763. Parallel.prototype.update = function (ecModel, api) {
  52764. this._updateAxesFromSeries(this._model, ecModel);
  52765. };
  52766. Parallel.prototype.containPoint = function (point) {
  52767. var layoutInfo = this._makeLayoutInfo();
  52768. var axisBase = layoutInfo.axisBase;
  52769. var layoutBase = layoutInfo.layoutBase;
  52770. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52771. var pAxis = point[1 - pixelDimIndex];
  52772. var pLayout = point[pixelDimIndex];
  52773. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  52774. };
  52775. Parallel.prototype.getModel = function () {
  52776. return this._model;
  52777. };
  52778. /**
  52779. * Update properties from series
  52780. */
  52781. Parallel.prototype._updateAxesFromSeries = function (parallelModel, ecModel) {
  52782. ecModel.eachSeries(function (seriesModel) {
  52783. if (!parallelModel.contains(seriesModel, ecModel)) {
  52784. return;
  52785. }
  52786. var data = seriesModel.getData();
  52787. each$6(this.dimensions, function (dim) {
  52788. var axis = this._axesMap.get(dim);
  52789. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  52790. niceScaleExtent(axis.scale, axis.model);
  52791. }, this);
  52792. }, this);
  52793. };
  52794. /**
  52795. * Resize the parallel coordinate system.
  52796. */
  52797. Parallel.prototype.resize = function (parallelModel, api) {
  52798. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  52799. width: api.getWidth(),
  52800. height: api.getHeight()
  52801. });
  52802. this._layoutAxes();
  52803. };
  52804. Parallel.prototype.getRect = function () {
  52805. return this._rect;
  52806. };
  52807. Parallel.prototype._makeLayoutInfo = function () {
  52808. var parallelModel = this._model;
  52809. var rect = this._rect;
  52810. var xy = ['x', 'y'];
  52811. var wh = ['width', 'height'];
  52812. var layout = parallelModel.get('layout');
  52813. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  52814. var layoutLength = rect[wh[pixelDimIndex]];
  52815. var layoutExtent = [0, layoutLength];
  52816. var axisCount = this.dimensions.length;
  52817. var axisExpandWidth = restrict$1(parallelModel.get('axisExpandWidth'), layoutExtent);
  52818. var axisExpandCount = restrict$1(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  52819. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  52820. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  52821. // where collapsed axes should be overlapped.
  52822. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  52823. var winSize;
  52824. if (!axisExpandWindow) {
  52825. winSize = restrict$1(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  52826. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  52827. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  52828. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52829. } else {
  52830. winSize = restrict$1(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  52831. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  52832. }
  52833. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  52834. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  52835. var winInnerIndices = [mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$1(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  52836. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  52837. return {
  52838. layout: layout,
  52839. pixelDimIndex: pixelDimIndex,
  52840. layoutBase: rect[xy[pixelDimIndex]],
  52841. layoutLength: layoutLength,
  52842. axisBase: rect[xy[1 - pixelDimIndex]],
  52843. axisLength: rect[wh[1 - pixelDimIndex]],
  52844. axisExpandable: axisExpandable,
  52845. axisExpandWidth: axisExpandWidth,
  52846. axisCollapseWidth: axisCollapseWidth,
  52847. axisExpandWindow: axisExpandWindow,
  52848. axisCount: axisCount,
  52849. winInnerIndices: winInnerIndices,
  52850. axisExpandWindow0Pos: axisExpandWindow0Pos
  52851. };
  52852. };
  52853. Parallel.prototype._layoutAxes = function () {
  52854. var rect = this._rect;
  52855. var axes = this._axesMap;
  52856. var dimensions = this.dimensions;
  52857. var layoutInfo = this._makeLayoutInfo();
  52858. var layout = layoutInfo.layout;
  52859. axes.each(function (axis) {
  52860. var axisExtent = [0, layoutInfo.axisLength];
  52861. var idx = axis.inverse ? 1 : 0;
  52862. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  52863. });
  52864. each$6(dimensions, function (dim, idx) {
  52865. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  52866. var positionTable = {
  52867. horizontal: {
  52868. x: posInfo.position,
  52869. y: layoutInfo.axisLength
  52870. },
  52871. vertical: {
  52872. x: 0,
  52873. y: posInfo.position
  52874. }
  52875. };
  52876. var rotationTable = {
  52877. horizontal: PI$7 / 2,
  52878. vertical: 0
  52879. };
  52880. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  52881. var rotation = rotationTable[layout];
  52882. var transform = create$1();
  52883. rotate(transform, transform, rotation);
  52884. translate(transform, transform, position); // TODO
  52885. // tick layout info
  52886. // TODO
  52887. // update dimensions info based on axis order.
  52888. this._axesLayout[dim] = {
  52889. position: position,
  52890. rotation: rotation,
  52891. transform: transform,
  52892. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  52893. axisLabelShow: posInfo.axisLabelShow,
  52894. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  52895. tickDirection: 1,
  52896. labelDirection: 1
  52897. };
  52898. }, this);
  52899. };
  52900. /**
  52901. * Get axis by dim.
  52902. */
  52903. Parallel.prototype.getAxis = function (dim) {
  52904. return this._axesMap.get(dim);
  52905. };
  52906. /**
  52907. * Convert a dim value of a single item of series data to Point.
  52908. */
  52909. Parallel.prototype.dataToPoint = function (value, dim) {
  52910. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  52911. };
  52912. /**
  52913. * Travel data for one time, get activeState of each data item.
  52914. * @param start the start dataIndex that travel from.
  52915. * @param end the next dataIndex of the last dataIndex will be travel.
  52916. */
  52917. Parallel.prototype.eachActiveState = function (data, callback, start, end) {
  52918. start == null && (start = 0);
  52919. end == null && (end = data.count());
  52920. var axesMap = this._axesMap;
  52921. var dimensions = this.dimensions;
  52922. var dataDimensions = [];
  52923. var axisModels = [];
  52924. each(dimensions, function (axisDim) {
  52925. dataDimensions.push(data.mapDimension(axisDim));
  52926. axisModels.push(axesMap.get(axisDim).model);
  52927. });
  52928. var hasActiveSet = this.hasAxisBrushed();
  52929. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  52930. var activeState = void 0;
  52931. if (!hasActiveSet) {
  52932. activeState = 'normal';
  52933. } else {
  52934. activeState = 'active';
  52935. var values = data.getValues(dataDimensions, dataIndex);
  52936. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52937. var state = axisModels[j].getActiveState(values[j]);
  52938. if (state === 'inactive') {
  52939. activeState = 'inactive';
  52940. break;
  52941. }
  52942. }
  52943. }
  52944. callback(activeState, dataIndex);
  52945. }
  52946. };
  52947. /**
  52948. * Whether has any activeSet.
  52949. */
  52950. Parallel.prototype.hasAxisBrushed = function () {
  52951. var dimensions = this.dimensions;
  52952. var axesMap = this._axesMap;
  52953. var hasActiveSet = false;
  52954. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  52955. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  52956. hasActiveSet = true;
  52957. }
  52958. }
  52959. return hasActiveSet;
  52960. };
  52961. /**
  52962. * Convert coords of each axis to Point.
  52963. * Return point. For example: [10, 20]
  52964. */
  52965. Parallel.prototype.axisCoordToPoint = function (coord, dim) {
  52966. var axisLayout = this._axesLayout[dim];
  52967. return applyTransform$1([coord, 0], axisLayout.transform);
  52968. };
  52969. /**
  52970. * Get axis layout.
  52971. */
  52972. Parallel.prototype.getAxisLayout = function (dim) {
  52973. return clone(this._axesLayout[dim]);
  52974. };
  52975. /**
  52976. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  52977. */
  52978. Parallel.prototype.getSlidedAxisExpandWindow = function (point) {
  52979. var layoutInfo = this._makeLayoutInfo();
  52980. var pixelDimIndex = layoutInfo.pixelDimIndex;
  52981. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  52982. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  52983. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  52984. if (!this.containPoint(point)) {
  52985. return {
  52986. behavior: 'none',
  52987. axisExpandWindow: axisExpandWindow
  52988. };
  52989. } // Conver the point from global to expand coordinates.
  52990. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  52991. // slided when mouse is the center area of the window.
  52992. var delta;
  52993. var behavior = 'slide';
  52994. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  52995. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  52996. var useJump = triggerArea[0] != null;
  52997. if (axisCollapseWidth) {
  52998. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  52999. behavior = 'jump';
  53000. delta = pointCoord - winSize * triggerArea[2];
  53001. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  53002. behavior = 'jump';
  53003. delta = pointCoord - winSize * (1 - triggerArea[2]);
  53004. } else {
  53005. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  53006. }
  53007. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  53008. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  53009. : behavior = 'none';
  53010. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  53011. else {
  53012. var winSize2 = axisExpandWindow[1] - axisExpandWindow[0];
  53013. var pos = extent[1] * pointCoord / winSize2;
  53014. axisExpandWindow = [mathMax$8(0, pos - winSize2 / 2)];
  53015. axisExpandWindow[1] = mathMin$8(extent[1], axisExpandWindow[0] + winSize2);
  53016. axisExpandWindow[0] = axisExpandWindow[1] - winSize2;
  53017. }
  53018. return {
  53019. axisExpandWindow: axisExpandWindow,
  53020. behavior: behavior
  53021. };
  53022. };
  53023. return Parallel;
  53024. }();
  53025. function restrict$1(len, extent) {
  53026. return mathMin$8(mathMax$8(len, extent[0]), extent[1]);
  53027. }
  53028. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  53029. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  53030. return {
  53031. position: step * axisIndex,
  53032. axisNameAvailableWidth: step,
  53033. axisLabelShow: true
  53034. };
  53035. }
  53036. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  53037. var layoutLength = layoutInfo.layoutLength;
  53038. var axisExpandWidth = layoutInfo.axisExpandWidth;
  53039. var axisCount = layoutInfo.axisCount;
  53040. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  53041. var winInnerIndices = layoutInfo.winInnerIndices;
  53042. var position;
  53043. var axisNameAvailableWidth = axisCollapseWidth;
  53044. var axisLabelShow = false;
  53045. var nameTruncateMaxWidth;
  53046. if (axisIndex < winInnerIndices[0]) {
  53047. position = axisIndex * axisCollapseWidth;
  53048. nameTruncateMaxWidth = axisCollapseWidth;
  53049. } else if (axisIndex <= winInnerIndices[1]) {
  53050. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  53051. axisNameAvailableWidth = axisExpandWidth;
  53052. axisLabelShow = true;
  53053. } else {
  53054. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  53055. nameTruncateMaxWidth = axisCollapseWidth;
  53056. }
  53057. return {
  53058. position: position,
  53059. axisNameAvailableWidth: axisNameAvailableWidth,
  53060. axisLabelShow: axisLabelShow,
  53061. nameTruncateMaxWidth: nameTruncateMaxWidth
  53062. };
  53063. }
  53064. function createParallelCoordSys(ecModel, api) {
  53065. var coordSysList = [];
  53066. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  53067. var coordSys = new Parallel(parallelModel, ecModel, api);
  53068. coordSys.name = 'parallel_' + idx;
  53069. coordSys.resize(parallelModel, api);
  53070. parallelModel.coordinateSystem = coordSys;
  53071. coordSys.model = parallelModel;
  53072. coordSysList.push(coordSys);
  53073. }); // Inject the coordinateSystems into seriesModel
  53074. ecModel.eachSeries(function (seriesModel) {
  53075. if (seriesModel.get('coordinateSystem') === 'parallel') {
  53076. var parallelModel = seriesModel.getReferringComponents('parallel', SINGLE_REFERRING).models[0];
  53077. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  53078. }
  53079. });
  53080. return coordSysList;
  53081. }
  53082. var parallelCoordSysCreator = {
  53083. create: createParallelCoordSys
  53084. };
  53085. var ParallelAxisModel =
  53086. /** @class */
  53087. function (_super) {
  53088. __extends(ParallelAxisModel, _super);
  53089. function ParallelAxisModel() {
  53090. var _this = _super !== null && _super.apply(this, arguments) || this;
  53091. _this.type = ParallelAxisModel.type;
  53092. /**
  53093. * @readOnly
  53094. */
  53095. _this.activeIntervals = [];
  53096. return _this;
  53097. }
  53098. ParallelAxisModel.prototype.getAreaSelectStyle = function () {
  53099. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
  53100. // So do not transfer decal directly.
  53101. ])(this.getModel('areaSelectStyle'));
  53102. };
  53103. /**
  53104. * The code of this feature is put on AxisModel but not ParallelAxis,
  53105. * because axisModel can be alive after echarts updating but instance of
  53106. * ParallelAxis having been disposed. this._activeInterval should be kept
  53107. * when action dispatched (i.e. legend click).
  53108. *
  53109. * @param intervals `interval.length === 0` means set all active.
  53110. */
  53111. ParallelAxisModel.prototype.setActiveIntervals = function (intervals) {
  53112. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  53113. if (activeIntervals) {
  53114. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  53115. asc(activeIntervals[i]);
  53116. }
  53117. }
  53118. };
  53119. /**
  53120. * @param value When only attempting detect whether 'no activeIntervals set',
  53121. * `value` is not needed to be input.
  53122. */
  53123. ParallelAxisModel.prototype.getActiveState = function (value) {
  53124. var activeIntervals = this.activeIntervals;
  53125. if (!activeIntervals.length) {
  53126. return 'normal';
  53127. }
  53128. if (value == null || isNaN(+value)) {
  53129. return 'inactive';
  53130. } // Simple optimization
  53131. if (activeIntervals.length === 1) {
  53132. var interval = activeIntervals[0];
  53133. if (interval[0] <= value && value <= interval[1]) {
  53134. return 'active';
  53135. }
  53136. } else {
  53137. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  53138. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  53139. return 'active';
  53140. }
  53141. }
  53142. }
  53143. return 'inactive';
  53144. };
  53145. return ParallelAxisModel;
  53146. }(ComponentModel);
  53147. mixin(ParallelAxisModel, AxisModelCommonMixin);
  53148. var BRUSH_PANEL_GLOBAL = true;
  53149. var mathMin$9 = Math.min;
  53150. var mathMax$9 = Math.max;
  53151. var mathPow$2 = Math.pow;
  53152. var COVER_Z = 10000;
  53153. var UNSELECT_THRESHOLD = 6;
  53154. var MIN_RESIZE_LINE_WIDTH = 6;
  53155. var MUTEX_RESOURCE_KEY = 'globalPan';
  53156. var DIRECTION_MAP = {
  53157. w: [0, 0],
  53158. e: [0, 1],
  53159. n: [1, 0],
  53160. s: [1, 1]
  53161. };
  53162. var CURSOR_MAP = {
  53163. w: 'ew',
  53164. e: 'ew',
  53165. n: 'ns',
  53166. s: 'ns',
  53167. ne: 'nesw',
  53168. sw: 'nesw',
  53169. nw: 'nwse',
  53170. se: 'nwse'
  53171. };
  53172. var DEFAULT_BRUSH_OPT = {
  53173. brushStyle: {
  53174. lineWidth: 2,
  53175. stroke: 'rgba(210,219,238,0.3)',
  53176. fill: '#D2DBEE'
  53177. },
  53178. transformable: true,
  53179. brushMode: 'single',
  53180. removeOnClick: false
  53181. };
  53182. var baseUID = 0;
  53183. /**
  53184. * params:
  53185. * areas: Array.<Array>, coord relates to container group,
  53186. * If no container specified, to global.
  53187. * opt {
  53188. * isEnd: boolean,
  53189. * removeOnClick: boolean
  53190. * }
  53191. */
  53192. var BrushController =
  53193. /** @class */
  53194. function (_super) {
  53195. __extends(BrushController, _super);
  53196. function BrushController(zr) {
  53197. var _this = _super.call(this) || this;
  53198. /**
  53199. * @internal
  53200. */
  53201. _this._track = [];
  53202. /**
  53203. * @internal
  53204. */
  53205. _this._covers = [];
  53206. _this._handlers = {};
  53207. if ("development" !== 'production') {
  53208. assert(zr);
  53209. }
  53210. _this._zr = zr;
  53211. _this.group = new Group();
  53212. _this._uid = 'brushController_' + baseUID++;
  53213. each(pointerHandlers, function (handler, eventName) {
  53214. this._handlers[eventName] = bind(handler, this);
  53215. }, _this);
  53216. return _this;
  53217. }
  53218. /**
  53219. * If set to `false`, select disabled.
  53220. */
  53221. BrushController.prototype.enableBrush = function (brushOption) {
  53222. if ("development" !== 'production') {
  53223. assert(this._mounted);
  53224. }
  53225. this._brushType && this._doDisableBrush();
  53226. brushOption.brushType && this._doEnableBrush(brushOption);
  53227. return this;
  53228. };
  53229. BrushController.prototype._doEnableBrush = function (brushOption) {
  53230. var zr = this._zr; // Consider roam, which takes globalPan too.
  53231. if (!this._enableGlobalPan) {
  53232. take(zr, MUTEX_RESOURCE_KEY, this._uid);
  53233. }
  53234. each(this._handlers, function (handler, eventName) {
  53235. zr.on(eventName, handler);
  53236. });
  53237. this._brushType = brushOption.brushType;
  53238. this._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  53239. };
  53240. BrushController.prototype._doDisableBrush = function () {
  53241. var zr = this._zr;
  53242. release(zr, MUTEX_RESOURCE_KEY, this._uid);
  53243. each(this._handlers, function (handler, eventName) {
  53244. zr.off(eventName, handler);
  53245. });
  53246. this._brushType = this._brushOption = null;
  53247. };
  53248. /**
  53249. * @param panelOpts If not pass, it is global brush.
  53250. */
  53251. BrushController.prototype.setPanels = function (panelOpts) {
  53252. if (panelOpts && panelOpts.length) {
  53253. var panels_1 = this._panels = {};
  53254. each(panelOpts, function (panelOpts) {
  53255. panels_1[panelOpts.panelId] = clone(panelOpts);
  53256. });
  53257. } else {
  53258. this._panels = null;
  53259. }
  53260. return this;
  53261. };
  53262. BrushController.prototype.mount = function (opt) {
  53263. opt = opt || {};
  53264. if ("development" !== 'production') {
  53265. this._mounted = true; // should be at first.
  53266. }
  53267. this._enableGlobalPan = opt.enableGlobalPan;
  53268. var thisGroup = this.group;
  53269. this._zr.add(thisGroup);
  53270. thisGroup.attr({
  53271. x: opt.x || 0,
  53272. y: opt.y || 0,
  53273. rotation: opt.rotation || 0,
  53274. scaleX: opt.scaleX || 1,
  53275. scaleY: opt.scaleY || 1
  53276. });
  53277. this._transform = thisGroup.getLocalTransform();
  53278. return this;
  53279. }; // eachCover(cb, context): void {
  53280. // each(this._covers, cb, context);
  53281. // }
  53282. /**
  53283. * Update covers.
  53284. * @param coverConfigList
  53285. * If coverConfigList is null/undefined, all covers removed.
  53286. */
  53287. BrushController.prototype.updateCovers = function (coverConfigList) {
  53288. if ("development" !== 'production') {
  53289. assert(this._mounted);
  53290. }
  53291. coverConfigList = map(coverConfigList, function (coverConfig) {
  53292. return merge(clone(DEFAULT_BRUSH_OPT), coverConfig, true);
  53293. });
  53294. var tmpIdPrefix = '\0-brush-index-';
  53295. var oldCovers = this._covers;
  53296. var newCovers = this._covers = [];
  53297. var controller = this;
  53298. var creatingCover = this._creatingCover;
  53299. new DataDiffer(oldCovers, coverConfigList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  53300. return this;
  53301. function getKey(brushOption, index) {
  53302. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  53303. }
  53304. function oldGetKey(cover, index) {
  53305. return getKey(cover.__brushOption, index);
  53306. }
  53307. function addOrUpdate(newIndex, oldIndex) {
  53308. var newBrushInternal = coverConfigList[newIndex]; // Consider setOption in event listener of brushSelect,
  53309. // where updating cover when creating should be forbiden.
  53310. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  53311. newCovers[newIndex] = oldCovers[oldIndex];
  53312. } else {
  53313. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushInternal, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushInternal));
  53314. updateCoverAfterCreation(controller, cover);
  53315. }
  53316. }
  53317. function remove(oldIndex) {
  53318. if (oldCovers[oldIndex] !== creatingCover) {
  53319. controller.group.remove(oldCovers[oldIndex]);
  53320. }
  53321. }
  53322. };
  53323. BrushController.prototype.unmount = function () {
  53324. if ("development" !== 'production') {
  53325. if (!this._mounted) {
  53326. return;
  53327. }
  53328. }
  53329. this.enableBrush(false); // container may 'removeAll' outside.
  53330. clearCovers(this);
  53331. this._zr.remove(this.group);
  53332. if ("development" !== 'production') {
  53333. this._mounted = false; // should be at last.
  53334. }
  53335. return this;
  53336. };
  53337. BrushController.prototype.dispose = function () {
  53338. this.unmount();
  53339. this.off();
  53340. };
  53341. return BrushController;
  53342. }(Eventful);
  53343. function createCover(controller, brushOption) {
  53344. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  53345. cover.__brushOption = brushOption;
  53346. updateZ(cover, brushOption);
  53347. controller.group.add(cover);
  53348. return cover;
  53349. }
  53350. function endCreating(controller, creatingCover) {
  53351. var coverRenderer = getCoverRenderer(creatingCover);
  53352. if (coverRenderer.endCreating) {
  53353. coverRenderer.endCreating(controller, creatingCover);
  53354. updateZ(creatingCover, creatingCover.__brushOption);
  53355. }
  53356. return creatingCover;
  53357. }
  53358. function updateCoverShape(controller, cover) {
  53359. var brushOption = cover.__brushOption;
  53360. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  53361. }
  53362. function updateZ(cover, brushOption) {
  53363. var z = brushOption.z;
  53364. z == null && (z = COVER_Z);
  53365. cover.traverse(function (el) {
  53366. el.z = z;
  53367. el.z2 = z; // Consider in given container.
  53368. });
  53369. }
  53370. function updateCoverAfterCreation(controller, cover) {
  53371. getCoverRenderer(cover).updateCommon(controller, cover);
  53372. updateCoverShape(controller, cover);
  53373. }
  53374. function getCoverRenderer(cover) {
  53375. return coverRenderers[cover.__brushOption.brushType];
  53376. } // return target panel or `true` (means global panel)
  53377. function getPanelByPoint(controller, e, localCursorPoint) {
  53378. var panels = controller._panels;
  53379. if (!panels) {
  53380. return BRUSH_PANEL_GLOBAL; // Global panel
  53381. }
  53382. var panel;
  53383. var transform = controller._transform;
  53384. each(panels, function (pn) {
  53385. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  53386. });
  53387. return panel;
  53388. } // Return a panel or true
  53389. function getPanelByCover(controller, cover) {
  53390. var panels = controller._panels;
  53391. if (!panels) {
  53392. return BRUSH_PANEL_GLOBAL; // Global panel
  53393. }
  53394. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  53395. // which is then treated as global panel.
  53396. return panelId != null ? panels[panelId] : BRUSH_PANEL_GLOBAL;
  53397. }
  53398. function clearCovers(controller) {
  53399. var covers = controller._covers;
  53400. var originalLength = covers.length;
  53401. each(covers, function (cover) {
  53402. controller.group.remove(cover);
  53403. }, controller);
  53404. covers.length = 0;
  53405. return !!originalLength;
  53406. }
  53407. function trigger$1(controller, opt) {
  53408. var areas = map(controller._covers, function (cover) {
  53409. var brushOption = cover.__brushOption;
  53410. var range = clone(brushOption.range);
  53411. return {
  53412. brushType: brushOption.brushType,
  53413. panelId: brushOption.panelId,
  53414. range: range
  53415. };
  53416. });
  53417. controller.trigger('brush', {
  53418. areas: areas,
  53419. isEnd: !!opt.isEnd,
  53420. removeOnClick: !!opt.removeOnClick
  53421. });
  53422. }
  53423. function shouldShowCover(controller) {
  53424. var track = controller._track;
  53425. if (!track.length) {
  53426. return false;
  53427. }
  53428. var p2 = track[track.length - 1];
  53429. var p1 = track[0];
  53430. var dx = p2[0] - p1[0];
  53431. var dy = p2[1] - p1[1];
  53432. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  53433. return dist > UNSELECT_THRESHOLD;
  53434. }
  53435. function getTrackEnds(track) {
  53436. var tail = track.length - 1;
  53437. tail < 0 && (tail = 0);
  53438. return [track[0], track[tail]];
  53439. }
  53440. function createBaseRectCover(rectRangeConverter, controller, brushOption, edgeNameSequences) {
  53441. var cover = new Group();
  53442. cover.add(new Rect({
  53443. name: 'main',
  53444. style: makeStyle(brushOption),
  53445. silent: true,
  53446. draggable: true,
  53447. cursor: 'move',
  53448. drift: curry(driftRect, rectRangeConverter, controller, cover, ['n', 's', 'w', 'e']),
  53449. ondragend: curry(trigger$1, controller, {
  53450. isEnd: true
  53451. })
  53452. }));
  53453. each(edgeNameSequences, function (nameSequence) {
  53454. cover.add(new Rect({
  53455. name: nameSequence.join(''),
  53456. style: {
  53457. opacity: 0
  53458. },
  53459. draggable: true,
  53460. silent: true,
  53461. invisible: true,
  53462. drift: curry(driftRect, rectRangeConverter, controller, cover, nameSequence),
  53463. ondragend: curry(trigger$1, controller, {
  53464. isEnd: true
  53465. })
  53466. }));
  53467. });
  53468. return cover;
  53469. }
  53470. function updateBaseRect(controller, cover, localRange, brushOption) {
  53471. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  53472. var handleSize = mathMax$9(lineWidth, MIN_RESIZE_LINE_WIDTH);
  53473. var x = localRange[0][0];
  53474. var y = localRange[1][0];
  53475. var xa = x - lineWidth / 2;
  53476. var ya = y - lineWidth / 2;
  53477. var x2 = localRange[0][1];
  53478. var y2 = localRange[1][1];
  53479. var x2a = x2 - handleSize + lineWidth / 2;
  53480. var y2a = y2 - handleSize + lineWidth / 2;
  53481. var width = x2 - x;
  53482. var height = y2 - y;
  53483. var widtha = width + lineWidth;
  53484. var heighta = height + lineWidth;
  53485. updateRectShape(controller, cover, 'main', x, y, width, height);
  53486. if (brushOption.transformable) {
  53487. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  53488. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  53489. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  53490. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  53491. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  53492. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  53493. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  53494. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  53495. }
  53496. }
  53497. function updateCommon(controller, cover) {
  53498. var brushOption = cover.__brushOption;
  53499. var transformable = brushOption.transformable;
  53500. var mainEl = cover.childAt(0);
  53501. mainEl.useStyle(makeStyle(brushOption));
  53502. mainEl.attr({
  53503. silent: !transformable,
  53504. cursor: transformable ? 'move' : 'default'
  53505. });
  53506. each([['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']], function (nameSequence) {
  53507. var el = cover.childOfName(nameSequence.join(''));
  53508. var globalDir = nameSequence.length === 1 ? getGlobalDirection1(controller, nameSequence[0]) : getGlobalDirection2(controller, nameSequence);
  53509. el && el.attr({
  53510. silent: !transformable,
  53511. invisible: !transformable,
  53512. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  53513. });
  53514. });
  53515. }
  53516. function updateRectShape(controller, cover, name, x, y, w, h) {
  53517. var el = cover.childOfName(name);
  53518. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  53519. }
  53520. function makeStyle(brushOption) {
  53521. return defaults({
  53522. strokeNoScale: true
  53523. }, brushOption.brushStyle);
  53524. }
  53525. function formatRectRange(x, y, x2, y2) {
  53526. var min = [mathMin$9(x, x2), mathMin$9(y, y2)];
  53527. var max = [mathMax$9(x, x2), mathMax$9(y, y2)];
  53528. return [[min[0], max[0]], [min[1], max[1]] // y range
  53529. ];
  53530. }
  53531. function getTransform$1(controller) {
  53532. return getTransform(controller.group);
  53533. }
  53534. function getGlobalDirection1(controller, localDirName) {
  53535. var map = {
  53536. w: 'left',
  53537. e: 'right',
  53538. n: 'top',
  53539. s: 'bottom'
  53540. };
  53541. var inverseMap = {
  53542. left: 'w',
  53543. right: 'e',
  53544. top: 'n',
  53545. bottom: 's'
  53546. };
  53547. var dir = transformDirection(map[localDirName], getTransform$1(controller));
  53548. return inverseMap[dir];
  53549. }
  53550. function getGlobalDirection2(controller, localDirNameSeq) {
  53551. var globalDir = [getGlobalDirection1(controller, localDirNameSeq[0]), getGlobalDirection1(controller, localDirNameSeq[1])];
  53552. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  53553. return globalDir.join('');
  53554. }
  53555. function driftRect(rectRangeConverter, controller, cover, dirNameSequence, dx, dy) {
  53556. var brushOption = cover.__brushOption;
  53557. var rectRange = rectRangeConverter.toRectRange(brushOption.range);
  53558. var localDelta = toLocalDelta(controller, dx, dy);
  53559. each(dirNameSequence, function (dirName) {
  53560. var ind = DIRECTION_MAP[dirName];
  53561. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  53562. });
  53563. brushOption.range = rectRangeConverter.fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  53564. updateCoverAfterCreation(controller, cover);
  53565. trigger$1(controller, {
  53566. isEnd: false
  53567. });
  53568. }
  53569. function driftPolygon(controller, cover, dx, dy) {
  53570. var range = cover.__brushOption.range;
  53571. var localDelta = toLocalDelta(controller, dx, dy);
  53572. each(range, function (point) {
  53573. point[0] += localDelta[0];
  53574. point[1] += localDelta[1];
  53575. });
  53576. updateCoverAfterCreation(controller, cover);
  53577. trigger$1(controller, {
  53578. isEnd: false
  53579. });
  53580. }
  53581. function toLocalDelta(controller, dx, dy) {
  53582. var thisGroup = controller.group;
  53583. var localD = thisGroup.transformCoordToLocal(dx, dy);
  53584. var localZero = thisGroup.transformCoordToLocal(0, 0);
  53585. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  53586. }
  53587. function clipByPanel(controller, cover, data) {
  53588. var panel = getPanelByCover(controller, cover);
  53589. return panel && panel !== BRUSH_PANEL_GLOBAL ? panel.clipPath(data, controller._transform) : clone(data);
  53590. }
  53591. function pointsToRect(points) {
  53592. var xmin = mathMin$9(points[0][0], points[1][0]);
  53593. var ymin = mathMin$9(points[0][1], points[1][1]);
  53594. var xmax = mathMax$9(points[0][0], points[1][0]);
  53595. var ymax = mathMax$9(points[0][1], points[1][1]);
  53596. return {
  53597. x: xmin,
  53598. y: ymin,
  53599. width: xmax - xmin,
  53600. height: ymax - ymin
  53601. };
  53602. }
  53603. function resetCursor(controller, e, localCursorPoint) {
  53604. if ( // Check active
  53605. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  53606. // but not called when mouse is out of zr area to avoid bad influence
  53607. // if `mousemove`, `mouseup` are triggered from `document` event.
  53608. || isOutsideZrArea(controller, e.offsetX, e.offsetY)) {
  53609. return;
  53610. }
  53611. var zr = controller._zr;
  53612. var covers = controller._covers;
  53613. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  53614. if (!controller._dragging) {
  53615. for (var i = 0; i < covers.length; i++) {
  53616. var brushOption = covers[i].__brushOption;
  53617. if (currPanel && (currPanel === BRUSH_PANEL_GLOBAL || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  53618. // Use cursor style set on cover.
  53619. return;
  53620. }
  53621. }
  53622. }
  53623. currPanel && zr.setCursorStyle('crosshair');
  53624. }
  53625. function preventDefault(e) {
  53626. var rawE = e.event;
  53627. rawE.preventDefault && rawE.preventDefault();
  53628. }
  53629. function mainShapeContain(cover, x, y) {
  53630. return cover.childOfName('main').contain(x, y);
  53631. }
  53632. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  53633. var creatingCover = controller._creatingCover;
  53634. var panel = controller._creatingPanel;
  53635. var thisBrushOption = controller._brushOption;
  53636. var eventParams;
  53637. controller._track.push(localCursorPoint.slice());
  53638. if (shouldShowCover(controller) || creatingCover) {
  53639. if (panel && !creatingCover) {
  53640. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  53641. var brushOption = clone(thisBrushOption);
  53642. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  53643. brushOption.panelId = panel === BRUSH_PANEL_GLOBAL ? null : panel.panelId;
  53644. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  53645. controller._covers.push(creatingCover);
  53646. }
  53647. if (creatingCover) {
  53648. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  53649. var coverBrushOption = creatingCover.__brushOption;
  53650. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  53651. if (isEnd) {
  53652. endCreating(controller, creatingCover);
  53653. coverRenderer.updateCommon(controller, creatingCover);
  53654. }
  53655. updateCoverShape(controller, creatingCover);
  53656. eventParams = {
  53657. isEnd: isEnd
  53658. };
  53659. }
  53660. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  53661. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  53662. // But a single click do not clear covers, because user may have casual
  53663. // clicks (for example, click on other component and do not expect covers
  53664. // disappear).
  53665. // Only some cover removed, trigger action, but not every click trigger action.
  53666. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  53667. eventParams = {
  53668. isEnd: isEnd,
  53669. removeOnClick: true
  53670. };
  53671. }
  53672. }
  53673. return eventParams;
  53674. }
  53675. function determineBrushType(brushType, panel) {
  53676. if (brushType === 'auto') {
  53677. if ("development" !== 'production') {
  53678. assert(panel && panel.defaultBrushType, 'MUST have defaultBrushType when brushType is "atuo"');
  53679. }
  53680. return panel.defaultBrushType;
  53681. }
  53682. return brushType;
  53683. }
  53684. var pointerHandlers = {
  53685. mousedown: function (e) {
  53686. if (this._dragging) {
  53687. // In case some browser do not support globalOut,
  53688. // and release mouse out side the browser.
  53689. handleDragEnd(this, e);
  53690. } else if (!e.target || !e.target.draggable) {
  53691. preventDefault(e);
  53692. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  53693. this._creatingCover = null;
  53694. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  53695. if (panel) {
  53696. this._dragging = true;
  53697. this._track = [localCursorPoint.slice()];
  53698. }
  53699. }
  53700. },
  53701. mousemove: function (e) {
  53702. var x = e.offsetX;
  53703. var y = e.offsetY;
  53704. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  53705. resetCursor(this, e, localCursorPoint);
  53706. if (this._dragging) {
  53707. preventDefault(e);
  53708. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  53709. eventParams && trigger$1(this, eventParams);
  53710. }
  53711. },
  53712. mouseup: function (e) {
  53713. handleDragEnd(this, e);
  53714. }
  53715. };
  53716. function handleDragEnd(controller, e) {
  53717. if (controller._dragging) {
  53718. preventDefault(e);
  53719. var x = e.offsetX;
  53720. var y = e.offsetY;
  53721. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  53722. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  53723. controller._dragging = false;
  53724. controller._track = [];
  53725. controller._creatingCover = null; // trigger event shoule be at final, after procedure will be nested.
  53726. eventParams && trigger$1(controller, eventParams);
  53727. }
  53728. }
  53729. function isOutsideZrArea(controller, x, y) {
  53730. var zr = controller._zr;
  53731. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  53732. }
  53733. /**
  53734. * key: brushType
  53735. */
  53736. var coverRenderers = {
  53737. lineX: getLineRenderer(0),
  53738. lineY: getLineRenderer(1),
  53739. rect: {
  53740. createCover: function (controller, brushOption) {
  53741. function returnInput(range) {
  53742. return range;
  53743. }
  53744. return createBaseRectCover({
  53745. toRectRange: returnInput,
  53746. fromRectRange: returnInput
  53747. }, controller, brushOption, [['w'], ['e'], ['n'], ['s'], ['s', 'e'], ['s', 'w'], ['n', 'e'], ['n', 'w']]);
  53748. },
  53749. getCreatingRange: function (localTrack) {
  53750. var ends = getTrackEnds(localTrack);
  53751. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  53752. },
  53753. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53754. updateBaseRect(controller, cover, localRange, brushOption);
  53755. },
  53756. updateCommon: updateCommon,
  53757. contain: mainShapeContain
  53758. },
  53759. polygon: {
  53760. createCover: function (controller, brushOption) {
  53761. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  53762. // border of the shape when drawing, which is a better experience for user.
  53763. cover.add(new Polyline({
  53764. name: 'main',
  53765. style: makeStyle(brushOption),
  53766. silent: true
  53767. }));
  53768. return cover;
  53769. },
  53770. getCreatingRange: function (localTrack) {
  53771. return localTrack;
  53772. },
  53773. endCreating: function (controller, cover) {
  53774. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  53775. cover.add(new Polygon({
  53776. name: 'main',
  53777. draggable: true,
  53778. drift: curry(driftPolygon, controller, cover),
  53779. ondragend: curry(trigger$1, controller, {
  53780. isEnd: true
  53781. })
  53782. }));
  53783. },
  53784. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53785. cover.childAt(0).setShape({
  53786. points: clipByPanel(controller, cover, localRange)
  53787. });
  53788. },
  53789. updateCommon: updateCommon,
  53790. contain: mainShapeContain
  53791. }
  53792. };
  53793. function getLineRenderer(xyIndex) {
  53794. return {
  53795. createCover: function (controller, brushOption) {
  53796. return createBaseRectCover({
  53797. toRectRange: function (range) {
  53798. var rectRange = [range, [0, 100]];
  53799. xyIndex && rectRange.reverse();
  53800. return rectRange;
  53801. },
  53802. fromRectRange: function (rectRange) {
  53803. return rectRange[xyIndex];
  53804. }
  53805. }, controller, brushOption, [[['w'], ['e']], [['n'], ['s']]][xyIndex]);
  53806. },
  53807. getCreatingRange: function (localTrack) {
  53808. var ends = getTrackEnds(localTrack);
  53809. var min = mathMin$9(ends[0][xyIndex], ends[1][xyIndex]);
  53810. var max = mathMax$9(ends[0][xyIndex], ends[1][xyIndex]);
  53811. return [min, max];
  53812. },
  53813. updateCoverShape: function (controller, cover, localRange, brushOption) {
  53814. var otherExtent; // If brushWidth not specified, fit the panel.
  53815. var panel = getPanelByCover(controller, cover);
  53816. if (panel !== BRUSH_PANEL_GLOBAL && panel.getLinearBrushOtherExtent) {
  53817. otherExtent = panel.getLinearBrushOtherExtent(xyIndex);
  53818. } else {
  53819. var zr = controller._zr;
  53820. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  53821. }
  53822. var rectRange = [localRange, otherExtent];
  53823. xyIndex && rectRange.reverse();
  53824. updateBaseRect(controller, cover, rectRange, brushOption);
  53825. },
  53826. updateCommon: updateCommon,
  53827. contain: mainShapeContain
  53828. };
  53829. }
  53830. function makeRectPanelClipPath(rect) {
  53831. rect = normalizeRect(rect);
  53832. return function (localPoints) {
  53833. return clipPointsByRect(localPoints, rect);
  53834. };
  53835. }
  53836. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  53837. rect = normalizeRect(rect);
  53838. return function (xyIndex) {
  53839. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  53840. var brushWidth = idx ? rect.width : rect.height;
  53841. var base = idx ? rect.x : rect.y;
  53842. return [base, base + (brushWidth || 0)];
  53843. };
  53844. }
  53845. function makeRectIsTargetByCursor(rect, api, targetModel) {
  53846. var boundingRect = normalizeRect(rect);
  53847. return function (e, localCursorPoint) {
  53848. return boundingRect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  53849. };
  53850. } // Consider width/height is negative.
  53851. function normalizeRect(rect) {
  53852. return BoundingRect.create(rect);
  53853. }
  53854. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  53855. var ParallelAxisView =
  53856. /** @class */
  53857. function (_super) {
  53858. __extends(ParallelAxisView, _super);
  53859. function ParallelAxisView() {
  53860. var _this = _super !== null && _super.apply(this, arguments) || this;
  53861. _this.type = ParallelAxisView.type;
  53862. return _this;
  53863. }
  53864. ParallelAxisView.prototype.init = function (ecModel, api) {
  53865. _super.prototype.init.apply(this, arguments);
  53866. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  53867. };
  53868. ParallelAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  53869. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  53870. return;
  53871. }
  53872. this.axisModel = axisModel;
  53873. this.api = api;
  53874. this.group.removeAll();
  53875. var oldAxisGroup = this._axisGroup;
  53876. this._axisGroup = new Group();
  53877. this.group.add(this._axisGroup);
  53878. if (!axisModel.get('show')) {
  53879. return;
  53880. }
  53881. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  53882. var coordSys = coordSysModel.coordinateSystem;
  53883. var areaSelectStyle = axisModel.getAreaSelectStyle();
  53884. var areaWidth = areaSelectStyle.width;
  53885. var dim = axisModel.axis.dim;
  53886. var axisLayout = coordSys.getAxisLayout(dim);
  53887. var builderOpt = extend({
  53888. strokeContainThreshold: areaWidth
  53889. }, axisLayout);
  53890. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  53891. each(elementList, axisBuilder.add, axisBuilder);
  53892. this._axisGroup.add(axisBuilder.getGroup());
  53893. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  53894. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  53895. }; // /**
  53896. // * @override
  53897. // */
  53898. // updateVisual(axisModel, ecModel, api, payload) {
  53899. // this._brushController && this._brushController
  53900. // .updateCovers(getCoverInfoList(axisModel));
  53901. // }
  53902. ParallelAxisView.prototype._refreshBrushController = function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  53903. // After filtering, axis may change, select area needs to be update.
  53904. var extent = axisModel.axis.getExtent();
  53905. var extentLen = extent[1] - extent[0];
  53906. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  53907. // width/height might be negative, which will be
  53908. // normalized in BoundingRect.
  53909. var rect = BoundingRect.create({
  53910. x: extent[0],
  53911. y: -areaWidth / 2,
  53912. width: extentLen,
  53913. height: areaWidth
  53914. });
  53915. rect.x -= extra;
  53916. rect.width += 2 * extra;
  53917. this._brushController.mount({
  53918. enableGlobalPan: true,
  53919. rotation: builderOpt.rotation,
  53920. x: builderOpt.position[0],
  53921. y: builderOpt.position[1]
  53922. }).setPanels([{
  53923. panelId: 'pl',
  53924. clipPath: makeRectPanelClipPath(rect),
  53925. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  53926. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  53927. }]).enableBrush({
  53928. brushType: 'lineX',
  53929. brushStyle: areaSelectStyle,
  53930. removeOnClick: true
  53931. }).updateCovers(getCoverInfoList(axisModel));
  53932. };
  53933. ParallelAxisView.prototype._onBrush = function (eventParam) {
  53934. var coverInfoList = eventParam.areas; // Do not cache these object, because the mey be changed.
  53935. var axisModel = this.axisModel;
  53936. var axis = axisModel.axis;
  53937. var intervals = map(coverInfoList, function (coverInfo) {
  53938. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  53939. }); // If realtime is true, action is not dispatched on drag end, because
  53940. // the drag end emits the same params with the last drag move event,
  53941. // and may have some delay when using touch pad.
  53942. if (!axisModel.option.realtime === eventParam.isEnd || eventParam.removeOnClick) {
  53943. // jshint ignore:line
  53944. this.api.dispatchAction({
  53945. type: 'axisAreaSelect',
  53946. parallelAxisId: axisModel.id,
  53947. intervals: intervals
  53948. });
  53949. }
  53950. };
  53951. ParallelAxisView.prototype.dispose = function () {
  53952. this._brushController.dispose();
  53953. };
  53954. ParallelAxisView.type = 'parallelAxis';
  53955. return ParallelAxisView;
  53956. }(ComponentView);
  53957. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  53958. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  53959. mainType: 'parallelAxis',
  53960. query: payload
  53961. })[0] === axisModel;
  53962. }
  53963. function getCoverInfoList(axisModel) {
  53964. var axis = axisModel.axis;
  53965. return map(axisModel.activeIntervals, function (interval) {
  53966. return {
  53967. brushType: 'lineX',
  53968. panelId: 'pl',
  53969. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  53970. };
  53971. });
  53972. }
  53973. function getCoordSysModel(axisModel, ecModel) {
  53974. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  53975. }
  53976. /*
  53977. * Licensed to the Apache Software Foundation (ASF) under one
  53978. * or more contributor license agreements. See the NOTICE file
  53979. * distributed with this work for additional information
  53980. * regarding copyright ownership. The ASF licenses this file
  53981. * to you under the Apache License, Version 2.0 (the
  53982. * "License"); you may not use this file except in compliance
  53983. * with the License. You may obtain a copy of the License at
  53984. *
  53985. * http://www.apache.org/licenses/LICENSE-2.0
  53986. *
  53987. * Unless required by applicable law or agreed to in writing,
  53988. * software distributed under the License is distributed on an
  53989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53990. * KIND, either express or implied. See the License for the
  53991. * specific language governing permissions and limitations
  53992. * under the License.
  53993. */
  53994. /**
  53995. * AUTO-GENERATED FILE. DO NOT MODIFY.
  53996. */
  53997. /*
  53998. * Licensed to the Apache Software Foundation (ASF) under one
  53999. * or more contributor license agreements. See the NOTICE file
  54000. * distributed with this work for additional information
  54001. * regarding copyright ownership. The ASF licenses this file
  54002. * to you under the Apache License, Version 2.0 (the
  54003. * "License"); you may not use this file except in compliance
  54004. * with the License. You may obtain a copy of the License at
  54005. *
  54006. * http://www.apache.org/licenses/LICENSE-2.0
  54007. *
  54008. * Unless required by applicable law or agreed to in writing,
  54009. * software distributed under the License is distributed on an
  54010. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54011. * KIND, either express or implied. See the License for the
  54012. * specific language governing permissions and limitations
  54013. * under the License.
  54014. */
  54015. var actionInfo$1 = {
  54016. type: 'axisAreaSelect',
  54017. event: 'axisAreaSelected' // update: 'updateVisual'
  54018. };
  54019. function installParallelActions(registers) {
  54020. registers.registerAction(actionInfo$1, function (payload, ecModel) {
  54021. ecModel.eachComponent({
  54022. mainType: 'parallelAxis',
  54023. query: payload
  54024. }, function (parallelAxisModel) {
  54025. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  54026. });
  54027. });
  54028. /**
  54029. * @payload
  54030. */
  54031. registers.registerAction('parallelAxisExpand', function (payload, ecModel) {
  54032. ecModel.eachComponent({
  54033. mainType: 'parallel',
  54034. query: payload
  54035. }, function (parallelModel) {
  54036. parallelModel.setAxisExpand(payload);
  54037. });
  54038. });
  54039. }
  54040. var defaultAxisOption = {
  54041. type: 'value',
  54042. areaSelectStyle: {
  54043. width: 20,
  54044. borderWidth: 1,
  54045. borderColor: 'rgba(160,197,232)',
  54046. color: 'rgba(160,197,232)',
  54047. opacity: 0.3
  54048. },
  54049. realtime: true,
  54050. z: 10
  54051. };
  54052. function install$g(registers) {
  54053. registers.registerComponentView(ParallelView$1);
  54054. registers.registerComponentModel(ParallelModel);
  54055. registers.registerCoordinateSystem('parallel', parallelCoordSysCreator);
  54056. registers.registerPreprocessor(parallelPreprocessor);
  54057. registers.registerComponentModel(ParallelAxisModel);
  54058. registers.registerComponentView(ParallelAxisView);
  54059. axisModelCreator(registers, 'parallel', ParallelAxisModel, defaultAxisOption);
  54060. installParallelActions(registers);
  54061. }
  54062. function install$h(registers) {
  54063. use(install$g);
  54064. registers.registerChartView(ParallelView);
  54065. registers.registerSeriesModel(ParallelSeriesModel);
  54066. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, parallelVisual);
  54067. }
  54068. var SankeyPathShape =
  54069. /** @class */
  54070. function () {
  54071. function SankeyPathShape() {
  54072. this.x1 = 0;
  54073. this.y1 = 0;
  54074. this.x2 = 0;
  54075. this.y2 = 0;
  54076. this.cpx1 = 0;
  54077. this.cpy1 = 0;
  54078. this.cpx2 = 0;
  54079. this.cpy2 = 0;
  54080. this.extent = 0;
  54081. }
  54082. return SankeyPathShape;
  54083. }();
  54084. var SankeyPath =
  54085. /** @class */
  54086. function (_super) {
  54087. __extends(SankeyPath, _super);
  54088. function SankeyPath(opts) {
  54089. return _super.call(this, opts) || this;
  54090. }
  54091. SankeyPath.prototype.getDefaultShape = function () {
  54092. return new SankeyPathShape();
  54093. };
  54094. SankeyPath.prototype.buildPath = function (ctx, shape) {
  54095. var extent = shape.extent;
  54096. ctx.moveTo(shape.x1, shape.y1);
  54097. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  54098. if (shape.orient === 'vertical') {
  54099. ctx.lineTo(shape.x2 + extent, shape.y2);
  54100. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  54101. } else {
  54102. ctx.lineTo(shape.x2, shape.y2 + extent);
  54103. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  54104. }
  54105. ctx.closePath();
  54106. };
  54107. SankeyPath.prototype.highlight = function () {
  54108. enterEmphasis(this);
  54109. };
  54110. SankeyPath.prototype.downplay = function () {
  54111. leaveEmphasis(this);
  54112. };
  54113. return SankeyPath;
  54114. }(Path);
  54115. var SankeyView =
  54116. /** @class */
  54117. function (_super) {
  54118. __extends(SankeyView, _super);
  54119. function SankeyView() {
  54120. var _this = _super !== null && _super.apply(this, arguments) || this;
  54121. _this.type = SankeyView.type;
  54122. _this._focusAdjacencyDisabled = false;
  54123. return _this;
  54124. }
  54125. SankeyView.prototype.render = function (seriesModel, ecModel, api) {
  54126. var sankeyView = this;
  54127. var graph = seriesModel.getGraph();
  54128. var group = this.group;
  54129. var layoutInfo = seriesModel.layoutInfo; // view width
  54130. var width = layoutInfo.width; // view height
  54131. var height = layoutInfo.height;
  54132. var nodeData = seriesModel.getData();
  54133. var edgeData = seriesModel.getData('edge');
  54134. var orient = seriesModel.get('orient');
  54135. this._model = seriesModel;
  54136. group.removeAll();
  54137. group.x = layoutInfo.x;
  54138. group.y = layoutInfo.y; // generate a bezire Curve for each edge
  54139. graph.eachEdge(function (edge) {
  54140. var curve = new SankeyPath();
  54141. var ecData = getECData(curve);
  54142. ecData.dataIndex = edge.dataIndex;
  54143. ecData.seriesIndex = seriesModel.seriesIndex;
  54144. ecData.dataType = 'edge';
  54145. var edgeModel = edge.getModel();
  54146. var lineStyleModel = edgeModel.getModel('lineStyle');
  54147. var curvature = lineStyleModel.get('curveness');
  54148. var n1Layout = edge.node1.getLayout();
  54149. var node1Model = edge.node1.getModel();
  54150. var dragX1 = node1Model.get('localX');
  54151. var dragY1 = node1Model.get('localY');
  54152. var n2Layout = edge.node2.getLayout();
  54153. var node2Model = edge.node2.getModel();
  54154. var dragX2 = node2Model.get('localX');
  54155. var dragY2 = node2Model.get('localY');
  54156. var edgeLayout = edge.getLayout();
  54157. var x1;
  54158. var y1;
  54159. var x2;
  54160. var y2;
  54161. var cpx1;
  54162. var cpy1;
  54163. var cpx2;
  54164. var cpy2;
  54165. curve.shape.extent = Math.max(1, edgeLayout.dy);
  54166. curve.shape.orient = orient;
  54167. if (orient === 'vertical') {
  54168. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  54169. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  54170. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  54171. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  54172. cpx1 = x1;
  54173. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  54174. cpx2 = x2;
  54175. cpy2 = y1 * curvature + y2 * (1 - curvature);
  54176. } else {
  54177. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  54178. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  54179. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  54180. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  54181. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  54182. cpy1 = y1;
  54183. cpx2 = x1 * curvature + x2 * (1 - curvature);
  54184. cpy2 = y2;
  54185. }
  54186. curve.setShape({
  54187. x1: x1,
  54188. y1: y1,
  54189. x2: x2,
  54190. y2: y2,
  54191. cpx1: cpx1,
  54192. cpy1: cpy1,
  54193. cpx2: cpx2,
  54194. cpy2: cpy2
  54195. });
  54196. curve.useStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  54197. switch (curve.style.fill) {
  54198. case 'source':
  54199. curve.style.fill = edge.node1.getVisual('color');
  54200. curve.style.decal = edge.node1.getVisual('style').decal;
  54201. break;
  54202. case 'target':
  54203. curve.style.fill = edge.node2.getVisual('color');
  54204. curve.style.decal = edge.node2.getVisual('style').decal;
  54205. break;
  54206. case 'gradient':
  54207. var sourceColor = edge.node1.getVisual('color');
  54208. var targetColor = edge.node2.getVisual('color');
  54209. if (typeof sourceColor === 'string' && typeof targetColor === 'string') {
  54210. curve.style.fill = new LinearGradient(0, 0, 1, 0, [{
  54211. color: sourceColor,
  54212. offset: 0
  54213. }, {
  54214. color: targetColor,
  54215. offset: 1
  54216. }]);
  54217. }
  54218. }
  54219. var emphasisModel = edgeModel.getModel('emphasis');
  54220. setStatesStylesFromModel(curve, edgeModel, 'lineStyle', function (model) {
  54221. return model.getItemStyle();
  54222. });
  54223. group.add(curve);
  54224. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  54225. var focus = emphasisModel.get('focus');
  54226. enableHoverEmphasis(curve, focus === 'adjacency' ? edge.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'));
  54227. getECData(curve).dataType = 'edge';
  54228. }); // Generate a rect for each node
  54229. graph.eachNode(function (node) {
  54230. var layout = node.getLayout();
  54231. var itemModel = node.getModel();
  54232. var dragX = itemModel.get('localX');
  54233. var dragY = itemModel.get('localY');
  54234. var emphasisModel = itemModel.getModel('emphasis');
  54235. var rect = new Rect({
  54236. shape: {
  54237. x: dragX != null ? dragX * width : layout.x,
  54238. y: dragY != null ? dragY * height : layout.y,
  54239. width: layout.dx,
  54240. height: layout.dy
  54241. },
  54242. style: itemModel.getModel('itemStyle').getItemStyle()
  54243. });
  54244. setLabelStyle(rect, getLabelStatesModels(itemModel), {
  54245. labelFetcher: seriesModel,
  54246. labelDataIndex: node.dataIndex,
  54247. defaultText: node.id
  54248. });
  54249. rect.disableLabelAnimation = true;
  54250. rect.setStyle('fill', node.getVisual('color'));
  54251. rect.setStyle('decal', node.getVisual('style').decal);
  54252. setStatesStylesFromModel(rect, itemModel);
  54253. group.add(rect);
  54254. nodeData.setItemGraphicEl(node.dataIndex, rect);
  54255. getECData(rect).dataType = 'node';
  54256. var focus = emphasisModel.get('focus');
  54257. enableHoverEmphasis(rect, focus === 'adjacency' ? node.getAdjacentDataIndices() : focus, emphasisModel.get('blurScope'));
  54258. });
  54259. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  54260. var itemModel = nodeData.getItemModel(dataIndex);
  54261. if (itemModel.get('draggable')) {
  54262. el.drift = function (dx, dy) {
  54263. sankeyView._focusAdjacencyDisabled = true;
  54264. this.shape.x += dx;
  54265. this.shape.y += dy;
  54266. this.dirty();
  54267. api.dispatchAction({
  54268. type: 'dragNode',
  54269. seriesId: seriesModel.id,
  54270. dataIndex: nodeData.getRawIndex(dataIndex),
  54271. localX: this.shape.x / width,
  54272. localY: this.shape.y / height
  54273. });
  54274. };
  54275. el.ondragend = function () {
  54276. sankeyView._focusAdjacencyDisabled = false;
  54277. };
  54278. el.draggable = true;
  54279. el.cursor = 'move';
  54280. }
  54281. });
  54282. if (!this._data && seriesModel.isAnimationEnabled()) {
  54283. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  54284. group.removeClipPath();
  54285. }));
  54286. }
  54287. this._data = seriesModel.getData();
  54288. };
  54289. SankeyView.prototype.dispose = function () {};
  54290. SankeyView.type = 'sankey';
  54291. return SankeyView;
  54292. }(ChartView); // Add animation to the view
  54293. function createGridClipShape$1(rect, seriesModel, cb) {
  54294. var rectEl = new Rect({
  54295. shape: {
  54296. x: rect.x - 10,
  54297. y: rect.y - 10,
  54298. width: 0,
  54299. height: rect.height + 20
  54300. }
  54301. });
  54302. initProps(rectEl, {
  54303. shape: {
  54304. width: rect.width + 20
  54305. }
  54306. }, seriesModel, cb);
  54307. return rectEl;
  54308. }
  54309. var SankeySeriesModel =
  54310. /** @class */
  54311. function (_super) {
  54312. __extends(SankeySeriesModel, _super);
  54313. function SankeySeriesModel() {
  54314. var _this = _super !== null && _super.apply(this, arguments) || this;
  54315. _this.type = SankeySeriesModel.type;
  54316. return _this;
  54317. }
  54318. /**
  54319. * Init a graph data structure from data in option series
  54320. *
  54321. * @param {Object} option the object used to config echarts view
  54322. * @return {module:echarts/data/List} storage initial data
  54323. */
  54324. SankeySeriesModel.prototype.getInitialData = function (option, ecModel) {
  54325. var links = option.edges || option.links;
  54326. var nodes = option.data || option.nodes;
  54327. var levels = option.levels;
  54328. this.levelModels = [];
  54329. var levelModels = this.levelModels;
  54330. for (var i = 0; i < levels.length; i++) {
  54331. if (levels[i].depth != null && levels[i].depth >= 0) {
  54332. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  54333. } else {
  54334. if ("development" !== 'production') {
  54335. throw new Error('levels[i].depth is mandatory and should be natural number');
  54336. }
  54337. }
  54338. }
  54339. if (nodes && links) {
  54340. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  54341. return graph.data;
  54342. }
  54343. function beforeLink(nodeData, edgeData) {
  54344. nodeData.wrapMethod('getItemModel', function (model, idx) {
  54345. var seriesModel = model.parentModel;
  54346. var layout = seriesModel.getData().getItemLayout(idx);
  54347. if (layout) {
  54348. var nodeDepth = layout.depth;
  54349. var levelModel = seriesModel.levelModels[nodeDepth];
  54350. if (levelModel) {
  54351. model.parentModel = levelModel;
  54352. }
  54353. }
  54354. return model;
  54355. });
  54356. edgeData.wrapMethod('getItemModel', function (model, idx) {
  54357. var seriesModel = model.parentModel;
  54358. var edge = seriesModel.getGraph().getEdgeByIndex(idx);
  54359. var layout = edge.node1.getLayout();
  54360. if (layout) {
  54361. var depth = layout.depth;
  54362. var levelModel = seriesModel.levelModels[depth];
  54363. if (levelModel) {
  54364. model.parentModel = levelModel;
  54365. }
  54366. }
  54367. return model;
  54368. });
  54369. }
  54370. };
  54371. SankeySeriesModel.prototype.setNodePosition = function (dataIndex, localPosition) {
  54372. var dataItem = this.option.data[dataIndex];
  54373. dataItem.localX = localPosition[0];
  54374. dataItem.localY = localPosition[1];
  54375. };
  54376. /**
  54377. * Return the graphic data structure
  54378. *
  54379. * @return graphic data structure
  54380. */
  54381. SankeySeriesModel.prototype.getGraph = function () {
  54382. return this.getData().graph;
  54383. };
  54384. /**
  54385. * Get edge data of graphic data structure
  54386. *
  54387. * @return data structure of list
  54388. */
  54389. SankeySeriesModel.prototype.getEdgeData = function () {
  54390. return this.getGraph().edgeData;
  54391. };
  54392. SankeySeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  54393. function noValue(val) {
  54394. return isNaN(val) || val == null;
  54395. } // dataType === 'node' or empty do not show tooltip by default
  54396. if (dataType === 'edge') {
  54397. var params = this.getDataParams(dataIndex, dataType);
  54398. var rawDataOpt = params.data;
  54399. var edgeValue = params.value;
  54400. var edgeName = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  54401. return createTooltipMarkup('nameValue', {
  54402. name: edgeName,
  54403. value: edgeValue,
  54404. noValue: noValue(edgeValue)
  54405. });
  54406. } // dataType === 'node'
  54407. else {
  54408. var node = this.getGraph().getNodeByIndex(dataIndex);
  54409. var value = node.getLayout().value;
  54410. var name_1 = this.getDataParams(dataIndex, dataType).data.name;
  54411. return createTooltipMarkup('nameValue', {
  54412. name: name_1 != null ? name_1 + '' : null,
  54413. value: value,
  54414. noValue: noValue(value)
  54415. });
  54416. }
  54417. };
  54418. SankeySeriesModel.prototype.optionUpdated = function () {
  54419. var option = this.option;
  54420. }; // Override Series.getDataParams()
  54421. SankeySeriesModel.prototype.getDataParams = function (dataIndex, dataType) {
  54422. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  54423. if (params.value == null && dataType === 'node') {
  54424. var node = this.getGraph().getNodeByIndex(dataIndex);
  54425. var nodeValue = node.getLayout().value;
  54426. params.value = nodeValue;
  54427. }
  54428. return params;
  54429. };
  54430. SankeySeriesModel.type = 'series.sankey';
  54431. SankeySeriesModel.defaultOption = {
  54432. zlevel: 0,
  54433. z: 2,
  54434. coordinateSystem: 'view',
  54435. left: '5%',
  54436. top: '5%',
  54437. right: '20%',
  54438. bottom: '5%',
  54439. orient: 'horizontal',
  54440. nodeWidth: 20,
  54441. nodeGap: 8,
  54442. draggable: true,
  54443. layoutIterations: 32,
  54444. label: {
  54445. show: true,
  54446. position: 'right',
  54447. fontSize: 12
  54448. },
  54449. levels: [],
  54450. nodeAlign: 'justify',
  54451. lineStyle: {
  54452. color: '#314656',
  54453. opacity: 0.2,
  54454. curveness: 0.5
  54455. },
  54456. emphasis: {
  54457. label: {
  54458. show: true
  54459. },
  54460. lineStyle: {
  54461. opacity: 0.5
  54462. }
  54463. },
  54464. select: {
  54465. itemStyle: {
  54466. borderColor: '#212121'
  54467. }
  54468. },
  54469. animationEasing: 'linear',
  54470. animationDuration: 1000
  54471. };
  54472. return SankeySeriesModel;
  54473. }(SeriesModel);
  54474. function sankeyLayout(ecModel, api) {
  54475. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  54476. var nodeWidth = seriesModel.get('nodeWidth');
  54477. var nodeGap = seriesModel.get('nodeGap');
  54478. var layoutInfo = getViewRect$4(seriesModel, api);
  54479. seriesModel.layoutInfo = layoutInfo;
  54480. var width = layoutInfo.width;
  54481. var height = layoutInfo.height;
  54482. var graph = seriesModel.getGraph();
  54483. var nodes = graph.nodes;
  54484. var edges = graph.edges;
  54485. computeNodeValues(nodes);
  54486. var filteredNodes = filter(nodes, function (node) {
  54487. return node.getLayout().value === 0;
  54488. });
  54489. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  54490. var orient = seriesModel.get('orient');
  54491. var nodeAlign = seriesModel.get('nodeAlign');
  54492. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  54493. });
  54494. }
  54495. /**
  54496. * Get the layout position of the whole view
  54497. */
  54498. function getViewRect$4(seriesModel, api) {
  54499. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  54500. width: api.getWidth(),
  54501. height: api.getHeight()
  54502. });
  54503. }
  54504. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  54505. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  54506. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  54507. computeEdgeDepths(nodes, orient);
  54508. }
  54509. /**
  54510. * Compute the value of each node by summing the associated edge's value
  54511. */
  54512. function computeNodeValues(nodes) {
  54513. each(nodes, function (node) {
  54514. var value1 = sum(node.outEdges, getEdgeValue);
  54515. var value2 = sum(node.inEdges, getEdgeValue);
  54516. var nodeRawValue = node.getValue() || 0;
  54517. var value = Math.max(value1, value2, nodeRawValue);
  54518. node.setLayout({
  54519. value: value
  54520. }, true);
  54521. });
  54522. }
  54523. /**
  54524. * Compute the x-position for each node.
  54525. *
  54526. * Here we use Kahn algorithm to detect cycle when we traverse
  54527. * the node to computer the initial x position.
  54528. */
  54529. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  54530. // Used to mark whether the edge is deleted. if it is deleted,
  54531. // the value is 0, otherwise it is 1.
  54532. var remainEdges = []; // Storage each node's indegree.
  54533. var indegreeArr = []; //Used to storage the node with indegree is equal to 0.
  54534. var zeroIndegrees = [];
  54535. var nextTargetNode = [];
  54536. var x = 0; // let kx = 0;
  54537. for (var i = 0; i < edges.length; i++) {
  54538. remainEdges[i] = 1;
  54539. }
  54540. for (var i = 0; i < nodes.length; i++) {
  54541. indegreeArr[i] = nodes[i].inEdges.length;
  54542. if (indegreeArr[i] === 0) {
  54543. zeroIndegrees.push(nodes[i]);
  54544. }
  54545. }
  54546. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  54547. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  54548. // position of the nodes.
  54549. while (zeroIndegrees.length) {
  54550. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  54551. var node = zeroIndegrees[idx];
  54552. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  54553. var isItemDepth = item.depth != null && item.depth >= 0;
  54554. if (isItemDepth && item.depth > maxNodeDepth) {
  54555. maxNodeDepth = item.depth;
  54556. }
  54557. node.setLayout({
  54558. depth: isItemDepth ? item.depth : x
  54559. }, true);
  54560. orient === 'vertical' ? node.setLayout({
  54561. dy: nodeWidth
  54562. }, true) : node.setLayout({
  54563. dx: nodeWidth
  54564. }, true);
  54565. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  54566. var edge = node.outEdges[edgeIdx];
  54567. var indexEdge = edges.indexOf(edge);
  54568. remainEdges[indexEdge] = 0;
  54569. var targetNode = edge.node2;
  54570. var nodeIndex = nodes.indexOf(targetNode);
  54571. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  54572. nextTargetNode.push(targetNode);
  54573. }
  54574. }
  54575. }
  54576. ++x;
  54577. zeroIndegrees = nextTargetNode;
  54578. nextTargetNode = [];
  54579. }
  54580. for (var i = 0; i < remainEdges.length; i++) {
  54581. if (remainEdges[i] === 1) {
  54582. throw new Error('Sankey is a DAG, the original data has cycle!');
  54583. }
  54584. }
  54585. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  54586. if (nodeAlign && nodeAlign !== 'left') {
  54587. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  54588. }
  54589. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  54590. scaleNodeBreadths(nodes, kx, orient);
  54591. }
  54592. function isNodeDepth(node) {
  54593. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  54594. return item.depth != null && item.depth >= 0;
  54595. }
  54596. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  54597. if (nodeAlign === 'right') {
  54598. var nextSourceNode = [];
  54599. var remainNodes = nodes;
  54600. var nodeHeight = 0;
  54601. while (remainNodes.length) {
  54602. for (var i = 0; i < remainNodes.length; i++) {
  54603. var node = remainNodes[i];
  54604. node.setLayout({
  54605. skNodeHeight: nodeHeight
  54606. }, true);
  54607. for (var j = 0; j < node.inEdges.length; j++) {
  54608. var edge = node.inEdges[j];
  54609. if (nextSourceNode.indexOf(edge.node1) < 0) {
  54610. nextSourceNode.push(edge.node1);
  54611. }
  54612. }
  54613. }
  54614. remainNodes = nextSourceNode;
  54615. nextSourceNode = [];
  54616. ++nodeHeight;
  54617. }
  54618. each(nodes, function (node) {
  54619. if (!isNodeDepth(node)) {
  54620. node.setLayout({
  54621. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  54622. }, true);
  54623. }
  54624. });
  54625. } else if (nodeAlign === 'justify') {
  54626. moveSinksRight(nodes, maxDepth);
  54627. }
  54628. }
  54629. /**
  54630. * All the node without outEgdes are assigned maximum x-position and
  54631. * be aligned in the last column.
  54632. *
  54633. * @param nodes. node of sankey view.
  54634. * @param maxDepth. use to assign to node without outEdges as x-position.
  54635. */
  54636. function moveSinksRight(nodes, maxDepth) {
  54637. each(nodes, function (node) {
  54638. if (!isNodeDepth(node) && !node.outEdges.length) {
  54639. node.setLayout({
  54640. depth: maxDepth
  54641. }, true);
  54642. }
  54643. });
  54644. }
  54645. /**
  54646. * Scale node x-position to the width
  54647. *
  54648. * @param nodes node of sankey view
  54649. * @param kx multiple used to scale nodes
  54650. */
  54651. function scaleNodeBreadths(nodes, kx, orient) {
  54652. each(nodes, function (node) {
  54653. var nodeDepth = node.getLayout().depth * kx;
  54654. orient === 'vertical' ? node.setLayout({
  54655. y: nodeDepth
  54656. }, true) : node.setLayout({
  54657. x: nodeDepth
  54658. }, true);
  54659. });
  54660. }
  54661. /**
  54662. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  54663. *
  54664. * @param nodes node of sankey view
  54665. * @param edges edge of sankey view
  54666. * @param height the whole height of the area to draw the view
  54667. * @param nodeGap the vertical distance between two nodes
  54668. * in the same column.
  54669. * @param iterations the number of iterations for the algorithm
  54670. */
  54671. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  54672. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  54673. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  54674. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  54675. for (var alpha = 1; iterations > 0; iterations--) {
  54676. // 0.99 is a experience parameter, ensure that each iterations of
  54677. // changes as small as possible.
  54678. alpha *= 0.99;
  54679. relaxRightToLeft(nodesByBreadth, alpha, orient);
  54680. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  54681. relaxLeftToRight(nodesByBreadth, alpha, orient);
  54682. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  54683. }
  54684. }
  54685. function prepareNodesByBreadth(nodes, orient) {
  54686. var nodesByBreadth = [];
  54687. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  54688. var groupResult = groupData(nodes, function (node) {
  54689. return node.getLayout()[keyAttr];
  54690. });
  54691. groupResult.keys.sort(function (a, b) {
  54692. return a - b;
  54693. });
  54694. each(groupResult.keys, function (key) {
  54695. nodesByBreadth.push(groupResult.buckets.get(key));
  54696. });
  54697. return nodesByBreadth;
  54698. }
  54699. /**
  54700. * Compute the original y-position for each node
  54701. */
  54702. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  54703. var minKy = Infinity;
  54704. each(nodesByBreadth, function (nodes) {
  54705. var n = nodes.length;
  54706. var sum = 0;
  54707. each(nodes, function (node) {
  54708. sum += node.getLayout().value;
  54709. });
  54710. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  54711. if (ky < minKy) {
  54712. minKy = ky;
  54713. }
  54714. });
  54715. each(nodesByBreadth, function (nodes) {
  54716. each(nodes, function (node, i) {
  54717. var nodeDy = node.getLayout().value * minKy;
  54718. if (orient === 'vertical') {
  54719. node.setLayout({
  54720. x: i
  54721. }, true);
  54722. node.setLayout({
  54723. dx: nodeDy
  54724. }, true);
  54725. } else {
  54726. node.setLayout({
  54727. y: i
  54728. }, true);
  54729. node.setLayout({
  54730. dy: nodeDy
  54731. }, true);
  54732. }
  54733. });
  54734. });
  54735. each(edges, function (edge) {
  54736. var edgeDy = +edge.getValue() * minKy;
  54737. edge.setLayout({
  54738. dy: edgeDy
  54739. }, true);
  54740. });
  54741. }
  54742. /**
  54743. * Resolve the collision of initialized depth (y-position)
  54744. */
  54745. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  54746. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  54747. each(nodesByBreadth, function (nodes) {
  54748. nodes.sort(function (a, b) {
  54749. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  54750. });
  54751. var nodeX;
  54752. var node;
  54753. var dy;
  54754. var y0 = 0;
  54755. var n = nodes.length;
  54756. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  54757. for (var i = 0; i < n; i++) {
  54758. node = nodes[i];
  54759. dy = y0 - node.getLayout()[keyAttr];
  54760. if (dy > 0) {
  54761. nodeX = node.getLayout()[keyAttr] + dy;
  54762. orient === 'vertical' ? node.setLayout({
  54763. x: nodeX
  54764. }, true) : node.setLayout({
  54765. y: nodeX
  54766. }, true);
  54767. }
  54768. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  54769. }
  54770. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  54771. dy = y0 - nodeGap - viewWidth;
  54772. if (dy > 0) {
  54773. nodeX = node.getLayout()[keyAttr] - dy;
  54774. orient === 'vertical' ? node.setLayout({
  54775. x: nodeX
  54776. }, true) : node.setLayout({
  54777. y: nodeX
  54778. }, true);
  54779. y0 = nodeX;
  54780. for (var i = n - 2; i >= 0; --i) {
  54781. node = nodes[i];
  54782. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  54783. if (dy > 0) {
  54784. nodeX = node.getLayout()[keyAttr] - dy;
  54785. orient === 'vertical' ? node.setLayout({
  54786. x: nodeX
  54787. }, true) : node.setLayout({
  54788. y: nodeX
  54789. }, true);
  54790. }
  54791. y0 = node.getLayout()[keyAttr];
  54792. }
  54793. }
  54794. });
  54795. }
  54796. /**
  54797. * Change the y-position of the nodes, except most the right side nodes
  54798. * @param nodesByBreadth
  54799. * @param alpha parameter used to adjust the nodes y-position
  54800. */
  54801. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  54802. each(nodesByBreadth.slice().reverse(), function (nodes) {
  54803. each(nodes, function (node) {
  54804. if (node.outEdges.length) {
  54805. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue);
  54806. if (isNaN(y)) {
  54807. var len = node.outEdges.length;
  54808. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  54809. }
  54810. if (orient === 'vertical') {
  54811. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  54812. node.setLayout({
  54813. x: nodeX
  54814. }, true);
  54815. } else {
  54816. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  54817. node.setLayout({
  54818. y: nodeY
  54819. }, true);
  54820. }
  54821. }
  54822. });
  54823. });
  54824. }
  54825. function weightedTarget(edge, orient) {
  54826. return center$1(edge.node2, orient) * edge.getValue();
  54827. }
  54828. function centerTarget(edge, orient) {
  54829. return center$1(edge.node2, orient);
  54830. }
  54831. function weightedSource(edge, orient) {
  54832. return center$1(edge.node1, orient) * edge.getValue();
  54833. }
  54834. function centerSource(edge, orient) {
  54835. return center$1(edge.node1, orient);
  54836. }
  54837. function center$1(node, orient) {
  54838. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  54839. }
  54840. function getEdgeValue(edge) {
  54841. return edge.getValue();
  54842. }
  54843. function sum(array, cb, orient) {
  54844. var sum = 0;
  54845. var len = array.length;
  54846. var i = -1;
  54847. while (++i < len) {
  54848. var value = +cb(array[i], orient);
  54849. if (!isNaN(value)) {
  54850. sum += value;
  54851. }
  54852. }
  54853. return sum;
  54854. }
  54855. /**
  54856. * Change the y-position of the nodes, except most the left side nodes
  54857. */
  54858. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  54859. each(nodesByBreadth, function (nodes) {
  54860. each(nodes, function (node) {
  54861. if (node.inEdges.length) {
  54862. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue);
  54863. if (isNaN(y)) {
  54864. var len = node.inEdges.length;
  54865. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  54866. }
  54867. if (orient === 'vertical') {
  54868. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  54869. node.setLayout({
  54870. x: nodeX
  54871. }, true);
  54872. } else {
  54873. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  54874. node.setLayout({
  54875. y: nodeY
  54876. }, true);
  54877. }
  54878. }
  54879. });
  54880. });
  54881. }
  54882. /**
  54883. * Compute the depth(y-position) of each edge
  54884. */
  54885. function computeEdgeDepths(nodes, orient) {
  54886. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  54887. each(nodes, function (node) {
  54888. node.outEdges.sort(function (a, b) {
  54889. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  54890. });
  54891. node.inEdges.sort(function (a, b) {
  54892. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  54893. });
  54894. });
  54895. each(nodes, function (node) {
  54896. var sy = 0;
  54897. var ty = 0;
  54898. each(node.outEdges, function (edge) {
  54899. edge.setLayout({
  54900. sy: sy
  54901. }, true);
  54902. sy += edge.getLayout().dy;
  54903. });
  54904. each(node.inEdges, function (edge) {
  54905. edge.setLayout({
  54906. ty: ty
  54907. }, true);
  54908. ty += edge.getLayout().dy;
  54909. });
  54910. });
  54911. }
  54912. function sankeyVisual(ecModel) {
  54913. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  54914. var graph = seriesModel.getGraph();
  54915. var nodes = graph.nodes;
  54916. if (nodes.length) {
  54917. var minValue_1 = Infinity;
  54918. var maxValue_1 = -Infinity;
  54919. each(nodes, function (node) {
  54920. var nodeValue = node.getLayout().value;
  54921. if (nodeValue < minValue_1) {
  54922. minValue_1 = nodeValue;
  54923. }
  54924. if (nodeValue > maxValue_1) {
  54925. maxValue_1 = nodeValue;
  54926. }
  54927. });
  54928. each(nodes, function (node) {
  54929. var mapping = new VisualMapping({
  54930. type: 'color',
  54931. mappingMethod: 'linear',
  54932. dataExtent: [minValue_1, maxValue_1],
  54933. visual: seriesModel.get('color')
  54934. });
  54935. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  54936. var customColor = node.getModel().get(['itemStyle', 'color']);
  54937. if (customColor != null) {
  54938. node.setVisual('color', customColor);
  54939. node.setVisual('style', {
  54940. fill: customColor
  54941. });
  54942. } else {
  54943. node.setVisual('color', mapValueToColor);
  54944. node.setVisual('style', {
  54945. fill: mapValueToColor
  54946. });
  54947. }
  54948. });
  54949. }
  54950. });
  54951. }
  54952. function install$i(registers) {
  54953. registers.registerChartView(SankeyView);
  54954. registers.registerSeriesModel(SankeySeriesModel);
  54955. registers.registerLayout(sankeyLayout);
  54956. registers.registerVisual(sankeyVisual);
  54957. registers.registerAction({
  54958. type: 'dragNode',
  54959. event: 'dragnode',
  54960. // here can only use 'update' now, other value is not support in echarts.
  54961. update: 'update'
  54962. }, function (payload, ecModel) {
  54963. ecModel.eachComponent({
  54964. mainType: 'series',
  54965. subType: 'sankey',
  54966. query: payload
  54967. }, function (seriesModel) {
  54968. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  54969. });
  54970. });
  54971. }
  54972. var WhiskerBoxCommonMixin =
  54973. /** @class */
  54974. function () {
  54975. function WhiskerBoxCommonMixin() {}
  54976. /**
  54977. * @override
  54978. */
  54979. WhiskerBoxCommonMixin.prototype.getInitialData = function (option, ecModel) {
  54980. // When both types of xAxis and yAxis are 'value', layout is
  54981. // needed to be specified by user. Otherwise, layout can be
  54982. // judged by which axis is category.
  54983. var ordinalMeta;
  54984. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  54985. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  54986. var xAxisType = xAxisModel.get('type');
  54987. var yAxisType = yAxisModel.get('type');
  54988. var addOrdinal; // FIXME
  54989. // Consider time axis.
  54990. if (xAxisType === 'category') {
  54991. option.layout = 'horizontal';
  54992. ordinalMeta = xAxisModel.getOrdinalMeta();
  54993. addOrdinal = true;
  54994. } else if (yAxisType === 'category') {
  54995. option.layout = 'vertical';
  54996. ordinalMeta = yAxisModel.getOrdinalMeta();
  54997. addOrdinal = true;
  54998. } else {
  54999. option.layout = option.layout || 'horizontal';
  55000. }
  55001. var coordDims = ['x', 'y'];
  55002. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  55003. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  55004. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  55005. var axisModels = [xAxisModel, yAxisModel];
  55006. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  55007. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  55008. var data = option.data; // ??? FIXME make a stage to perform data transfrom.
  55009. // MUST create a new data, consider setOption({}) again.
  55010. if (data && addOrdinal) {
  55011. var newOptionData_1 = [];
  55012. each(data, function (item, index) {
  55013. var newItem;
  55014. if (isArray(item)) {
  55015. newItem = item.slice();
  55016. item.unshift(index);
  55017. } else if (isArray(item.value)) {
  55018. newItem = item.value.slice();
  55019. item.value.unshift(index);
  55020. } else {
  55021. newItem = item;
  55022. }
  55023. newOptionData_1.push(newItem);
  55024. });
  55025. option.data = newOptionData_1;
  55026. }
  55027. var defaultValueDimensions = this.defaultValueDimensions;
  55028. var coordDimensions = [{
  55029. name: baseAxisDim,
  55030. type: getDimensionTypeByAxis(baseAxisType),
  55031. ordinalMeta: ordinalMeta,
  55032. otherDims: {
  55033. tooltip: false,
  55034. itemName: 0
  55035. },
  55036. dimsDef: ['base']
  55037. }, {
  55038. name: otherAxisDim,
  55039. type: getDimensionTypeByAxis(otherAxisType),
  55040. dimsDef: defaultValueDimensions.slice()
  55041. }];
  55042. return createListSimply(this, {
  55043. coordDimensions: coordDimensions,
  55044. dimensionsCount: defaultValueDimensions.length + 1,
  55045. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  55046. });
  55047. };
  55048. /**
  55049. * If horizontal, base axis is x, otherwise y.
  55050. * @override
  55051. */
  55052. WhiskerBoxCommonMixin.prototype.getBaseAxis = function () {
  55053. var dim = this._baseAxisDim;
  55054. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  55055. };
  55056. return WhiskerBoxCommonMixin;
  55057. }();
  55058. var BoxplotSeriesModel =
  55059. /** @class */
  55060. function (_super) {
  55061. __extends(BoxplotSeriesModel, _super);
  55062. function BoxplotSeriesModel() {
  55063. var _this = _super !== null && _super.apply(this, arguments) || this;
  55064. _this.type = BoxplotSeriesModel.type; // TODO
  55065. // box width represents group size, so dimension should have 'size'.
  55066. /**
  55067. * @see <https://en.wikipedia.org/wiki/Box_plot>
  55068. * The meanings of 'min' and 'max' depend on user,
  55069. * and echarts do not need to know it.
  55070. * @readOnly
  55071. */
  55072. _this.defaultValueDimensions = [{
  55073. name: 'min',
  55074. defaultTooltip: true
  55075. }, {
  55076. name: 'Q1',
  55077. defaultTooltip: true
  55078. }, {
  55079. name: 'median',
  55080. defaultTooltip: true
  55081. }, {
  55082. name: 'Q3',
  55083. defaultTooltip: true
  55084. }, {
  55085. name: 'max',
  55086. defaultTooltip: true
  55087. }];
  55088. _this.visualDrawType = 'stroke';
  55089. return _this;
  55090. }
  55091. BoxplotSeriesModel.type = 'series.boxplot';
  55092. BoxplotSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  55093. BoxplotSeriesModel.defaultOption = {
  55094. zlevel: 0,
  55095. z: 2,
  55096. coordinateSystem: 'cartesian2d',
  55097. legendHoverLink: true,
  55098. layout: null,
  55099. boxWidth: [7, 50],
  55100. itemStyle: {
  55101. color: '#fff',
  55102. borderWidth: 1
  55103. },
  55104. emphasis: {
  55105. scale: true,
  55106. itemStyle: {
  55107. borderWidth: 2,
  55108. shadowBlur: 5,
  55109. shadowOffsetX: 1,
  55110. shadowOffsetY: 1,
  55111. shadowColor: 'rgba(0,0,0,0.2)'
  55112. }
  55113. },
  55114. animationDuration: 800
  55115. };
  55116. return BoxplotSeriesModel;
  55117. }(SeriesModel);
  55118. mixin(BoxplotSeriesModel, WhiskerBoxCommonMixin, true);
  55119. var BoxplotView =
  55120. /** @class */
  55121. function (_super) {
  55122. __extends(BoxplotView, _super);
  55123. function BoxplotView() {
  55124. var _this = _super !== null && _super.apply(this, arguments) || this;
  55125. _this.type = BoxplotView.type;
  55126. return _this;
  55127. }
  55128. BoxplotView.prototype.render = function (seriesModel, ecModel, api) {
  55129. var data = seriesModel.getData();
  55130. var group = this.group;
  55131. var oldData = this._data; // There is no old data only when first rendering or switching from
  55132. // stream mode to normal mode, where previous elements should be removed.
  55133. if (!this._data) {
  55134. group.removeAll();
  55135. }
  55136. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  55137. data.diff(oldData).add(function (newIdx) {
  55138. if (data.hasValue(newIdx)) {
  55139. var itemLayout = data.getItemLayout(newIdx);
  55140. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  55141. data.setItemGraphicEl(newIdx, symbolEl);
  55142. group.add(symbolEl);
  55143. }
  55144. }).update(function (newIdx, oldIdx) {
  55145. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  55146. if (!data.hasValue(newIdx)) {
  55147. group.remove(symbolEl);
  55148. return;
  55149. }
  55150. var itemLayout = data.getItemLayout(newIdx);
  55151. if (!symbolEl) {
  55152. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  55153. } else {
  55154. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  55155. }
  55156. group.add(symbolEl);
  55157. data.setItemGraphicEl(newIdx, symbolEl);
  55158. }).remove(function (oldIdx) {
  55159. var el = oldData.getItemGraphicEl(oldIdx);
  55160. el && group.remove(el);
  55161. }).execute();
  55162. this._data = data;
  55163. };
  55164. BoxplotView.prototype.remove = function (ecModel) {
  55165. var group = this.group;
  55166. var data = this._data;
  55167. this._data = null;
  55168. data && data.eachItemGraphicEl(function (el) {
  55169. el && group.remove(el);
  55170. });
  55171. };
  55172. BoxplotView.type = 'boxplot';
  55173. return BoxplotView;
  55174. }(ChartView);
  55175. var BoxPathShape =
  55176. /** @class */
  55177. function () {
  55178. function BoxPathShape() {}
  55179. return BoxPathShape;
  55180. }();
  55181. var BoxPath =
  55182. /** @class */
  55183. function (_super) {
  55184. __extends(BoxPath, _super);
  55185. function BoxPath(opts) {
  55186. var _this = _super.call(this, opts) || this;
  55187. _this.type = 'boxplotBoxPath';
  55188. return _this;
  55189. }
  55190. BoxPath.prototype.getDefaultShape = function () {
  55191. return new BoxPathShape();
  55192. };
  55193. BoxPath.prototype.buildPath = function (ctx, shape) {
  55194. var ends = shape.points;
  55195. var i = 0;
  55196. ctx.moveTo(ends[i][0], ends[i][1]);
  55197. i++;
  55198. for (; i < 4; i++) {
  55199. ctx.lineTo(ends[i][0], ends[i][1]);
  55200. }
  55201. ctx.closePath();
  55202. for (; i < ends.length; i++) {
  55203. ctx.moveTo(ends[i][0], ends[i][1]);
  55204. i++;
  55205. ctx.lineTo(ends[i][0], ends[i][1]);
  55206. }
  55207. };
  55208. return BoxPath;
  55209. }(Path);
  55210. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  55211. var ends = itemLayout.ends;
  55212. var el = new BoxPath({
  55213. shape: {
  55214. points: isInit ? transInit(ends, constDim, itemLayout) : ends
  55215. }
  55216. });
  55217. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  55218. return el;
  55219. }
  55220. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  55221. var seriesModel = data.hostModel;
  55222. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  55223. updateMethod(el, {
  55224. shape: {
  55225. points: itemLayout.ends
  55226. }
  55227. }, seriesModel, dataIndex);
  55228. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  55229. el.style.strokeNoScale = true;
  55230. el.z2 = 100;
  55231. var itemModel = data.getItemModel(dataIndex);
  55232. setStatesStylesFromModel(el, itemModel);
  55233. enableHoverEmphasis(el, itemModel.get(['emphasis', 'focus']), itemModel.get(['emphasis', 'blurScope']));
  55234. }
  55235. function transInit(points, dim, itemLayout) {
  55236. return map(points, function (point) {
  55237. point = point.slice();
  55238. point[dim] = itemLayout.initBaseline;
  55239. return point;
  55240. });
  55241. }
  55242. /*
  55243. * Licensed to the Apache Software Foundation (ASF) under one
  55244. * or more contributor license agreements. See the NOTICE file
  55245. * distributed with this work for additional information
  55246. * regarding copyright ownership. The ASF licenses this file
  55247. * to you under the Apache License, Version 2.0 (the
  55248. * "License"); you may not use this file except in compliance
  55249. * with the License. You may obtain a copy of the License at
  55250. *
  55251. * http://www.apache.org/licenses/LICENSE-2.0
  55252. *
  55253. * Unless required by applicable law or agreed to in writing,
  55254. * software distributed under the License is distributed on an
  55255. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55256. * KIND, either express or implied. See the License for the
  55257. * specific language governing permissions and limitations
  55258. * under the License.
  55259. */
  55260. /**
  55261. * AUTO-GENERATED FILE. DO NOT MODIFY.
  55262. */
  55263. /*
  55264. * Licensed to the Apache Software Foundation (ASF) under one
  55265. * or more contributor license agreements. See the NOTICE file
  55266. * distributed with this work for additional information
  55267. * regarding copyright ownership. The ASF licenses this file
  55268. * to you under the Apache License, Version 2.0 (the
  55269. * "License"); you may not use this file except in compliance
  55270. * with the License. You may obtain a copy of the License at
  55271. *
  55272. * http://www.apache.org/licenses/LICENSE-2.0
  55273. *
  55274. * Unless required by applicable law or agreed to in writing,
  55275. * software distributed under the License is distributed on an
  55276. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55277. * KIND, either express or implied. See the License for the
  55278. * specific language governing permissions and limitations
  55279. * under the License.
  55280. */
  55281. function boxplotVisual(ecModel, api) {
  55282. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  55283. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  55284. });
  55285. }
  55286. var each$7 = each;
  55287. function boxplotLayout(ecModel) {
  55288. var groupResult = groupSeriesByAxis(ecModel);
  55289. each$7(groupResult, function (groupItem) {
  55290. var seriesModels = groupItem.seriesModels;
  55291. if (!seriesModels.length) {
  55292. return;
  55293. }
  55294. calculateBase(groupItem);
  55295. each$7(seriesModels, function (seriesModel, idx) {
  55296. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  55297. });
  55298. });
  55299. }
  55300. /**
  55301. * Group series by axis.
  55302. */
  55303. function groupSeriesByAxis(ecModel) {
  55304. var result = [];
  55305. var axisList = [];
  55306. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  55307. var baseAxis = seriesModel.getBaseAxis();
  55308. var idx = indexOf(axisList, baseAxis);
  55309. if (idx < 0) {
  55310. idx = axisList.length;
  55311. axisList[idx] = baseAxis;
  55312. result[idx] = {
  55313. axis: baseAxis,
  55314. seriesModels: []
  55315. };
  55316. }
  55317. result[idx].seriesModels.push(seriesModel);
  55318. });
  55319. return result;
  55320. }
  55321. /**
  55322. * Calculate offset and box width for each series.
  55323. */
  55324. function calculateBase(groupItem) {
  55325. var extent;
  55326. var baseAxis = groupItem.axis;
  55327. var seriesModels = groupItem.seriesModels;
  55328. var seriesCount = seriesModels.length;
  55329. var boxWidthList = groupItem.boxWidthList = [];
  55330. var boxOffsetList = groupItem.boxOffsetList = [];
  55331. var boundList = [];
  55332. var bandWidth;
  55333. if (baseAxis.type === 'category') {
  55334. bandWidth = baseAxis.getBandWidth();
  55335. } else {
  55336. var maxDataCount_1 = 0;
  55337. each$7(seriesModels, function (seriesModel) {
  55338. maxDataCount_1 = Math.max(maxDataCount_1, seriesModel.getData().count());
  55339. });
  55340. extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / maxDataCount_1;
  55341. }
  55342. each$7(seriesModels, function (seriesModel) {
  55343. var boxWidthBound = seriesModel.get('boxWidth');
  55344. if (!isArray(boxWidthBound)) {
  55345. boxWidthBound = [boxWidthBound, boxWidthBound];
  55346. }
  55347. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  55348. });
  55349. var availableWidth = bandWidth * 0.8 - 2;
  55350. var boxGap = availableWidth / seriesCount * 0.3;
  55351. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  55352. var base = boxWidth / 2 - availableWidth / 2;
  55353. each$7(seriesModels, function (seriesModel, idx) {
  55354. boxOffsetList.push(base);
  55355. base += boxGap + boxWidth;
  55356. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  55357. });
  55358. }
  55359. /**
  55360. * Calculate points location for each series.
  55361. */
  55362. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  55363. var coordSys = seriesModel.coordinateSystem;
  55364. var data = seriesModel.getData();
  55365. var halfWidth = boxWidth / 2;
  55366. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  55367. var vDimIdx = 1 - cDimIdx;
  55368. var coordDims = ['x', 'y'];
  55369. var cDim = data.mapDimension(coordDims[cDimIdx]);
  55370. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  55371. if (cDim == null || vDims.length < 5) {
  55372. return;
  55373. }
  55374. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  55375. var axisDimVal = data.get(cDim, dataIndex);
  55376. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  55377. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  55378. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  55379. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  55380. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  55381. var ends = [];
  55382. addBodyEnd(ends, end2, false);
  55383. addBodyEnd(ends, end4, true);
  55384. ends.push(end1, end2, end5, end4);
  55385. layEndLine(ends, end1);
  55386. layEndLine(ends, end5);
  55387. layEndLine(ends, median);
  55388. data.setItemLayout(dataIndex, {
  55389. initBaseline: median[vDimIdx],
  55390. ends: ends
  55391. });
  55392. }
  55393. function getPoint(axisDimVal, dim, dataIndex) {
  55394. var val = data.get(dim, dataIndex);
  55395. var p = [];
  55396. p[cDimIdx] = axisDimVal;
  55397. p[vDimIdx] = val;
  55398. var point;
  55399. if (isNaN(axisDimVal) || isNaN(val)) {
  55400. point = [NaN, NaN];
  55401. } else {
  55402. point = coordSys.dataToPoint(p);
  55403. point[cDimIdx] += offset;
  55404. }
  55405. return point;
  55406. }
  55407. function addBodyEnd(ends, point, start) {
  55408. var point1 = point.slice();
  55409. var point2 = point.slice();
  55410. point1[cDimIdx] += halfWidth;
  55411. point2[cDimIdx] -= halfWidth;
  55412. start ? ends.push(point1, point2) : ends.push(point2, point1);
  55413. }
  55414. function layEndLine(ends, endCenter) {
  55415. var from = endCenter.slice();
  55416. var to = endCenter.slice();
  55417. from[cDimIdx] -= halfWidth;
  55418. to[cDimIdx] += halfWidth;
  55419. ends.push(from, to);
  55420. }
  55421. }
  55422. /**
  55423. * See:
  55424. * <https://en.wikipedia.org/wiki/Box_plot#cite_note-frigge_hoaglin_iglewicz-2>
  55425. * <http://stat.ethz.ch/R-manual/R-devel/library/grDevices/html/boxplot.stats.html>
  55426. *
  55427. * Helper method for preparing data.
  55428. *
  55429. * @param rawData like
  55430. * [
  55431. * [12,232,443], (raw data set for the first box)
  55432. * [3843,5545,1232], (raw data set for the second box)
  55433. * ...
  55434. * ]
  55435. * @param opt.boundIQR=1.5 Data less than min bound is outlier.
  55436. * default 1.5, means Q1 - 1.5 * (Q3 - Q1).
  55437. * If 'none'/0 passed, min bound will not be used.
  55438. */
  55439. function prepareBoxplotData(rawData, opt) {
  55440. opt = opt || {};
  55441. var boxData = [];
  55442. var outliers = [];
  55443. var boundIQR = opt.boundIQR;
  55444. var useExtreme = boundIQR === 'none' || boundIQR === 0;
  55445. for (var i = 0; i < rawData.length; i++) {
  55446. var ascList = asc(rawData[i].slice());
  55447. var Q1 = quantile(ascList, 0.25);
  55448. var Q2 = quantile(ascList, 0.5);
  55449. var Q3 = quantile(ascList, 0.75);
  55450. var min = ascList[0];
  55451. var max = ascList[ascList.length - 1];
  55452. var bound = (boundIQR == null ? 1.5 : boundIQR) * (Q3 - Q1);
  55453. var low = useExtreme ? min : Math.max(min, Q1 - bound);
  55454. var high = useExtreme ? max : Math.min(max, Q3 + bound);
  55455. var itemNameFormatter = opt.itemNameFormatter;
  55456. var itemName = isFunction(itemNameFormatter) ? itemNameFormatter({
  55457. value: i
  55458. }) : isString(itemNameFormatter) ? itemNameFormatter.replace('{value}', i + '') : i + '';
  55459. boxData.push([itemName, low, Q1, Q2, Q3, high]);
  55460. for (var j = 0; j < ascList.length; j++) {
  55461. var dataItem = ascList[j];
  55462. if (dataItem < low || dataItem > high) {
  55463. var outlier = [itemName, dataItem];
  55464. outliers.push(outlier);
  55465. }
  55466. }
  55467. }
  55468. return {
  55469. boxData: boxData,
  55470. outliers: outliers
  55471. };
  55472. }
  55473. var boxplotTransform = {
  55474. type: 'echarts:boxplot',
  55475. transform: function transform(params) {
  55476. var upstream = params.upstream;
  55477. if (upstream.sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS) {
  55478. var errMsg = '';
  55479. if ("development" !== 'production') {
  55480. errMsg = makePrintable('source data is not applicable for this boxplot transform. Expect number[][].');
  55481. }
  55482. throwError(errMsg);
  55483. }
  55484. var result = prepareBoxplotData(upstream.getRawData(), params.config);
  55485. return [{
  55486. dimensions: ['ItemName', 'Low', 'Q1', 'Q2', 'Q3', 'High'],
  55487. data: result.boxData
  55488. }, {
  55489. data: result.outliers
  55490. }];
  55491. }
  55492. };
  55493. function install$j(registers) {
  55494. registers.registerSeriesModel(BoxplotSeriesModel);
  55495. registers.registerChartView(BoxplotView);
  55496. registers.registerVisual(boxplotVisual);
  55497. registers.registerLayout(boxplotLayout);
  55498. registers.registerTransform(boxplotTransform);
  55499. }
  55500. var SKIP_PROPS = ['color', 'borderColor'];
  55501. var CandlestickView =
  55502. /** @class */
  55503. function (_super) {
  55504. __extends(CandlestickView, _super);
  55505. function CandlestickView() {
  55506. var _this = _super !== null && _super.apply(this, arguments) || this;
  55507. _this.type = CandlestickView.type;
  55508. return _this;
  55509. }
  55510. CandlestickView.prototype.render = function (seriesModel, ecModel, api) {
  55511. // If there is clipPath created in large mode. Remove it.
  55512. this.group.removeClipPath();
  55513. this._updateDrawMode(seriesModel);
  55514. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  55515. };
  55516. CandlestickView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  55517. this._clear();
  55518. this._updateDrawMode(seriesModel);
  55519. };
  55520. CandlestickView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  55521. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  55522. };
  55523. CandlestickView.prototype._updateDrawMode = function (seriesModel) {
  55524. var isLargeDraw = seriesModel.pipelineContext.large;
  55525. if (this._isLargeDraw == null || isLargeDraw !== this._isLargeDraw) {
  55526. this._isLargeDraw = isLargeDraw;
  55527. this._clear();
  55528. }
  55529. };
  55530. CandlestickView.prototype._renderNormal = function (seriesModel) {
  55531. var data = seriesModel.getData();
  55532. var oldData = this._data;
  55533. var group = this.group;
  55534. var isSimpleBox = data.getLayout('isSimpleBox');
  55535. var needsClip = seriesModel.get('clip', true);
  55536. var coord = seriesModel.coordinateSystem;
  55537. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  55538. // stream mode to normal mode, where previous elements should be removed.
  55539. if (!this._data) {
  55540. group.removeAll();
  55541. }
  55542. data.diff(oldData).add(function (newIdx) {
  55543. if (data.hasValue(newIdx)) {
  55544. var itemLayout = data.getItemLayout(newIdx);
  55545. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  55546. return;
  55547. }
  55548. var el = createNormalBox$1(itemLayout, newIdx, true);
  55549. initProps(el, {
  55550. shape: {
  55551. points: itemLayout.ends
  55552. }
  55553. }, seriesModel, newIdx);
  55554. setBoxCommon(el, data, newIdx, isSimpleBox);
  55555. group.add(el);
  55556. data.setItemGraphicEl(newIdx, el);
  55557. }
  55558. }).update(function (newIdx, oldIdx) {
  55559. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  55560. if (!data.hasValue(newIdx)) {
  55561. group.remove(el);
  55562. return;
  55563. }
  55564. var itemLayout = data.getItemLayout(newIdx);
  55565. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  55566. group.remove(el);
  55567. return;
  55568. }
  55569. if (!el) {
  55570. el = createNormalBox$1(itemLayout);
  55571. } else {
  55572. updateProps(el, {
  55573. shape: {
  55574. points: itemLayout.ends
  55575. }
  55576. }, seriesModel, newIdx);
  55577. }
  55578. setBoxCommon(el, data, newIdx, isSimpleBox);
  55579. group.add(el);
  55580. data.setItemGraphicEl(newIdx, el);
  55581. }).remove(function (oldIdx) {
  55582. var el = oldData.getItemGraphicEl(oldIdx);
  55583. el && group.remove(el);
  55584. }).execute();
  55585. this._data = data;
  55586. };
  55587. CandlestickView.prototype._renderLarge = function (seriesModel) {
  55588. this._clear();
  55589. createLarge$1(seriesModel, this.group);
  55590. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  55591. if (clipPath) {
  55592. this.group.setClipPath(clipPath);
  55593. } else {
  55594. this.group.removeClipPath();
  55595. }
  55596. };
  55597. CandlestickView.prototype._incrementalRenderNormal = function (params, seriesModel) {
  55598. var data = seriesModel.getData();
  55599. var isSimpleBox = data.getLayout('isSimpleBox');
  55600. var dataIndex;
  55601. while ((dataIndex = params.next()) != null) {
  55602. var itemLayout = data.getItemLayout(dataIndex);
  55603. var el = createNormalBox$1(itemLayout);
  55604. setBoxCommon(el, data, dataIndex, isSimpleBox);
  55605. el.incremental = true;
  55606. this.group.add(el);
  55607. }
  55608. };
  55609. CandlestickView.prototype._incrementalRenderLarge = function (params, seriesModel) {
  55610. createLarge$1(seriesModel, this.group, true);
  55611. };
  55612. CandlestickView.prototype.remove = function (ecModel) {
  55613. this._clear();
  55614. };
  55615. CandlestickView.prototype._clear = function () {
  55616. this.group.removeAll();
  55617. this._data = null;
  55618. };
  55619. CandlestickView.type = 'candlestick';
  55620. return CandlestickView;
  55621. }(ChartView);
  55622. var NormalBoxPathShape =
  55623. /** @class */
  55624. function () {
  55625. function NormalBoxPathShape() {}
  55626. return NormalBoxPathShape;
  55627. }();
  55628. var NormalBoxPath =
  55629. /** @class */
  55630. function (_super) {
  55631. __extends(NormalBoxPath, _super);
  55632. function NormalBoxPath(opts) {
  55633. var _this = _super.call(this, opts) || this;
  55634. _this.type = 'normalCandlestickBox';
  55635. return _this;
  55636. }
  55637. NormalBoxPath.prototype.getDefaultShape = function () {
  55638. return new NormalBoxPathShape();
  55639. };
  55640. NormalBoxPath.prototype.buildPath = function (ctx, shape) {
  55641. var ends = shape.points;
  55642. if (this.__simpleBox) {
  55643. ctx.moveTo(ends[4][0], ends[4][1]);
  55644. ctx.lineTo(ends[6][0], ends[6][1]);
  55645. } else {
  55646. ctx.moveTo(ends[0][0], ends[0][1]);
  55647. ctx.lineTo(ends[1][0], ends[1][1]);
  55648. ctx.lineTo(ends[2][0], ends[2][1]);
  55649. ctx.lineTo(ends[3][0], ends[3][1]);
  55650. ctx.closePath();
  55651. ctx.moveTo(ends[4][0], ends[4][1]);
  55652. ctx.lineTo(ends[5][0], ends[5][1]);
  55653. ctx.moveTo(ends[6][0], ends[6][1]);
  55654. ctx.lineTo(ends[7][0], ends[7][1]);
  55655. }
  55656. };
  55657. return NormalBoxPath;
  55658. }(Path);
  55659. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  55660. var ends = itemLayout.ends;
  55661. return new NormalBoxPath({
  55662. shape: {
  55663. points: isInit ? transInit$1(ends, itemLayout) : ends
  55664. },
  55665. z2: 100
  55666. });
  55667. }
  55668. function isNormalBoxClipped(clipArea, itemLayout) {
  55669. var clipped = true;
  55670. for (var i = 0; i < itemLayout.ends.length; i++) {
  55671. // If any point are in the region.
  55672. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  55673. clipped = false;
  55674. break;
  55675. }
  55676. }
  55677. return clipped;
  55678. }
  55679. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  55680. var itemModel = data.getItemModel(dataIndex);
  55681. el.useStyle(data.getItemVisual(dataIndex, 'style'));
  55682. el.style.strokeNoScale = true;
  55683. el.__simpleBox = isSimpleBox;
  55684. setStatesStylesFromModel(el, itemModel);
  55685. }
  55686. function transInit$1(points, itemLayout) {
  55687. return map(points, function (point) {
  55688. point = point.slice();
  55689. point[1] = itemLayout.initBaseline;
  55690. return point;
  55691. });
  55692. }
  55693. var LargeBoxPathShape =
  55694. /** @class */
  55695. function () {
  55696. function LargeBoxPathShape() {}
  55697. return LargeBoxPathShape;
  55698. }();
  55699. var LargeBoxPath =
  55700. /** @class */
  55701. function (_super) {
  55702. __extends(LargeBoxPath, _super);
  55703. function LargeBoxPath(opts) {
  55704. var _this = _super.call(this, opts) || this;
  55705. _this.type = 'largeCandlestickBox';
  55706. return _this;
  55707. }
  55708. LargeBoxPath.prototype.getDefaultShape = function () {
  55709. return new LargeBoxPathShape();
  55710. };
  55711. LargeBoxPath.prototype.buildPath = function (ctx, shape) {
  55712. // Drawing lines is more efficient than drawing
  55713. // a whole line or drawing rects.
  55714. var points = shape.points;
  55715. for (var i = 0; i < points.length;) {
  55716. if (this.__sign === points[i++]) {
  55717. var x = points[i++];
  55718. ctx.moveTo(x, points[i++]);
  55719. ctx.lineTo(x, points[i++]);
  55720. } else {
  55721. i += 3;
  55722. }
  55723. }
  55724. };
  55725. return LargeBoxPath;
  55726. }(Path);
  55727. function createLarge$1(seriesModel, group, incremental) {
  55728. var data = seriesModel.getData();
  55729. var largePoints = data.getLayout('largePoints');
  55730. var elP = new LargeBoxPath({
  55731. shape: {
  55732. points: largePoints
  55733. },
  55734. __sign: 1
  55735. });
  55736. group.add(elP);
  55737. var elN = new LargeBoxPath({
  55738. shape: {
  55739. points: largePoints
  55740. },
  55741. __sign: -1
  55742. });
  55743. group.add(elN);
  55744. setLargeStyle$1(1, elP, seriesModel);
  55745. setLargeStyle$1(-1, elN, seriesModel);
  55746. if (incremental) {
  55747. elP.incremental = true;
  55748. elN.incremental = true;
  55749. }
  55750. }
  55751. function setLargeStyle$1(sign, el, seriesModel, data) {
  55752. // TODO put in visual?
  55753. var borderColor = seriesModel.get(['itemStyle', sign > 0 ? 'borderColor' : 'borderColor0']) || seriesModel.get(['itemStyle', sign > 0 ? 'color' : 'color0']); // Color must be excluded.
  55754. // Because symbol provide setColor individually to set fill and stroke
  55755. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(SKIP_PROPS);
  55756. el.useStyle(itemStyle);
  55757. el.style.fill = null;
  55758. el.style.stroke = borderColor;
  55759. }
  55760. var CandlestickSeriesModel =
  55761. /** @class */
  55762. function (_super) {
  55763. __extends(CandlestickSeriesModel, _super);
  55764. function CandlestickSeriesModel() {
  55765. var _this = _super !== null && _super.apply(this, arguments) || this;
  55766. _this.type = CandlestickSeriesModel.type;
  55767. _this.defaultValueDimensions = [{
  55768. name: 'open',
  55769. defaultTooltip: true
  55770. }, {
  55771. name: 'close',
  55772. defaultTooltip: true
  55773. }, {
  55774. name: 'lowest',
  55775. defaultTooltip: true
  55776. }, {
  55777. name: 'highest',
  55778. defaultTooltip: true
  55779. }];
  55780. return _this;
  55781. }
  55782. /**
  55783. * Get dimension for shadow in dataZoom
  55784. * @return dimension name
  55785. */
  55786. CandlestickSeriesModel.prototype.getShadowDim = function () {
  55787. return 'open';
  55788. };
  55789. CandlestickSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  55790. var itemLayout = data.getItemLayout(dataIndex);
  55791. return itemLayout && selectors.rect(itemLayout.brushRect);
  55792. };
  55793. CandlestickSeriesModel.type = 'series.candlestick';
  55794. CandlestickSeriesModel.dependencies = ['xAxis', 'yAxis', 'grid'];
  55795. CandlestickSeriesModel.defaultOption = {
  55796. zlevel: 0,
  55797. z: 2,
  55798. coordinateSystem: 'cartesian2d',
  55799. legendHoverLink: true,
  55800. // xAxisIndex: 0,
  55801. // yAxisIndex: 0,
  55802. layout: null,
  55803. clip: true,
  55804. itemStyle: {
  55805. color: '#eb5454',
  55806. color0: '#47b262',
  55807. borderColor: '#eb5454',
  55808. borderColor0: '#47b262',
  55809. // borderColor: '#d24040',
  55810. // borderColor0: '#398f4f',
  55811. borderWidth: 1
  55812. },
  55813. emphasis: {
  55814. scale: true,
  55815. itemStyle: {
  55816. borderWidth: 2
  55817. }
  55818. },
  55819. barMaxWidth: null,
  55820. barMinWidth: null,
  55821. barWidth: null,
  55822. large: true,
  55823. largeThreshold: 600,
  55824. progressive: 3e3,
  55825. progressiveThreshold: 1e4,
  55826. progressiveChunkMode: 'mod',
  55827. animationEasing: 'linear',
  55828. animationDuration: 300
  55829. };
  55830. return CandlestickSeriesModel;
  55831. }(SeriesModel);
  55832. mixin(CandlestickSeriesModel, WhiskerBoxCommonMixin, true);
  55833. function candlestickPreprocessor(option) {
  55834. if (!option || !isArray(option.series)) {
  55835. return;
  55836. } // Translate 'k' to 'candlestick'.
  55837. each(option.series, function (seriesItem) {
  55838. if (isObject(seriesItem) && seriesItem.type === 'k') {
  55839. seriesItem.type = 'candlestick';
  55840. }
  55841. });
  55842. }
  55843. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  55844. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  55845. var positiveColorQuery = ['itemStyle', 'color'];
  55846. var negativeColorQuery = ['itemStyle', 'color0'];
  55847. var candlestickVisual = {
  55848. seriesType: 'candlestick',
  55849. plan: createRenderPlanner(),
  55850. // For legend.
  55851. performRawSeries: true,
  55852. reset: function (seriesModel, ecModel) {
  55853. function getColor(sign, model) {
  55854. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  55855. }
  55856. function getBorderColor(sign, model) {
  55857. return model.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  55858. }
  55859. var data = seriesModel.getData();
  55860. data.setVisual('legendSymbol', 'roundRect'); // Only visible series has each data be visual encoded
  55861. if (ecModel.isSeriesFiltered(seriesModel)) {
  55862. return;
  55863. }
  55864. var isLargeRender = seriesModel.pipelineContext.large;
  55865. return !isLargeRender && {
  55866. progress: function (params, data) {
  55867. var dataIndex;
  55868. while ((dataIndex = params.next()) != null) {
  55869. var itemModel = data.getItemModel(dataIndex);
  55870. var sign = data.getItemLayout(dataIndex).sign;
  55871. var style = itemModel.getItemStyle();
  55872. style.fill = getColor(sign, itemModel);
  55873. style.stroke = getBorderColor(sign, itemModel) || style.fill;
  55874. var existsStyle = data.ensureUniqueItemVisual(dataIndex, 'style');
  55875. extend(existsStyle, style);
  55876. }
  55877. }
  55878. };
  55879. }
  55880. };
  55881. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  55882. var candlestickLayout = {
  55883. seriesType: 'candlestick',
  55884. plan: createRenderPlanner(),
  55885. reset: function (seriesModel) {
  55886. var coordSys = seriesModel.coordinateSystem;
  55887. var data = seriesModel.getData();
  55888. var candleWidth = calculateCandleWidth(seriesModel, data);
  55889. var cDimIdx = 0;
  55890. var vDimIdx = 1;
  55891. var coordDims = ['x', 'y'];
  55892. var cDim = data.mapDimension(coordDims[cDimIdx]);
  55893. var vDims = data.mapDimensionsAll(coordDims[vDimIdx]);
  55894. var openDim = vDims[0];
  55895. var closeDim = vDims[1];
  55896. var lowestDim = vDims[2];
  55897. var highestDim = vDims[3];
  55898. data.setLayout({
  55899. candleWidth: candleWidth,
  55900. // The value is experimented visually.
  55901. isSimpleBox: candleWidth <= 1.3
  55902. });
  55903. if (cDim == null || vDims.length < 4) {
  55904. return;
  55905. }
  55906. return {
  55907. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  55908. };
  55909. function normalProgress(params, data) {
  55910. var dataIndex;
  55911. while ((dataIndex = params.next()) != null) {
  55912. var axisDimVal = data.get(cDim, dataIndex);
  55913. var openVal = data.get(openDim, dataIndex);
  55914. var closeVal = data.get(closeDim, dataIndex);
  55915. var lowestVal = data.get(lowestDim, dataIndex);
  55916. var highestVal = data.get(highestDim, dataIndex);
  55917. var ocLow = Math.min(openVal, closeVal);
  55918. var ocHigh = Math.max(openVal, closeVal);
  55919. var ocLowPoint = getPoint(ocLow, axisDimVal);
  55920. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  55921. var lowestPoint = getPoint(lowestVal, axisDimVal);
  55922. var highestPoint = getPoint(highestVal, axisDimVal);
  55923. var ends = [];
  55924. addBodyEnd(ends, ocHighPoint, 0);
  55925. addBodyEnd(ends, ocLowPoint, 1);
  55926. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  55927. data.setItemLayout(dataIndex, {
  55928. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  55929. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  55930. ends: ends,
  55931. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  55932. });
  55933. }
  55934. function getPoint(val, axisDimVal) {
  55935. var p = [];
  55936. p[cDimIdx] = axisDimVal;
  55937. p[vDimIdx] = val;
  55938. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  55939. }
  55940. function addBodyEnd(ends, point, start) {
  55941. var point1 = point.slice();
  55942. var point2 = point.slice();
  55943. point1[cDimIdx] = subPixelOptimize$1(point1[cDimIdx] + candleWidth / 2, 1, false);
  55944. point2[cDimIdx] = subPixelOptimize$1(point2[cDimIdx] - candleWidth / 2, 1, true);
  55945. start ? ends.push(point1, point2) : ends.push(point2, point1);
  55946. }
  55947. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  55948. var pmin = getPoint(lowestVal, axisDimVal);
  55949. var pmax = getPoint(highestVal, axisDimVal);
  55950. pmin[cDimIdx] -= candleWidth / 2;
  55951. pmax[cDimIdx] -= candleWidth / 2;
  55952. return {
  55953. x: pmin[0],
  55954. y: pmin[1],
  55955. width: candleWidth ,
  55956. height: pmax[1] - pmin[1]
  55957. };
  55958. }
  55959. function subPixelOptimizePoint(point) {
  55960. point[cDimIdx] = subPixelOptimize$1(point[cDimIdx], 1);
  55961. return point;
  55962. }
  55963. }
  55964. function largeProgress(params, data) {
  55965. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  55966. var points = new LargeArr$1(params.count * 4);
  55967. var offset = 0;
  55968. var point;
  55969. var tmpIn = [];
  55970. var tmpOut = [];
  55971. var dataIndex;
  55972. while ((dataIndex = params.next()) != null) {
  55973. var axisDimVal = data.get(cDim, dataIndex);
  55974. var openVal = data.get(openDim, dataIndex);
  55975. var closeVal = data.get(closeDim, dataIndex);
  55976. var lowestVal = data.get(lowestDim, dataIndex);
  55977. var highestVal = data.get(highestDim, dataIndex);
  55978. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  55979. points[offset++] = NaN;
  55980. offset += 3;
  55981. continue;
  55982. }
  55983. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  55984. tmpIn[cDimIdx] = axisDimVal;
  55985. tmpIn[vDimIdx] = lowestVal;
  55986. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  55987. points[offset++] = point ? point[0] : NaN;
  55988. points[offset++] = point ? point[1] : NaN;
  55989. tmpIn[vDimIdx] = highestVal;
  55990. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  55991. points[offset++] = point ? point[1] : NaN;
  55992. }
  55993. data.setLayout('largePoints', points);
  55994. }
  55995. }
  55996. };
  55997. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  55998. var sign;
  55999. if (openVal > closeVal) {
  56000. sign = -1;
  56001. } else if (openVal < closeVal) {
  56002. sign = 1;
  56003. } else {
  56004. sign = dataIndex > 0 // If close === open, compare with close of last record
  56005. ? data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  56006. 1;
  56007. }
  56008. return sign;
  56009. }
  56010. function calculateCandleWidth(seriesModel, data) {
  56011. var baseAxis = seriesModel.getBaseAxis();
  56012. var extent;
  56013. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  56014. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  56015. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  56016. var barWidth = seriesModel.get('barWidth');
  56017. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  56018. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  56019. }
  56020. function install$k(registers) {
  56021. registers.registerChartView(CandlestickView);
  56022. registers.registerSeriesModel(CandlestickSeriesModel);
  56023. registers.registerPreprocessor(candlestickPreprocessor);
  56024. registers.registerVisual(candlestickVisual);
  56025. registers.registerLayout(candlestickLayout);
  56026. }
  56027. var EFFECT_RIPPLE_NUMBER = 3;
  56028. function normalizeSymbolSize$1(symbolSize) {
  56029. if (!isArray(symbolSize)) {
  56030. symbolSize = [+symbolSize, +symbolSize];
  56031. }
  56032. return symbolSize;
  56033. }
  56034. function updateRipplePath(rippleGroup, effectCfg) {
  56035. var color = effectCfg.rippleEffectColor || effectCfg.color;
  56036. rippleGroup.eachChild(function (ripplePath) {
  56037. ripplePath.attr({
  56038. z: effectCfg.z,
  56039. zlevel: effectCfg.zlevel,
  56040. style: {
  56041. stroke: effectCfg.brushType === 'stroke' ? color : null,
  56042. fill: effectCfg.brushType === 'fill' ? color : null
  56043. }
  56044. });
  56045. });
  56046. }
  56047. var EffectSymbol =
  56048. /** @class */
  56049. function (_super) {
  56050. __extends(EffectSymbol, _super);
  56051. function EffectSymbol(data, idx) {
  56052. var _this = _super.call(this) || this;
  56053. var symbol = new Symbol(data, idx);
  56054. var rippleGroup = new Group();
  56055. _this.add(symbol);
  56056. _this.add(rippleGroup);
  56057. _this.updateData(data, idx);
  56058. return _this;
  56059. }
  56060. EffectSymbol.prototype.stopEffectAnimation = function () {
  56061. this.childAt(1).removeAll();
  56062. };
  56063. EffectSymbol.prototype.startEffectAnimation = function (effectCfg) {
  56064. var symbolType = effectCfg.symbolType;
  56065. var color = effectCfg.color;
  56066. var rippleGroup = this.childAt(1);
  56067. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  56068. // If width/height are set too small (e.g., set to 1) on ios10
  56069. // and macOS Sierra, a circle stroke become a rect, no matter what
  56070. // the scale is set. So we set width/height as 2. See #4136.
  56071. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  56072. ripplePath.attr({
  56073. style: {
  56074. strokeNoScale: true
  56075. },
  56076. z2: 99,
  56077. silent: true,
  56078. scaleX: 0.5,
  56079. scaleY: 0.5
  56080. });
  56081. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset; // TODO Configurable effectCfg.period
  56082. ripplePath.animate('', true).when(effectCfg.period, {
  56083. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  56084. }).delay(delay).start();
  56085. ripplePath.animateStyle(true).when(effectCfg.period, {
  56086. opacity: 0
  56087. }).delay(delay).start();
  56088. rippleGroup.add(ripplePath);
  56089. }
  56090. updateRipplePath(rippleGroup, effectCfg);
  56091. };
  56092. /**
  56093. * Update effect symbol
  56094. */
  56095. EffectSymbol.prototype.updateEffectAnimation = function (effectCfg) {
  56096. var oldEffectCfg = this._effectCfg;
  56097. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  56098. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  56099. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  56100. var propName = DIFFICULT_PROPS[i];
  56101. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  56102. this.stopEffectAnimation();
  56103. this.startEffectAnimation(effectCfg);
  56104. return;
  56105. }
  56106. }
  56107. updateRipplePath(rippleGroup, effectCfg);
  56108. };
  56109. /**
  56110. * Highlight symbol
  56111. */
  56112. EffectSymbol.prototype.highlight = function () {
  56113. enterEmphasis(this);
  56114. };
  56115. /**
  56116. * Downplay symbol
  56117. */
  56118. EffectSymbol.prototype.downplay = function () {
  56119. leaveEmphasis(this);
  56120. };
  56121. /**
  56122. * Update symbol properties
  56123. */
  56124. EffectSymbol.prototype.updateData = function (data, idx) {
  56125. var _this = this;
  56126. var seriesModel = data.hostModel;
  56127. this.childAt(0).updateData(data, idx);
  56128. var rippleGroup = this.childAt(1);
  56129. var itemModel = data.getItemModel(idx);
  56130. var symbolType = data.getItemVisual(idx, 'symbol');
  56131. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  56132. var symbolStyle = data.getItemVisual(idx, 'style');
  56133. var color = symbolStyle && symbolStyle.fill;
  56134. rippleGroup.setScale(symbolSize);
  56135. rippleGroup.traverse(function (ripplePath) {
  56136. ripplePath.setStyle('fill', color);
  56137. });
  56138. var symbolOffset = itemModel.getShallow('symbolOffset');
  56139. if (symbolOffset) {
  56140. rippleGroup.x = parsePercent$1(symbolOffset[0], symbolSize[0]);
  56141. rippleGroup.y = parsePercent$1(symbolOffset[1], symbolSize[1]);
  56142. }
  56143. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  56144. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  56145. var effectCfg = {};
  56146. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  56147. effectCfg.rippleScale = itemModel.get(['rippleEffect', 'scale']);
  56148. effectCfg.brushType = itemModel.get(['rippleEffect', 'brushType']);
  56149. effectCfg.period = itemModel.get(['rippleEffect', 'period']) * 1000;
  56150. effectCfg.effectOffset = idx / data.count();
  56151. effectCfg.z = seriesModel.getShallow('z') || 0;
  56152. effectCfg.zlevel = seriesModel.getShallow('zlevel') || 0;
  56153. effectCfg.symbolType = symbolType;
  56154. effectCfg.color = color;
  56155. effectCfg.rippleEffectColor = itemModel.get(['rippleEffect', 'color']);
  56156. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  56157. if (effectCfg.showEffectOn === 'render') {
  56158. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  56159. this._effectCfg = effectCfg;
  56160. } else {
  56161. // Not keep old effect config
  56162. this._effectCfg = null;
  56163. this.stopEffectAnimation();
  56164. this.onHoverStateChange = function (toState) {
  56165. if (toState === 'emphasis') {
  56166. if (effectCfg.showEffectOn !== 'render') {
  56167. _this.startEffectAnimation(effectCfg);
  56168. }
  56169. } else if (toState === 'normal') {
  56170. if (effectCfg.showEffectOn !== 'render') {
  56171. _this.stopEffectAnimation();
  56172. }
  56173. }
  56174. };
  56175. }
  56176. this._effectCfg = effectCfg;
  56177. enableHoverEmphasis(this);
  56178. };
  56179. EffectSymbol.prototype.fadeOut = function (cb) {
  56180. this.off('mouseover').off('mouseout');
  56181. cb && cb();
  56182. };
  56183. return EffectSymbol;
  56184. }(Group);
  56185. inherits(EffectSymbol, Group);
  56186. var EffectScatterView =
  56187. /** @class */
  56188. function (_super) {
  56189. __extends(EffectScatterView, _super);
  56190. function EffectScatterView() {
  56191. var _this = _super !== null && _super.apply(this, arguments) || this;
  56192. _this.type = EffectScatterView.type;
  56193. return _this;
  56194. }
  56195. EffectScatterView.prototype.init = function () {
  56196. this._symbolDraw = new SymbolDraw(EffectSymbol);
  56197. };
  56198. EffectScatterView.prototype.render = function (seriesModel, ecModel, api) {
  56199. var data = seriesModel.getData();
  56200. var effectSymbolDraw = this._symbolDraw;
  56201. effectSymbolDraw.updateData(data);
  56202. this.group.add(effectSymbolDraw.group);
  56203. };
  56204. EffectScatterView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  56205. var data = seriesModel.getData();
  56206. this.group.dirty();
  56207. var res = pointsLayout('').reset(seriesModel, ecModel, api);
  56208. if (res.progress) {
  56209. res.progress({
  56210. start: 0,
  56211. end: data.count(),
  56212. count: data.count()
  56213. }, data);
  56214. }
  56215. this._symbolDraw.updateLayout();
  56216. };
  56217. EffectScatterView.prototype._updateGroupTransform = function (seriesModel) {
  56218. var coordSys = seriesModel.coordinateSystem;
  56219. if (coordSys && coordSys.getRoamTransform) {
  56220. this.group.transform = clone$2(coordSys.getRoamTransform());
  56221. this.group.decomposeTransform();
  56222. }
  56223. };
  56224. EffectScatterView.prototype.remove = function (ecModel, api) {
  56225. this._symbolDraw && this._symbolDraw.remove(true);
  56226. };
  56227. EffectScatterView.type = 'effectScatter';
  56228. return EffectScatterView;
  56229. }(ChartView);
  56230. var EffectScatterSeriesModel =
  56231. /** @class */
  56232. function (_super) {
  56233. __extends(EffectScatterSeriesModel, _super);
  56234. function EffectScatterSeriesModel() {
  56235. var _this = _super !== null && _super.apply(this, arguments) || this;
  56236. _this.type = EffectScatterSeriesModel.type;
  56237. _this.hasSymbolVisual = true;
  56238. return _this;
  56239. }
  56240. EffectScatterSeriesModel.prototype.getInitialData = function (option, ecModel) {
  56241. return createListFromArray(this.getSource(), this, {
  56242. useEncodeDefaulter: true
  56243. });
  56244. };
  56245. EffectScatterSeriesModel.prototype.brushSelector = function (dataIndex, data, selectors) {
  56246. return selectors.point(data.getItemLayout(dataIndex));
  56247. };
  56248. EffectScatterSeriesModel.type = 'series.effectScatter';
  56249. EffectScatterSeriesModel.dependencies = ['grid', 'polar'];
  56250. EffectScatterSeriesModel.defaultOption = {
  56251. coordinateSystem: 'cartesian2d',
  56252. zlevel: 0,
  56253. z: 2,
  56254. legendHoverLink: true,
  56255. effectType: 'ripple',
  56256. progressive: 0,
  56257. // When to show the effect, option: 'render'|'emphasis'
  56258. showEffectOn: 'render',
  56259. // Ripple effect config
  56260. rippleEffect: {
  56261. period: 4,
  56262. // Scale of ripple
  56263. scale: 2.5,
  56264. // Brush type can be fill or stroke
  56265. brushType: 'fill'
  56266. },
  56267. // Cartesian coordinate system
  56268. // xAxisIndex: 0,
  56269. // yAxisIndex: 0,
  56270. // Polar coordinate system
  56271. // polarIndex: 0,
  56272. // Geo coordinate system
  56273. // geoIndex: 0,
  56274. // symbol: null, // 图形类型
  56275. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  56276. // symbolRotate: null, // 图形旋转控制
  56277. // itemStyle: {
  56278. // opacity: 1
  56279. // }
  56280. };
  56281. return EffectScatterSeriesModel;
  56282. }(SeriesModel);
  56283. function install$l(registers) {
  56284. registers.registerChartView(EffectScatterView);
  56285. registers.registerSeriesModel(EffectScatterSeriesModel);
  56286. registers.registerLayout(pointsLayout('effectScatter'));
  56287. }
  56288. var EffectLine =
  56289. /** @class */
  56290. function (_super) {
  56291. __extends(EffectLine, _super);
  56292. function EffectLine(lineData, idx, seriesScope) {
  56293. var _this = _super.call(this) || this;
  56294. _this.add(_this.createLine(lineData, idx, seriesScope));
  56295. _this._updateEffectSymbol(lineData, idx);
  56296. return _this;
  56297. }
  56298. EffectLine.prototype.createLine = function (lineData, idx, seriesScope) {
  56299. return new Line$1(lineData, idx, seriesScope);
  56300. };
  56301. EffectLine.prototype._updateEffectSymbol = function (lineData, idx) {
  56302. var itemModel = lineData.getItemModel(idx);
  56303. var effectModel = itemModel.getModel('effect');
  56304. var size = effectModel.get('symbolSize');
  56305. var symbolType = effectModel.get('symbol');
  56306. if (!isArray(size)) {
  56307. size = [size, size];
  56308. }
  56309. var lineStyle = lineData.getItemVisual(idx, 'style');
  56310. var color = effectModel.get('color') || lineStyle && lineStyle.stroke;
  56311. var symbol = this.childAt(1);
  56312. if (this._symbolType !== symbolType) {
  56313. // Remove previous
  56314. this.remove(symbol);
  56315. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  56316. symbol.z2 = 100;
  56317. symbol.culling = true;
  56318. this.add(symbol);
  56319. } // Symbol may be removed if loop is false
  56320. if (!symbol) {
  56321. return;
  56322. } // Shadow color is same with color in default
  56323. symbol.setStyle('shadowColor', color);
  56324. symbol.setStyle(effectModel.getItemStyle(['color']));
  56325. symbol.scaleX = size[0];
  56326. symbol.scaleY = size[1];
  56327. symbol.setColor(color);
  56328. this._symbolType = symbolType;
  56329. this._symbolScale = size;
  56330. this._updateEffectAnimation(lineData, effectModel, idx);
  56331. };
  56332. EffectLine.prototype._updateEffectAnimation = function (lineData, effectModel, idx) {
  56333. var symbol = this.childAt(1);
  56334. if (!symbol) {
  56335. return;
  56336. }
  56337. var self = this;
  56338. var points = lineData.getItemLayout(idx);
  56339. var period = effectModel.get('period') * 1000;
  56340. var loop = effectModel.get('loop');
  56341. var constantSpeed = effectModel.get('constantSpeed');
  56342. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  56343. return idx / lineData.count() * period / 3;
  56344. }); // Ignore when updating
  56345. symbol.ignore = true;
  56346. this._updateAnimationPoints(symbol, points);
  56347. if (constantSpeed > 0) {
  56348. period = this._getLineLength(symbol) / constantSpeed * 1000;
  56349. }
  56350. if (period !== this._period || loop !== this._loop) {
  56351. symbol.stopAnimation();
  56352. if (period > 0) {
  56353. var delayNum = void 0;
  56354. if (typeof delayExpr === 'function') {
  56355. delayNum = delayExpr(idx);
  56356. } else {
  56357. delayNum = delayExpr;
  56358. }
  56359. if (symbol.__t > 0) {
  56360. delayNum = -period * symbol.__t;
  56361. }
  56362. symbol.__t = 0;
  56363. var animator = symbol.animate('', loop).when(period, {
  56364. __t: 1
  56365. }).delay(delayNum).during(function () {
  56366. self._updateSymbolPosition(symbol);
  56367. });
  56368. if (!loop) {
  56369. animator.done(function () {
  56370. self.remove(symbol);
  56371. });
  56372. }
  56373. animator.start();
  56374. }
  56375. }
  56376. this._period = period;
  56377. this._loop = loop;
  56378. };
  56379. EffectLine.prototype._getLineLength = function (symbol) {
  56380. // Not so accurate
  56381. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  56382. };
  56383. EffectLine.prototype._updateAnimationPoints = function (symbol, points) {
  56384. symbol.__p1 = points[0];
  56385. symbol.__p2 = points[1];
  56386. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  56387. };
  56388. EffectLine.prototype.updateData = function (lineData, idx, seriesScope) {
  56389. this.childAt(0).updateData(lineData, idx, seriesScope);
  56390. this._updateEffectSymbol(lineData, idx);
  56391. };
  56392. EffectLine.prototype._updateSymbolPosition = function (symbol) {
  56393. var p1 = symbol.__p1;
  56394. var p2 = symbol.__p2;
  56395. var cp1 = symbol.__cp1;
  56396. var t = symbol.__t;
  56397. var pos = [symbol.x, symbol.y];
  56398. var lastPos = pos.slice();
  56399. var quadraticAt$1 = quadraticAt;
  56400. var quadraticDerivativeAt$1 = quadraticDerivativeAt;
  56401. pos[0] = quadraticAt$1(p1[0], cp1[0], p2[0], t);
  56402. pos[1] = quadraticAt$1(p1[1], cp1[1], p2[1], t); // Tangent
  56403. var tx = quadraticDerivativeAt$1(p1[0], cp1[0], p2[0], t);
  56404. var ty = quadraticDerivativeAt$1(p1[1], cp1[1], p2[1], t);
  56405. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  56406. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  56407. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  56408. symbol.scaleY = dist(lastPos, pos) * 1.05; // make sure the last segment render within endPoint
  56409. if (t === 1) {
  56410. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  56411. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  56412. }
  56413. } else if (symbol.__lastT === 1) {
  56414. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  56415. symbol.scaleY = 2 * dist(p1, pos);
  56416. } else {
  56417. symbol.scaleY = this._symbolScale[1];
  56418. }
  56419. }
  56420. symbol.__lastT = symbol.__t;
  56421. symbol.ignore = false;
  56422. symbol.x = pos[0];
  56423. symbol.y = pos[1];
  56424. };
  56425. EffectLine.prototype.updateLayout = function (lineData, idx) {
  56426. this.childAt(0).updateLayout(lineData, idx);
  56427. var effectModel = lineData.getItemModel(idx).getModel('effect');
  56428. this._updateEffectAnimation(lineData, effectModel, idx);
  56429. };
  56430. return EffectLine;
  56431. }(Group);
  56432. var Polyline$1 =
  56433. /** @class */
  56434. function (_super) {
  56435. __extends(Polyline$1, _super);
  56436. function Polyline$1(lineData, idx, seriesScope) {
  56437. var _this = _super.call(this) || this;
  56438. _this._createPolyline(lineData, idx, seriesScope);
  56439. return _this;
  56440. }
  56441. Polyline$1.prototype._createPolyline = function (lineData, idx, seriesScope) {
  56442. // let seriesModel = lineData.hostModel;
  56443. var points = lineData.getItemLayout(idx);
  56444. var line = new Polyline({
  56445. shape: {
  56446. points: points
  56447. }
  56448. });
  56449. this.add(line);
  56450. this._updateCommonStl(lineData, idx, seriesScope);
  56451. };
  56452. Polyline$1.prototype.updateData = function (lineData, idx, seriesScope) {
  56453. var seriesModel = lineData.hostModel;
  56454. var line = this.childAt(0);
  56455. var target = {
  56456. shape: {
  56457. points: lineData.getItemLayout(idx)
  56458. }
  56459. };
  56460. updateProps(line, target, seriesModel, idx);
  56461. this._updateCommonStl(lineData, idx, seriesScope);
  56462. };
  56463. Polyline$1.prototype._updateCommonStl = function (lineData, idx, seriesScope) {
  56464. var line = this.childAt(0);
  56465. var itemModel = lineData.getItemModel(idx);
  56466. var hoverLineStyle = seriesScope && seriesScope.emphasisLineStyle;
  56467. if (!seriesScope || lineData.hasItemOption) {
  56468. hoverLineStyle = itemModel.getModel(['emphasis', 'lineStyle']).getLineStyle();
  56469. }
  56470. line.useStyle(lineData.getItemVisual(idx, 'style'));
  56471. line.style.fill = null;
  56472. line.style.strokeNoScale = true;
  56473. var lineEmphasisState = line.ensureState('emphasis');
  56474. lineEmphasisState.style = hoverLineStyle;
  56475. enableHoverEmphasis(this);
  56476. };
  56477. Polyline$1.prototype.updateLayout = function (lineData, idx) {
  56478. var polyline = this.childAt(0);
  56479. polyline.setShape('points', lineData.getItemLayout(idx));
  56480. };
  56481. return Polyline$1;
  56482. }(Group);
  56483. var EffectPolyline =
  56484. /** @class */
  56485. function (_super) {
  56486. __extends(EffectPolyline, _super);
  56487. function EffectPolyline() {
  56488. var _this = _super !== null && _super.apply(this, arguments) || this;
  56489. _this._lastFrame = 0;
  56490. _this._lastFramePercent = 0;
  56491. return _this;
  56492. } // Override
  56493. EffectPolyline.prototype.createLine = function (lineData, idx, seriesScope) {
  56494. return new Polyline$1(lineData, idx, seriesScope);
  56495. };
  56496. EffectPolyline.prototype._updateAnimationPoints = function (symbol, points) {
  56497. this._points = points;
  56498. var accLenArr = [0];
  56499. var len = 0;
  56500. for (var i = 1; i < points.length; i++) {
  56501. var p1 = points[i - 1];
  56502. var p2 = points[i];
  56503. len += dist(p1, p2);
  56504. accLenArr.push(len);
  56505. }
  56506. if (len === 0) {
  56507. this._length = 0;
  56508. return;
  56509. }
  56510. for (var i = 0; i < accLenArr.length; i++) {
  56511. accLenArr[i] /= len;
  56512. }
  56513. this._offsets = accLenArr;
  56514. this._length = len;
  56515. };
  56516. EffectPolyline.prototype._getLineLength = function () {
  56517. return this._length;
  56518. };
  56519. EffectPolyline.prototype._updateSymbolPosition = function (symbol) {
  56520. var t = symbol.__t;
  56521. var points = this._points;
  56522. var offsets = this._offsets;
  56523. var len = points.length;
  56524. if (!offsets) {
  56525. // Has length 0
  56526. return;
  56527. }
  56528. var lastFrame = this._lastFrame;
  56529. var frame;
  56530. if (t < this._lastFramePercent) {
  56531. // Start from the next frame
  56532. // PENDING start from lastFrame ?
  56533. var start = Math.min(lastFrame + 1, len - 1);
  56534. for (frame = start; frame >= 0; frame--) {
  56535. if (offsets[frame] <= t) {
  56536. break;
  56537. }
  56538. } // PENDING really need to do this ?
  56539. frame = Math.min(frame, len - 2);
  56540. } else {
  56541. for (frame = lastFrame; frame < len; frame++) {
  56542. if (offsets[frame] > t) {
  56543. break;
  56544. }
  56545. }
  56546. frame = Math.min(frame - 1, len - 2);
  56547. }
  56548. var p = (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]);
  56549. var p0 = points[frame];
  56550. var p1 = points[frame + 1];
  56551. symbol.x = p0[0] * (1 - p) + p * p1[0];
  56552. symbol.y = p0[1] * (1 - p) + p * p1[1];
  56553. var tx = p1[0] - p0[0];
  56554. var ty = p1[1] - p0[1];
  56555. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  56556. this._lastFrame = frame;
  56557. this._lastFramePercent = t;
  56558. symbol.ignore = false;
  56559. };
  56560. return EffectPolyline;
  56561. }(EffectLine);
  56562. var LargeLinesPathShape =
  56563. /** @class */
  56564. function () {
  56565. function LargeLinesPathShape() {
  56566. this.polyline = false;
  56567. this.curveness = 0;
  56568. this.segs = [];
  56569. }
  56570. return LargeLinesPathShape;
  56571. }();
  56572. var LargeLinesPath =
  56573. /** @class */
  56574. function (_super) {
  56575. __extends(LargeLinesPath, _super);
  56576. function LargeLinesPath(opts) {
  56577. return _super.call(this, opts) || this;
  56578. }
  56579. LargeLinesPath.prototype.getDefaultStyle = function () {
  56580. return {
  56581. stroke: '#000',
  56582. fill: null
  56583. };
  56584. };
  56585. LargeLinesPath.prototype.getDefaultShape = function () {
  56586. return new LargeLinesPathShape();
  56587. };
  56588. LargeLinesPath.prototype.buildPath = function (ctx, shape) {
  56589. var segs = shape.segs;
  56590. var curveness = shape.curveness;
  56591. if (shape.polyline) {
  56592. for (var i = 0; i < segs.length;) {
  56593. var count = segs[i++];
  56594. if (count > 0) {
  56595. ctx.moveTo(segs[i++], segs[i++]);
  56596. for (var k = 1; k < count; k++) {
  56597. ctx.lineTo(segs[i++], segs[i++]);
  56598. }
  56599. }
  56600. }
  56601. } else {
  56602. for (var i = 0; i < segs.length;) {
  56603. var x0 = segs[i++];
  56604. var y0 = segs[i++];
  56605. var x1 = segs[i++];
  56606. var y1 = segs[i++];
  56607. ctx.moveTo(x0, y0);
  56608. if (curveness > 0) {
  56609. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  56610. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  56611. ctx.quadraticCurveTo(x2, y2, x1, y1);
  56612. } else {
  56613. ctx.lineTo(x1, y1);
  56614. }
  56615. }
  56616. }
  56617. };
  56618. LargeLinesPath.prototype.findDataIndex = function (x, y) {
  56619. var shape = this.shape;
  56620. var segs = shape.segs;
  56621. var curveness = shape.curveness;
  56622. var lineWidth = this.style.lineWidth;
  56623. if (shape.polyline) {
  56624. var dataIndex = 0;
  56625. for (var i = 0; i < segs.length;) {
  56626. var count = segs[i++];
  56627. if (count > 0) {
  56628. var x0 = segs[i++];
  56629. var y0 = segs[i++];
  56630. for (var k = 1; k < count; k++) {
  56631. var x1 = segs[i++];
  56632. var y1 = segs[i++];
  56633. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  56634. return dataIndex;
  56635. }
  56636. }
  56637. }
  56638. dataIndex++;
  56639. }
  56640. } else {
  56641. var dataIndex = 0;
  56642. for (var i = 0; i < segs.length;) {
  56643. var x0 = segs[i++];
  56644. var y0 = segs[i++];
  56645. var x1 = segs[i++];
  56646. var y1 = segs[i++];
  56647. if (curveness > 0) {
  56648. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  56649. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  56650. if (containStroke$2(x0, y0, x2, y2, x1, y1, lineWidth, x, y)) {
  56651. return dataIndex;
  56652. }
  56653. } else {
  56654. if (containStroke(x0, y0, x1, y1, lineWidth, x, y)) {
  56655. return dataIndex;
  56656. }
  56657. }
  56658. dataIndex++;
  56659. }
  56660. }
  56661. return -1;
  56662. };
  56663. return LargeLinesPath;
  56664. }(Path);
  56665. var LargeLineDraw =
  56666. /** @class */
  56667. function () {
  56668. function LargeLineDraw() {
  56669. this.group = new Group();
  56670. }
  56671. LargeLineDraw.prototype.isPersistent = function () {
  56672. return !this._incremental;
  56673. };
  56674. /**
  56675. * Update symbols draw by new data
  56676. */
  56677. LargeLineDraw.prototype.updateData = function (data) {
  56678. this.group.removeAll();
  56679. var lineEl = new LargeLinesPath({
  56680. rectHover: true,
  56681. cursor: 'default'
  56682. });
  56683. lineEl.setShape({
  56684. segs: data.getLayout('linesPoints')
  56685. });
  56686. this._setCommon(lineEl, data); // Add back
  56687. this.group.add(lineEl);
  56688. this._incremental = null;
  56689. };
  56690. /**
  56691. * @override
  56692. */
  56693. LargeLineDraw.prototype.incrementalPrepareUpdate = function (data) {
  56694. this.group.removeAll();
  56695. this._clearIncremental();
  56696. if (data.count() > 5e5) {
  56697. if (!this._incremental) {
  56698. this._incremental = new IncrementalDisplayable({
  56699. silent: true
  56700. });
  56701. }
  56702. this.group.add(this._incremental);
  56703. } else {
  56704. this._incremental = null;
  56705. }
  56706. };
  56707. /**
  56708. * @override
  56709. */
  56710. LargeLineDraw.prototype.incrementalUpdate = function (taskParams, data) {
  56711. var lineEl = new LargeLinesPath();
  56712. lineEl.setShape({
  56713. segs: data.getLayout('linesPoints')
  56714. });
  56715. this._setCommon(lineEl, data, !!this._incremental);
  56716. if (!this._incremental) {
  56717. lineEl.rectHover = true;
  56718. lineEl.cursor = 'default';
  56719. lineEl.__startIndex = taskParams.start;
  56720. this.group.add(lineEl);
  56721. } else {
  56722. this._incremental.addDisplayable(lineEl, true);
  56723. }
  56724. };
  56725. /**
  56726. * @override
  56727. */
  56728. LargeLineDraw.prototype.remove = function () {
  56729. this._clearIncremental();
  56730. this._incremental = null;
  56731. this.group.removeAll();
  56732. };
  56733. LargeLineDraw.prototype._setCommon = function (lineEl, data, isIncremental) {
  56734. var hostModel = data.hostModel;
  56735. lineEl.setShape({
  56736. polyline: hostModel.get('polyline'),
  56737. curveness: hostModel.get(['lineStyle', 'curveness'])
  56738. });
  56739. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  56740. lineEl.style.strokeNoScale = true;
  56741. var style = data.getVisual('style');
  56742. if (style && style.stroke) {
  56743. lineEl.setStyle('stroke', style.stroke);
  56744. }
  56745. lineEl.setStyle('fill', null);
  56746. if (!isIncremental) {
  56747. var ecData_1 = getECData(lineEl); // Enable tooltip
  56748. // PENDING May have performance issue when path is extremely large
  56749. ecData_1.seriesIndex = hostModel.seriesIndex;
  56750. lineEl.on('mousemove', function (e) {
  56751. ecData_1.dataIndex = null;
  56752. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  56753. if (dataIndex > 0) {
  56754. // Provide dataIndex for tooltip
  56755. ecData_1.dataIndex = dataIndex + lineEl.__startIndex;
  56756. }
  56757. });
  56758. }
  56759. };
  56760. LargeLineDraw.prototype._clearIncremental = function () {
  56761. var incremental = this._incremental;
  56762. if (incremental) {
  56763. incremental.clearDisplaybles();
  56764. }
  56765. };
  56766. return LargeLineDraw;
  56767. }();
  56768. var linesLayout = {
  56769. seriesType: 'lines',
  56770. plan: createRenderPlanner(),
  56771. reset: function (seriesModel) {
  56772. var coordSys = seriesModel.coordinateSystem;
  56773. var isPolyline = seriesModel.get('polyline');
  56774. var isLarge = seriesModel.pipelineContext.large;
  56775. return {
  56776. progress: function (params, lineData) {
  56777. var lineCoords = [];
  56778. if (isLarge) {
  56779. var points = void 0;
  56780. var segCount = params.end - params.start;
  56781. if (isPolyline) {
  56782. var totalCoordsCount = 0;
  56783. for (var i = params.start; i < params.end; i++) {
  56784. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  56785. }
  56786. points = new Float32Array(segCount + totalCoordsCount * 2);
  56787. } else {
  56788. points = new Float32Array(segCount * 4);
  56789. }
  56790. var offset = 0;
  56791. var pt = [];
  56792. for (var i = params.start; i < params.end; i++) {
  56793. var len = seriesModel.getLineCoords(i, lineCoords);
  56794. if (isPolyline) {
  56795. points[offset++] = len;
  56796. }
  56797. for (var k = 0; k < len; k++) {
  56798. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  56799. points[offset++] = pt[0];
  56800. points[offset++] = pt[1];
  56801. }
  56802. }
  56803. lineData.setLayout('linesPoints', points);
  56804. } else {
  56805. for (var i = params.start; i < params.end; i++) {
  56806. var itemModel = lineData.getItemModel(i);
  56807. var len = seriesModel.getLineCoords(i, lineCoords);
  56808. var pts = [];
  56809. if (isPolyline) {
  56810. for (var j = 0; j < len; j++) {
  56811. pts.push(coordSys.dataToPoint(lineCoords[j]));
  56812. }
  56813. } else {
  56814. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  56815. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  56816. var curveness = itemModel.get(['lineStyle', 'curveness']);
  56817. if (+curveness) {
  56818. 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];
  56819. }
  56820. }
  56821. lineData.setItemLayout(i, pts);
  56822. }
  56823. }
  56824. }
  56825. };
  56826. }
  56827. };
  56828. var LinesView =
  56829. /** @class */
  56830. function (_super) {
  56831. __extends(LinesView, _super);
  56832. function LinesView() {
  56833. var _this = _super !== null && _super.apply(this, arguments) || this;
  56834. _this.type = LinesView.type;
  56835. return _this;
  56836. }
  56837. LinesView.prototype.render = function (seriesModel, ecModel, api) {
  56838. var data = seriesModel.getData();
  56839. var lineDraw = this._updateLineDraw(data, seriesModel);
  56840. var zlevel = seriesModel.get('zlevel');
  56841. var trailLength = seriesModel.get(['effect', 'trailLength']);
  56842. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  56843. // FIXME Better way ?
  56844. // SVG doesn't support
  56845. var isSvg = zr.painter.getType() === 'svg';
  56846. if (!isSvg) {
  56847. zr.painter.getLayer(zlevel).clear(true);
  56848. } // Config layer with motion blur
  56849. if (this._lastZlevel != null && !isSvg) {
  56850. zr.configLayer(this._lastZlevel, {
  56851. motionBlur: false
  56852. });
  56853. }
  56854. if (this._showEffect(seriesModel) && trailLength) {
  56855. if ("development" !== 'production') {
  56856. var notInIndividual_1 = false;
  56857. ecModel.eachSeries(function (otherSeriesModel) {
  56858. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  56859. notInIndividual_1 = true;
  56860. }
  56861. });
  56862. notInIndividual_1 && console.warn('Lines with trail effect should have an individual zlevel');
  56863. }
  56864. if (!isSvg) {
  56865. zr.configLayer(zlevel, {
  56866. motionBlur: true,
  56867. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  56868. });
  56869. }
  56870. }
  56871. lineDraw.updateData(data);
  56872. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  56873. if (clipPath) {
  56874. this.group.setClipPath(clipPath);
  56875. } else {
  56876. this.group.removeClipPath();
  56877. }
  56878. this._lastZlevel = zlevel;
  56879. this._finished = true;
  56880. };
  56881. LinesView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  56882. var data = seriesModel.getData();
  56883. var lineDraw = this._updateLineDraw(data, seriesModel);
  56884. lineDraw.incrementalPrepareUpdate(data);
  56885. this._clearLayer(api);
  56886. this._finished = false;
  56887. };
  56888. LinesView.prototype.incrementalRender = function (taskParams, seriesModel, ecModel) {
  56889. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  56890. this._finished = taskParams.end === seriesModel.getData().count();
  56891. };
  56892. LinesView.prototype.updateTransform = function (seriesModel, ecModel, api) {
  56893. var data = seriesModel.getData();
  56894. var pipelineContext = seriesModel.pipelineContext;
  56895. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  56896. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  56897. return {
  56898. update: true
  56899. };
  56900. } else {
  56901. // TODO Use same logic with ScatterView.
  56902. // Manually update layout
  56903. var res = linesLayout.reset(seriesModel, ecModel, api);
  56904. if (res.progress) {
  56905. res.progress({
  56906. start: 0,
  56907. end: data.count(),
  56908. count: data.count()
  56909. }, data);
  56910. } // Not in large mode
  56911. this._lineDraw.updateLayout();
  56912. this._clearLayer(api);
  56913. }
  56914. };
  56915. LinesView.prototype._updateLineDraw = function (data, seriesModel) {
  56916. var lineDraw = this._lineDraw;
  56917. var hasEffect = this._showEffect(seriesModel);
  56918. var isPolyline = !!seriesModel.get('polyline');
  56919. var pipelineContext = seriesModel.pipelineContext;
  56920. var isLargeDraw = pipelineContext.large;
  56921. if ("development" !== 'production') {
  56922. if (hasEffect && isLargeDraw) {
  56923. console.warn('Large lines not support effect');
  56924. }
  56925. }
  56926. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  56927. if (lineDraw) {
  56928. lineDraw.remove();
  56929. }
  56930. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$1 : hasEffect ? EffectLine : Line$1);
  56931. this._hasEffet = hasEffect;
  56932. this._isPolyline = isPolyline;
  56933. this._isLargeDraw = isLargeDraw;
  56934. this.group.removeAll();
  56935. }
  56936. this.group.add(lineDraw.group);
  56937. return lineDraw;
  56938. };
  56939. LinesView.prototype._showEffect = function (seriesModel) {
  56940. return !!seriesModel.get(['effect', 'show']);
  56941. };
  56942. LinesView.prototype._clearLayer = function (api) {
  56943. // Not use motion when dragging or zooming
  56944. var zr = api.getZr();
  56945. var isSvg = zr.painter.getType() === 'svg';
  56946. if (!isSvg && this._lastZlevel != null) {
  56947. zr.painter.getLayer(this._lastZlevel).clear(true);
  56948. }
  56949. };
  56950. LinesView.prototype.remove = function (ecModel, api) {
  56951. this._lineDraw && this._lineDraw.remove();
  56952. this._lineDraw = null; // Clear motion when lineDraw is removed
  56953. this._clearLayer(api);
  56954. };
  56955. LinesView.type = 'lines';
  56956. return LinesView;
  56957. }(ChartView);
  56958. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  56959. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  56960. function compatEc2(seriesOpt) {
  56961. var data = seriesOpt.data;
  56962. if (data && data[0] && data[0][0] && data[0][0].coord) {
  56963. if ("development" !== 'production') {
  56964. console.warn('Lines data configuration has been changed to' + ' { coords:[[1,2],[2,3]] }');
  56965. }
  56966. seriesOpt.data = map(data, function (itemOpt) {
  56967. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  56968. var target = {
  56969. coords: coords
  56970. };
  56971. if (itemOpt[0].name) {
  56972. target.fromName = itemOpt[0].name;
  56973. }
  56974. if (itemOpt[1].name) {
  56975. target.toName = itemOpt[1].name;
  56976. }
  56977. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  56978. });
  56979. }
  56980. }
  56981. var LinesSeriesModel =
  56982. /** @class */
  56983. function (_super) {
  56984. __extends(LinesSeriesModel, _super);
  56985. function LinesSeriesModel() {
  56986. var _this = _super !== null && _super.apply(this, arguments) || this;
  56987. _this.type = LinesSeriesModel.type;
  56988. _this.visualStyleAccessPath = 'lineStyle';
  56989. _this.visualDrawType = 'stroke';
  56990. return _this;
  56991. }
  56992. LinesSeriesModel.prototype.init = function (option) {
  56993. // The input data may be null/undefined.
  56994. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  56995. compatEc2(option);
  56996. var result = this._processFlatCoordsArray(option.data);
  56997. this._flatCoords = result.flatCoords;
  56998. this._flatCoordsOffset = result.flatCoordsOffset;
  56999. if (result.flatCoords) {
  57000. option.data = new Float32Array(result.count);
  57001. }
  57002. _super.prototype.init.apply(this, arguments);
  57003. };
  57004. LinesSeriesModel.prototype.mergeOption = function (option) {
  57005. compatEc2(option);
  57006. if (option.data) {
  57007. // Only update when have option data to merge.
  57008. var result = this._processFlatCoordsArray(option.data);
  57009. this._flatCoords = result.flatCoords;
  57010. this._flatCoordsOffset = result.flatCoordsOffset;
  57011. if (result.flatCoords) {
  57012. option.data = new Float32Array(result.count);
  57013. }
  57014. }
  57015. _super.prototype.mergeOption.apply(this, arguments);
  57016. };
  57017. LinesSeriesModel.prototype.appendData = function (params) {
  57018. var result = this._processFlatCoordsArray(params.data);
  57019. if (result.flatCoords) {
  57020. if (!this._flatCoords) {
  57021. this._flatCoords = result.flatCoords;
  57022. this._flatCoordsOffset = result.flatCoordsOffset;
  57023. } else {
  57024. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  57025. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  57026. }
  57027. params.data = new Float32Array(result.count);
  57028. }
  57029. this.getRawData().appendData(params.data);
  57030. };
  57031. LinesSeriesModel.prototype._getCoordsFromItemModel = function (idx) {
  57032. var itemModel = this.getData().getItemModel(idx);
  57033. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  57034. if ("development" !== 'production') {
  57035. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  57036. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  57037. }
  57038. }
  57039. return coords;
  57040. };
  57041. LinesSeriesModel.prototype.getLineCoordsCount = function (idx) {
  57042. if (this._flatCoordsOffset) {
  57043. return this._flatCoordsOffset[idx * 2 + 1];
  57044. } else {
  57045. return this._getCoordsFromItemModel(idx).length;
  57046. }
  57047. };
  57048. LinesSeriesModel.prototype.getLineCoords = function (idx, out) {
  57049. if (this._flatCoordsOffset) {
  57050. var offset = this._flatCoordsOffset[idx * 2];
  57051. var len = this._flatCoordsOffset[idx * 2 + 1];
  57052. for (var i = 0; i < len; i++) {
  57053. out[i] = out[i] || [];
  57054. out[i][0] = this._flatCoords[offset + i * 2];
  57055. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  57056. }
  57057. return len;
  57058. } else {
  57059. var coords = this._getCoordsFromItemModel(idx);
  57060. for (var i = 0; i < coords.length; i++) {
  57061. out[i] = out[i] || [];
  57062. out[i][0] = coords[i][0];
  57063. out[i][1] = coords[i][1];
  57064. }
  57065. return coords.length;
  57066. }
  57067. };
  57068. LinesSeriesModel.prototype._processFlatCoordsArray = function (data) {
  57069. var startOffset = 0;
  57070. if (this._flatCoords) {
  57071. startOffset = this._flatCoords.length;
  57072. } // Stored as a typed array. In format
  57073. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  57074. if (typeof data[0] === 'number') {
  57075. var len = data.length; // Store offset and len of each segment
  57076. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  57077. var coordsStorage = new Float64Arr(len);
  57078. var coordsCursor = 0;
  57079. var offsetCursor = 0;
  57080. var dataCount = 0;
  57081. for (var i = 0; i < len;) {
  57082. dataCount++;
  57083. var count = data[i++]; // Offset
  57084. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  57085. coordsOffsetAndLenStorage[offsetCursor++] = count;
  57086. for (var k = 0; k < count; k++) {
  57087. var x = data[i++];
  57088. var y = data[i++];
  57089. coordsStorage[coordsCursor++] = x;
  57090. coordsStorage[coordsCursor++] = y;
  57091. if (i > len) {
  57092. if ("development" !== 'production') {
  57093. throw new Error('Invalid data format.');
  57094. }
  57095. }
  57096. }
  57097. }
  57098. return {
  57099. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  57100. flatCoords: coordsStorage,
  57101. count: dataCount
  57102. };
  57103. }
  57104. return {
  57105. flatCoordsOffset: null,
  57106. flatCoords: null,
  57107. count: data.length
  57108. };
  57109. };
  57110. LinesSeriesModel.prototype.getInitialData = function (option, ecModel) {
  57111. if ("development" !== 'production') {
  57112. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  57113. if (!CoordSys) {
  57114. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  57115. }
  57116. }
  57117. var lineData = new List(['value'], this);
  57118. lineData.hasItemOption = false;
  57119. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  57120. // dataItem is simply coords
  57121. if (dataItem instanceof Array) {
  57122. return NaN;
  57123. } else {
  57124. lineData.hasItemOption = true;
  57125. var value = dataItem.value;
  57126. if (value != null) {
  57127. return value instanceof Array ? value[dimIndex] : value;
  57128. }
  57129. }
  57130. });
  57131. return lineData;
  57132. };
  57133. LinesSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  57134. var data = this.getData();
  57135. var itemModel = data.getItemModel(dataIndex);
  57136. var name = itemModel.get('name');
  57137. if (name) {
  57138. return name;
  57139. }
  57140. var fromName = itemModel.get('fromName');
  57141. var toName = itemModel.get('toName');
  57142. var nameArr = [];
  57143. fromName != null && nameArr.push(fromName);
  57144. toName != null && nameArr.push(toName);
  57145. return createTooltipMarkup('nameValue', {
  57146. name: nameArr.join(' > ')
  57147. });
  57148. };
  57149. LinesSeriesModel.prototype.preventIncremental = function () {
  57150. return !!this.get(['effect', 'show']);
  57151. };
  57152. LinesSeriesModel.prototype.getProgressive = function () {
  57153. var progressive = this.option.progressive;
  57154. if (progressive == null) {
  57155. return this.option.large ? 1e4 : this.get('progressive');
  57156. }
  57157. return progressive;
  57158. };
  57159. LinesSeriesModel.prototype.getProgressiveThreshold = function () {
  57160. var progressiveThreshold = this.option.progressiveThreshold;
  57161. if (progressiveThreshold == null) {
  57162. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  57163. }
  57164. return progressiveThreshold;
  57165. };
  57166. LinesSeriesModel.type = 'series.lines';
  57167. LinesSeriesModel.dependencies = ['grid', 'polar', 'geo', 'calendar'];
  57168. LinesSeriesModel.defaultOption = {
  57169. coordinateSystem: 'geo',
  57170. zlevel: 0,
  57171. z: 2,
  57172. legendHoverLink: true,
  57173. // Cartesian coordinate system
  57174. xAxisIndex: 0,
  57175. yAxisIndex: 0,
  57176. symbol: ['none', 'none'],
  57177. symbolSize: [10, 10],
  57178. // Geo coordinate system
  57179. geoIndex: 0,
  57180. effect: {
  57181. show: false,
  57182. period: 4,
  57183. constantSpeed: 0,
  57184. symbol: 'circle',
  57185. symbolSize: 3,
  57186. loop: true,
  57187. trailLength: 0.2
  57188. },
  57189. large: false,
  57190. // Available when large is true
  57191. largeThreshold: 2000,
  57192. polyline: false,
  57193. clip: true,
  57194. label: {
  57195. show: false,
  57196. position: 'end' // distance: 5,
  57197. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  57198. },
  57199. lineStyle: {
  57200. opacity: 0.5
  57201. }
  57202. };
  57203. return LinesSeriesModel;
  57204. }(SeriesModel);
  57205. /*
  57206. * Licensed to the Apache Software Foundation (ASF) under one
  57207. * or more contributor license agreements. See the NOTICE file
  57208. * distributed with this work for additional information
  57209. * regarding copyright ownership. The ASF licenses this file
  57210. * to you under the Apache License, Version 2.0 (the
  57211. * "License"); you may not use this file except in compliance
  57212. * with the License. You may obtain a copy of the License at
  57213. *
  57214. * http://www.apache.org/licenses/LICENSE-2.0
  57215. *
  57216. * Unless required by applicable law or agreed to in writing,
  57217. * software distributed under the License is distributed on an
  57218. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57219. * KIND, either express or implied. See the License for the
  57220. * specific language governing permissions and limitations
  57221. * under the License.
  57222. */
  57223. /**
  57224. * AUTO-GENERATED FILE. DO NOT MODIFY.
  57225. */
  57226. /*
  57227. * Licensed to the Apache Software Foundation (ASF) under one
  57228. * or more contributor license agreements. See the NOTICE file
  57229. * distributed with this work for additional information
  57230. * regarding copyright ownership. The ASF licenses this file
  57231. * to you under the Apache License, Version 2.0 (the
  57232. * "License"); you may not use this file except in compliance
  57233. * with the License. You may obtain a copy of the License at
  57234. *
  57235. * http://www.apache.org/licenses/LICENSE-2.0
  57236. *
  57237. * Unless required by applicable law or agreed to in writing,
  57238. * software distributed under the License is distributed on an
  57239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57240. * KIND, either express or implied. See the License for the
  57241. * specific language governing permissions and limitations
  57242. * under the License.
  57243. */
  57244. function normalize$3(a) {
  57245. if (!(a instanceof Array)) {
  57246. a = [a, a];
  57247. }
  57248. return a;
  57249. }
  57250. var linesVisual = {
  57251. seriesType: 'lines',
  57252. reset: function (seriesModel) {
  57253. var symbolType = normalize$3(seriesModel.get('symbol'));
  57254. var symbolSize = normalize$3(seriesModel.get('symbolSize'));
  57255. var data = seriesModel.getData();
  57256. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  57257. data.setVisual('toSymbol', symbolType && symbolType[1]);
  57258. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  57259. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  57260. function dataEach(data, idx) {
  57261. var itemModel = data.getItemModel(idx);
  57262. var symbolType = normalize$3(itemModel.getShallow('symbol', true));
  57263. var symbolSize = normalize$3(itemModel.getShallow('symbolSize', true));
  57264. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  57265. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  57266. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  57267. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  57268. }
  57269. return {
  57270. dataEach: data.hasItemOption ? dataEach : null
  57271. };
  57272. }
  57273. };
  57274. function install$m(registers) {
  57275. registers.registerChartView(LinesView);
  57276. registers.registerSeriesModel(LinesSeriesModel);
  57277. registers.registerLayout(linesLayout);
  57278. registers.registerVisual(linesVisual);
  57279. }
  57280. var GRADIENT_LEVELS = 256;
  57281. var HeatmapLayer =
  57282. /** @class */
  57283. function () {
  57284. function HeatmapLayer() {
  57285. this.blurSize = 30;
  57286. this.pointSize = 20;
  57287. this.maxOpacity = 1;
  57288. this.minOpacity = 0;
  57289. this._gradientPixels = {
  57290. inRange: null,
  57291. outOfRange: null
  57292. };
  57293. var canvas = createCanvas();
  57294. this.canvas = canvas;
  57295. }
  57296. /**
  57297. * Renders Heatmap and returns the rendered canvas
  57298. * @param data array of data, each has x, y, value
  57299. * @param width canvas width
  57300. * @param height canvas height
  57301. */
  57302. HeatmapLayer.prototype.update = function (data, width, height, normalize, colorFunc, isInRange) {
  57303. var brush = this._getBrush();
  57304. var gradientInRange = this._getGradient(colorFunc, 'inRange');
  57305. var gradientOutOfRange = this._getGradient(colorFunc, 'outOfRange');
  57306. var r = this.pointSize + this.blurSize;
  57307. var canvas = this.canvas;
  57308. var ctx = canvas.getContext('2d');
  57309. var len = data.length;
  57310. canvas.width = width;
  57311. canvas.height = height;
  57312. for (var i = 0; i < len; ++i) {
  57313. var p = data[i];
  57314. var x = p[0];
  57315. var y = p[1];
  57316. var value = p[2]; // calculate alpha using value
  57317. var alpha = normalize(value); // draw with the circle brush with alpha
  57318. ctx.globalAlpha = alpha;
  57319. ctx.drawImage(brush, x - r, y - r);
  57320. }
  57321. if (!canvas.width || !canvas.height) {
  57322. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  57323. // 'CanvasRenderingContext2D': The source height is 0."
  57324. return canvas;
  57325. } // colorize the canvas using alpha value and set with gradient
  57326. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  57327. var pixels = imageData.data;
  57328. var offset = 0;
  57329. var pixelLen = pixels.length;
  57330. var minOpacity = this.minOpacity;
  57331. var maxOpacity = this.maxOpacity;
  57332. var diffOpacity = maxOpacity - minOpacity;
  57333. while (offset < pixelLen) {
  57334. var alpha = pixels[offset + 3] / 256;
  57335. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  57336. if (alpha > 0) {
  57337. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  57338. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  57339. pixels[offset++] = gradient[gradientOffset];
  57340. pixels[offset++] = gradient[gradientOffset + 1];
  57341. pixels[offset++] = gradient[gradientOffset + 2];
  57342. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  57343. } else {
  57344. offset += 4;
  57345. }
  57346. }
  57347. ctx.putImageData(imageData, 0, 0);
  57348. return canvas;
  57349. };
  57350. /**
  57351. * get canvas of a black circle brush used for canvas to draw later
  57352. */
  57353. HeatmapLayer.prototype._getBrush = function () {
  57354. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas()); // set brush size
  57355. var r = this.pointSize + this.blurSize;
  57356. var d = r * 2;
  57357. brushCanvas.width = d;
  57358. brushCanvas.height = d;
  57359. var ctx = brushCanvas.getContext('2d');
  57360. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  57361. // draw the distinct circle in an invisible place,
  57362. // and use shadowOffset to draw shadow in the center of the canvas
  57363. ctx.shadowOffsetX = d;
  57364. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  57365. // color in color map
  57366. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  57367. ctx.beginPath();
  57368. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  57369. ctx.closePath();
  57370. ctx.fill();
  57371. return brushCanvas;
  57372. };
  57373. /**
  57374. * get gradient color map
  57375. * @private
  57376. */
  57377. HeatmapLayer.prototype._getGradient = function (colorFunc, state) {
  57378. var gradientPixels = this._gradientPixels;
  57379. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  57380. var color = [0, 0, 0, 0];
  57381. var off = 0;
  57382. for (var i = 0; i < 256; i++) {
  57383. colorFunc[state](i / 255, true, color);
  57384. pixelsSingleState[off++] = color[0];
  57385. pixelsSingleState[off++] = color[1];
  57386. pixelsSingleState[off++] = color[2];
  57387. pixelsSingleState[off++] = color[3];
  57388. }
  57389. return pixelsSingleState;
  57390. };
  57391. return HeatmapLayer;
  57392. }();
  57393. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  57394. var dataSpan = dataExtent[1] - dataExtent[0];
  57395. pieceList = map(pieceList, function (piece) {
  57396. return {
  57397. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  57398. };
  57399. });
  57400. var len = pieceList.length;
  57401. var lastIndex = 0;
  57402. return function (val) {
  57403. var i; // Try to find in the location of the last found
  57404. for (i = lastIndex; i < len; i++) {
  57405. var interval = pieceList[i].interval;
  57406. if (interval[0] <= val && val <= interval[1]) {
  57407. lastIndex = i;
  57408. break;
  57409. }
  57410. }
  57411. if (i === len) {
  57412. // Not found, back interation
  57413. for (i = lastIndex - 1; i >= 0; i--) {
  57414. var interval = pieceList[i].interval;
  57415. if (interval[0] <= val && val <= interval[1]) {
  57416. lastIndex = i;
  57417. break;
  57418. }
  57419. }
  57420. }
  57421. return i >= 0 && i < len && selected[i];
  57422. };
  57423. }
  57424. function getIsInContinuousRange(dataExtent, range) {
  57425. var dataSpan = dataExtent[1] - dataExtent[0];
  57426. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  57427. return function (val) {
  57428. return val >= range[0] && val <= range[1];
  57429. };
  57430. }
  57431. function isGeoCoordSys(coordSys) {
  57432. var dimensions = coordSys.dimensions; // Not use coorSys.type === 'geo' because coordSys maybe extended
  57433. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  57434. }
  57435. var HeatmapView =
  57436. /** @class */
  57437. function (_super) {
  57438. __extends(HeatmapView, _super);
  57439. function HeatmapView() {
  57440. var _this = _super !== null && _super.apply(this, arguments) || this;
  57441. _this.type = HeatmapView.type;
  57442. return _this;
  57443. }
  57444. HeatmapView.prototype.render = function (seriesModel, ecModel, api) {
  57445. var visualMapOfThisSeries;
  57446. ecModel.eachComponent('visualMap', function (visualMap) {
  57447. visualMap.eachTargetSeries(function (targetSeries) {
  57448. if (targetSeries === seriesModel) {
  57449. visualMapOfThisSeries = visualMap;
  57450. }
  57451. });
  57452. });
  57453. if ("development" !== 'production') {
  57454. if (!visualMapOfThisSeries) {
  57455. throw new Error('Heatmap must use with visualMap');
  57456. }
  57457. }
  57458. this.group.removeAll();
  57459. this._incrementalDisplayable = null;
  57460. var coordSys = seriesModel.coordinateSystem;
  57461. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  57462. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  57463. } else if (isGeoCoordSys(coordSys)) {
  57464. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  57465. }
  57466. };
  57467. HeatmapView.prototype.incrementalPrepareRender = function (seriesModel, ecModel, api) {
  57468. this.group.removeAll();
  57469. };
  57470. HeatmapView.prototype.incrementalRender = function (params, seriesModel, ecModel, api) {
  57471. var coordSys = seriesModel.coordinateSystem;
  57472. if (coordSys) {
  57473. // geo does not support incremental rendering?
  57474. if (isGeoCoordSys(coordSys)) {
  57475. this.render(seriesModel, ecModel, api);
  57476. } else {
  57477. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  57478. }
  57479. }
  57480. };
  57481. HeatmapView.prototype._renderOnCartesianAndCalendar = function (seriesModel, api, start, end, incremental) {
  57482. var coordSys = seriesModel.coordinateSystem;
  57483. var width;
  57484. var height;
  57485. var xAxisExtent;
  57486. var yAxisExtent;
  57487. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  57488. var xAxis = coordSys.getAxis('x');
  57489. var yAxis = coordSys.getAxis('y');
  57490. if ("development" !== 'production') {
  57491. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  57492. throw new Error('Heatmap on cartesian must have two category axes');
  57493. }
  57494. if (!(xAxis.onBand && yAxis.onBand)) {
  57495. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  57496. }
  57497. }
  57498. width = xAxis.getBandWidth();
  57499. height = yAxis.getBandWidth();
  57500. xAxisExtent = xAxis.scale.getExtent();
  57501. yAxisExtent = yAxis.scale.getExtent();
  57502. }
  57503. var group = this.group;
  57504. var data = seriesModel.getData();
  57505. var emphasisStyle = seriesModel.getModel(['emphasis', 'itemStyle']).getItemStyle();
  57506. var blurStyle = seriesModel.getModel(['blur', 'itemStyle']).getItemStyle();
  57507. var selectStyle = seriesModel.getModel(['select', 'itemStyle']).getItemStyle();
  57508. var labelStatesModels = getLabelStatesModels(seriesModel);
  57509. var focus = seriesModel.get(['emphasis', 'focus']);
  57510. var blurScope = seriesModel.get(['emphasis', 'blurScope']);
  57511. var dataDims = isCoordinateSystemType(coordSys, 'cartesian2d') ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  57512. for (var idx = start; idx < end; idx++) {
  57513. var rect = void 0;
  57514. var style = data.getItemVisual(idx, 'style');
  57515. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  57516. var dataDimX = data.get(dataDims[0], idx);
  57517. var dataDimY = data.get(dataDims[1], idx); // Ignore empty data and out of extent data
  57518. if (isNaN(data.get(dataDims[2], idx)) || dataDimX < xAxisExtent[0] || dataDimX > xAxisExtent[1] || dataDimY < yAxisExtent[0] || dataDimY > yAxisExtent[1]) {
  57519. continue;
  57520. }
  57521. var point = coordSys.dataToPoint([dataDimX, dataDimY]);
  57522. rect = new Rect({
  57523. shape: {
  57524. x: Math.floor(Math.round(point[0]) - width / 2),
  57525. y: Math.floor(Math.round(point[1]) - height / 2),
  57526. width: Math.ceil(width),
  57527. height: Math.ceil(height)
  57528. },
  57529. style: style
  57530. });
  57531. } else {
  57532. // Ignore empty data
  57533. if (isNaN(data.get(dataDims[1], idx))) {
  57534. continue;
  57535. }
  57536. rect = new Rect({
  57537. z2: 1,
  57538. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  57539. style: style
  57540. });
  57541. }
  57542. var itemModel = data.getItemModel(idx); // Optimization for large datset
  57543. if (data.hasItemOption) {
  57544. var emphasisModel = itemModel.getModel('emphasis');
  57545. emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  57546. blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  57547. selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  57548. focus = emphasisModel.get('focus');
  57549. blurScope = emphasisModel.get('blurScope');
  57550. labelStatesModels = getLabelStatesModels(itemModel);
  57551. }
  57552. var rawValue = seriesModel.getRawValue(idx);
  57553. var defaultText = '-';
  57554. if (rawValue && rawValue[2] != null) {
  57555. defaultText = rawValue[2] + '';
  57556. }
  57557. setLabelStyle(rect, labelStatesModels, {
  57558. labelFetcher: seriesModel,
  57559. labelDataIndex: idx,
  57560. defaultOpacity: style.opacity,
  57561. defaultText: defaultText
  57562. });
  57563. rect.ensureState('emphasis').style = emphasisStyle;
  57564. rect.ensureState('blur').style = blurStyle;
  57565. rect.ensureState('select').style = selectStyle;
  57566. enableHoverEmphasis(rect, focus, blurScope);
  57567. rect.incremental = incremental; // PENDING
  57568. if (incremental) {
  57569. // Rect must use hover layer if it's incremental.
  57570. rect.states.emphasis.hoverLayer = true;
  57571. }
  57572. group.add(rect);
  57573. data.setItemGraphicEl(idx, rect);
  57574. }
  57575. };
  57576. HeatmapView.prototype._renderOnGeo = function (geo, seriesModel, visualMapModel, api) {
  57577. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  57578. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  57579. // throw new Error('Data range must have color visuals');
  57580. // }
  57581. var data = seriesModel.getData();
  57582. var hmLayer = this._hmLayer || this._hmLayer || new HeatmapLayer();
  57583. hmLayer.blurSize = seriesModel.get('blurSize');
  57584. hmLayer.pointSize = seriesModel.get('pointSize');
  57585. hmLayer.minOpacity = seriesModel.get('minOpacity');
  57586. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  57587. var rect = geo.getViewRect().clone();
  57588. var roamTransform = geo.getRoamTransform();
  57589. rect.applyTransform(roamTransform); // Clamp on viewport
  57590. var x = Math.max(rect.x, 0);
  57591. var y = Math.max(rect.y, 0);
  57592. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  57593. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  57594. var width = x2 - x;
  57595. var height = y2 - y;
  57596. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  57597. var points = data.mapArray(dims, function (lng, lat, value) {
  57598. var pt = geo.dataToPoint([lng, lat]);
  57599. pt[0] -= x;
  57600. pt[1] -= y;
  57601. pt.push(value);
  57602. return pt;
  57603. });
  57604. var dataExtent = visualMapModel.getExtent();
  57605. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  57606. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  57607. inRange: inRangeVisuals.color.getColorMapper(),
  57608. outOfRange: outOfRangeVisuals.color.getColorMapper()
  57609. }, isInRange);
  57610. var img = new ZRImage({
  57611. style: {
  57612. width: width,
  57613. height: height,
  57614. x: x,
  57615. y: y,
  57616. image: hmLayer.canvas
  57617. },
  57618. silent: true
  57619. });
  57620. this.group.add(img);
  57621. };
  57622. HeatmapView.type = 'heatmap';
  57623. return HeatmapView;
  57624. }(ChartView);
  57625. var HeatmapSeriesModel =
  57626. /** @class */
  57627. function (_super) {
  57628. __extends(HeatmapSeriesModel, _super);
  57629. function HeatmapSeriesModel() {
  57630. var _this = _super !== null && _super.apply(this, arguments) || this;
  57631. _this.type = HeatmapSeriesModel.type;
  57632. return _this;
  57633. }
  57634. HeatmapSeriesModel.prototype.getInitialData = function (option, ecModel) {
  57635. return createListFromArray(this.getSource(), this, {
  57636. generateCoord: 'value'
  57637. });
  57638. };
  57639. HeatmapSeriesModel.prototype.preventIncremental = function () {
  57640. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  57641. if (coordSysCreator && coordSysCreator.dimensions) {
  57642. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  57643. }
  57644. };
  57645. HeatmapSeriesModel.type = 'series.heatmap';
  57646. HeatmapSeriesModel.dependencies = ['grid', 'geo', 'calendar'];
  57647. HeatmapSeriesModel.defaultOption = {
  57648. coordinateSystem: 'cartesian2d',
  57649. zlevel: 0,
  57650. z: 2,
  57651. // Cartesian coordinate system
  57652. // xAxisIndex: 0,
  57653. // yAxisIndex: 0,
  57654. // Geo coordinate system
  57655. geoIndex: 0,
  57656. blurSize: 30,
  57657. pointSize: 20,
  57658. maxOpacity: 1,
  57659. minOpacity: 0,
  57660. select: {
  57661. itemStyle: {
  57662. borderColor: '#212121'
  57663. }
  57664. }
  57665. };
  57666. return HeatmapSeriesModel;
  57667. }(SeriesModel);
  57668. function install$n(registers) {
  57669. registers.registerChartView(HeatmapView);
  57670. registers.registerSeriesModel(HeatmapSeriesModel);
  57671. }
  57672. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  57673. var LAYOUT_ATTRS = [{
  57674. xy: 'x',
  57675. wh: 'width',
  57676. index: 0,
  57677. posDesc: ['left', 'right']
  57678. }, {
  57679. xy: 'y',
  57680. wh: 'height',
  57681. index: 1,
  57682. posDesc: ['top', 'bottom']
  57683. }];
  57684. var pathForLineWidth = new Circle();
  57685. var PictorialBarView =
  57686. /** @class */
  57687. function (_super) {
  57688. __extends(PictorialBarView, _super);
  57689. function PictorialBarView() {
  57690. var _this = _super !== null && _super.apply(this, arguments) || this;
  57691. _this.type = PictorialBarView.type;
  57692. return _this;
  57693. }
  57694. PictorialBarView.prototype.render = function (seriesModel, ecModel, api) {
  57695. var group = this.group;
  57696. var data = seriesModel.getData();
  57697. var oldData = this._data;
  57698. var cartesian = seriesModel.coordinateSystem;
  57699. var baseAxis = cartesian.getBaseAxis();
  57700. var isHorizontal = baseAxis.isHorizontal();
  57701. var coordSysRect = cartesian.master.getRect();
  57702. var opt = {
  57703. ecSize: {
  57704. width: api.getWidth(),
  57705. height: api.getHeight()
  57706. },
  57707. seriesModel: seriesModel,
  57708. coordSys: cartesian,
  57709. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  57710. isHorizontal: isHorizontal,
  57711. valueDim: LAYOUT_ATTRS[+isHorizontal],
  57712. categoryDim: LAYOUT_ATTRS[1 - +isHorizontal]
  57713. };
  57714. data.diff(oldData).add(function (dataIndex) {
  57715. if (!data.hasValue(dataIndex)) {
  57716. return;
  57717. }
  57718. var itemModel = getItemModel(data, dataIndex);
  57719. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  57720. var bar = createBar(data, opt, symbolMeta);
  57721. data.setItemGraphicEl(dataIndex, bar);
  57722. group.add(bar);
  57723. updateCommon$1(bar, opt, symbolMeta);
  57724. }).update(function (newIndex, oldIndex) {
  57725. var bar = oldData.getItemGraphicEl(oldIndex);
  57726. if (!data.hasValue(newIndex)) {
  57727. group.remove(bar);
  57728. return;
  57729. }
  57730. var itemModel = getItemModel(data, newIndex);
  57731. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  57732. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  57733. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  57734. group.remove(bar);
  57735. data.setItemGraphicEl(newIndex, null);
  57736. bar = null;
  57737. }
  57738. if (bar) {
  57739. updateBar(bar, opt, symbolMeta);
  57740. } else {
  57741. bar = createBar(data, opt, symbolMeta, true);
  57742. }
  57743. data.setItemGraphicEl(newIndex, bar);
  57744. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  57745. group.add(bar);
  57746. updateCommon$1(bar, opt, symbolMeta);
  57747. }).remove(function (dataIndex) {
  57748. var bar = oldData.getItemGraphicEl(dataIndex);
  57749. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  57750. }).execute();
  57751. this._data = data;
  57752. return this.group;
  57753. };
  57754. PictorialBarView.prototype.remove = function (ecModel, api) {
  57755. var group = this.group;
  57756. var data = this._data;
  57757. if (ecModel.get('animation')) {
  57758. if (data) {
  57759. data.eachItemGraphicEl(function (bar) {
  57760. removeBar(data, getECData(bar).dataIndex, ecModel, bar);
  57761. });
  57762. }
  57763. } else {
  57764. group.removeAll();
  57765. }
  57766. };
  57767. PictorialBarView.type = 'pictorialBar';
  57768. return PictorialBarView;
  57769. }(ChartView); // Set or calculate default value about symbol, and calculate layout info.
  57770. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  57771. var layout = data.getItemLayout(dataIndex);
  57772. var symbolRepeat = itemModel.get('symbolRepeat');
  57773. var symbolClip = itemModel.get('symbolClip');
  57774. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  57775. var symbolRotate = itemModel.get('symbolRotate');
  57776. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  57777. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  57778. var isAnimationEnabled = itemModel.isAnimationEnabled();
  57779. var symbolMeta = {
  57780. dataIndex: dataIndex,
  57781. layout: layout,
  57782. itemModel: itemModel,
  57783. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  57784. style: data.getItemVisual(dataIndex, 'style'),
  57785. symbolClip: symbolClip,
  57786. symbolRepeat: symbolRepeat,
  57787. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  57788. symbolPatternSize: symbolPatternSize,
  57789. rotation: rotation,
  57790. animationModel: isAnimationEnabled ? itemModel : null,
  57791. hoverScale: isAnimationEnabled && itemModel.get(['emphasis', 'scale']),
  57792. z2: itemModel.getShallow('z', true) || 0
  57793. };
  57794. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  57795. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  57796. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  57797. var symbolSize = symbolMeta.symbolSize;
  57798. var symbolOffset = itemModel.get('symbolOffset');
  57799. if (isArray(symbolOffset)) {
  57800. symbolOffset = [parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1])];
  57801. }
  57802. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  57803. return symbolMeta;
  57804. } // bar length can be negative.
  57805. function prepareBarLength(itemModel, symbolRepeat, layout, opt, outputSymbolMeta) {
  57806. var valueDim = opt.valueDim;
  57807. var symbolBoundingData = itemModel.get('symbolBoundingData');
  57808. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  57809. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  57810. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  57811. var boundingLength;
  57812. if (isArray(symbolBoundingData)) {
  57813. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  57814. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  57815. boundingLength = symbolBoundingExtent[pxSignIdx];
  57816. } else if (symbolBoundingData != null) {
  57817. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  57818. } else if (symbolRepeat) {
  57819. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  57820. } else {
  57821. boundingLength = layout[valueDim.wh];
  57822. }
  57823. outputSymbolMeta.boundingLength = boundingLength;
  57824. if (symbolRepeat) {
  57825. outputSymbolMeta.repeatCutLength = layout[valueDim.wh];
  57826. }
  57827. outputSymbolMeta.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  57828. }
  57829. function convertToCoordOnAxis(axis, value) {
  57830. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  57831. } // Support ['100%', '100%']
  57832. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, outputSymbolMeta) {
  57833. var valueDim = opt.valueDim;
  57834. var categoryDim = opt.categoryDim;
  57835. var categorySize = Math.abs(layout[categoryDim.wh]);
  57836. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  57837. var parsedSymbolSize;
  57838. if (isArray(symbolSize)) {
  57839. parsedSymbolSize = symbolSize.slice();
  57840. } else {
  57841. if (symbolSize == null) {
  57842. // will parse to number below
  57843. parsedSymbolSize = ['100%', '100%'];
  57844. } else {
  57845. parsedSymbolSize = [symbolSize, symbolSize];
  57846. }
  57847. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  57848. // to complicated to calculate real percent value if considering scaled lineWidth.
  57849. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  57850. // which can be tolerated in pictorial chart.
  57851. parsedSymbolSize[categoryDim.index] = parsePercent$1(parsedSymbolSize[categoryDim.index], categorySize);
  57852. parsedSymbolSize[valueDim.index] = parsePercent$1(parsedSymbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  57853. outputSymbolMeta.symbolSize = parsedSymbolSize; // If x or y is less than zero, show reversed shape.
  57854. var symbolScale = outputSymbolMeta.symbolScale = [parsedSymbolSize[0] / symbolPatternSize, parsedSymbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  57855. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  57856. }
  57857. function prepareLineWidth(itemModel, symbolScale, rotation, opt, outputSymbolMeta) {
  57858. // In symbols are drawn with scale, so do not need to care about the case that width
  57859. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  57860. // be calculated.
  57861. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  57862. if (valueLineWidth) {
  57863. pathForLineWidth.attr({
  57864. scaleX: symbolScale[0],
  57865. scaleY: symbolScale[1],
  57866. rotation: rotation
  57867. });
  57868. pathForLineWidth.updateTransform();
  57869. valueLineWidth /= pathForLineWidth.getLineScale();
  57870. valueLineWidth *= symbolScale[opt.valueDim.index];
  57871. }
  57872. outputSymbolMeta.valueLineWidth = valueLineWidth;
  57873. }
  57874. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, outputSymbolMeta) {
  57875. var categoryDim = opt.categoryDim;
  57876. var valueDim = opt.valueDim;
  57877. var pxSign = outputSymbolMeta.pxSign;
  57878. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  57879. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  57880. // want symbols to rotate on its center, which should not be translated
  57881. // when rotating.
  57882. if (symbolRepeat) {
  57883. var absBoundingLength = Math.abs(boundingLength);
  57884. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  57885. var hasEndGap = false;
  57886. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  57887. hasEndGap = true;
  57888. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  57889. }
  57890. var symbolMarginNumeric = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  57891. var uLenWithMargin = Math.max(unitLength + symbolMarginNumeric * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  57892. // to ensure that all of the symbols will not be overflow the given area.
  57893. var endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Both final repeatTimes and final symbolMarginNumeric area calculated based on
  57894. // boundingLength.
  57895. var repeatSpecified = isNumeric(symbolRepeat);
  57896. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  57897. // entirely in the given layout area.
  57898. var mDiff = absBoundingLength - repeatTimes * unitLength;
  57899. symbolMarginNumeric = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  57900. uLenWithMargin = unitLength + symbolMarginNumeric * 2;
  57901. endFix = hasEndGap ? 0 : symbolMarginNumeric * 2; // Update repeatTimes when not all symbol will be shown.
  57902. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  57903. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  57904. }
  57905. pathLen = repeatTimes * uLenWithMargin - endFix;
  57906. outputSymbolMeta.repeatTimes = repeatTimes;
  57907. outputSymbolMeta.symbolMargin = symbolMarginNumeric;
  57908. }
  57909. var sizeFix = pxSign * (pathLen / 2);
  57910. var pathPosition = outputSymbolMeta.pathPosition = [];
  57911. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  57912. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  57913. if (symbolOffset) {
  57914. pathPosition[0] += symbolOffset[0];
  57915. pathPosition[1] += symbolOffset[1];
  57916. }
  57917. var bundlePosition = outputSymbolMeta.bundlePosition = [];
  57918. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  57919. bundlePosition[valueDim.index] = layout[valueDim.xy];
  57920. var barRectShape = outputSymbolMeta.barRectShape = extend({}, layout);
  57921. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  57922. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  57923. var clipShape = outputSymbolMeta.clipShape = {}; // Consider that symbol may be overflow layout rect.
  57924. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  57925. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  57926. clipShape[valueDim.xy] = 0;
  57927. clipShape[valueDim.wh] = layout[valueDim.wh];
  57928. }
  57929. function createPath(symbolMeta) {
  57930. var symbolPatternSize = symbolMeta.symbolPatternSize;
  57931. var path = createSymbol( // Consider texture img, make a big size.
  57932. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize);
  57933. path.attr({
  57934. culling: true
  57935. });
  57936. path.type !== 'image' && path.setStyle({
  57937. strokeNoScale: true
  57938. });
  57939. return path;
  57940. }
  57941. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  57942. var bundle = bar.__pictorialBundle;
  57943. var symbolSize = symbolMeta.symbolSize;
  57944. var valueLineWidth = symbolMeta.valueLineWidth;
  57945. var pathPosition = symbolMeta.pathPosition;
  57946. var valueDim = opt.valueDim;
  57947. var repeatTimes = symbolMeta.repeatTimes || 0;
  57948. var index = 0;
  57949. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  57950. eachPath(bar, function (path) {
  57951. path.__pictorialAnimationIndex = index;
  57952. path.__pictorialRepeatTimes = repeatTimes;
  57953. if (index < repeatTimes) {
  57954. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  57955. } else {
  57956. updateAttr(path, null, {
  57957. scaleX: 0,
  57958. scaleY: 0
  57959. }, symbolMeta, isUpdate, function () {
  57960. bundle.remove(path);
  57961. });
  57962. } // updateHoverAnimation(path, symbolMeta);
  57963. index++;
  57964. });
  57965. for (; index < repeatTimes; index++) {
  57966. var path = createPath(symbolMeta);
  57967. path.__pictorialAnimationIndex = index;
  57968. path.__pictorialRepeatTimes = repeatTimes;
  57969. bundle.add(path);
  57970. var target = makeTarget(index);
  57971. updateAttr(path, {
  57972. x: target.x,
  57973. y: target.y,
  57974. scaleX: 0,
  57975. scaleY: 0
  57976. }, {
  57977. scaleX: target.scaleX,
  57978. scaleY: target.scaleY,
  57979. rotation: target.rotation
  57980. }, symbolMeta, isUpdate);
  57981. }
  57982. function makeTarget(index) {
  57983. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  57984. // Otherwise: i = index;
  57985. var pxSign = symbolMeta.pxSign;
  57986. var i = index;
  57987. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  57988. i = repeatTimes - 1 - index;
  57989. }
  57990. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  57991. return {
  57992. x: position[0],
  57993. y: position[1],
  57994. scaleX: symbolMeta.symbolScale[0],
  57995. scaleY: symbolMeta.symbolScale[1],
  57996. rotation: symbolMeta.rotation
  57997. };
  57998. }
  57999. }
  58000. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  58001. var bundle = bar.__pictorialBundle;
  58002. var mainPath = bar.__pictorialMainPath;
  58003. if (!mainPath) {
  58004. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  58005. bundle.add(mainPath);
  58006. updateAttr(mainPath, {
  58007. x: symbolMeta.pathPosition[0],
  58008. y: symbolMeta.pathPosition[1],
  58009. scaleX: 0,
  58010. scaleY: 0,
  58011. rotation: symbolMeta.rotation
  58012. }, {
  58013. scaleX: symbolMeta.symbolScale[0],
  58014. scaleY: symbolMeta.symbolScale[1]
  58015. }, symbolMeta, isUpdate);
  58016. } else {
  58017. updateAttr(mainPath, null, {
  58018. x: symbolMeta.pathPosition[0],
  58019. y: symbolMeta.pathPosition[1],
  58020. scaleX: symbolMeta.symbolScale[0],
  58021. scaleY: symbolMeta.symbolScale[1],
  58022. rotation: symbolMeta.rotation
  58023. }, symbolMeta, isUpdate);
  58024. }
  58025. } // bar rect is used for label.
  58026. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  58027. var rectShape = extend({}, symbolMeta.barRectShape);
  58028. var barRect = bar.__pictorialBarRect;
  58029. if (!barRect) {
  58030. barRect = bar.__pictorialBarRect = new Rect({
  58031. z2: 2,
  58032. shape: rectShape,
  58033. silent: true,
  58034. style: {
  58035. stroke: 'transparent',
  58036. fill: 'transparent',
  58037. lineWidth: 0
  58038. }
  58039. });
  58040. bar.add(barRect);
  58041. } else {
  58042. updateAttr(barRect, null, {
  58043. shape: rectShape
  58044. }, symbolMeta, isUpdate);
  58045. }
  58046. }
  58047. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  58048. // If not clip, symbol will be remove and rebuilt.
  58049. if (symbolMeta.symbolClip) {
  58050. var clipPath = bar.__pictorialClipPath;
  58051. var clipShape = extend({}, symbolMeta.clipShape);
  58052. var valueDim = opt.valueDim;
  58053. var animationModel = symbolMeta.animationModel;
  58054. var dataIndex = symbolMeta.dataIndex;
  58055. if (clipPath) {
  58056. updateProps(clipPath, {
  58057. shape: clipShape
  58058. }, animationModel, dataIndex);
  58059. } else {
  58060. clipShape[valueDim.wh] = 0;
  58061. clipPath = new Rect({
  58062. shape: clipShape
  58063. });
  58064. bar.__pictorialBundle.setClipPath(clipPath);
  58065. bar.__pictorialClipPath = clipPath;
  58066. var target = {};
  58067. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  58068. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  58069. shape: target
  58070. }, animationModel, dataIndex);
  58071. }
  58072. }
  58073. }
  58074. function getItemModel(data, dataIndex) {
  58075. var itemModel = data.getItemModel(dataIndex);
  58076. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  58077. itemModel.isAnimationEnabled = isAnimationEnabled;
  58078. return itemModel;
  58079. }
  58080. function getAnimationDelayParams(path) {
  58081. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  58082. return {
  58083. index: path.__pictorialAnimationIndex,
  58084. count: path.__pictorialRepeatTimes
  58085. };
  58086. }
  58087. function isAnimationEnabled() {
  58088. // `animation` prop can be set on itemModel in pictorial bar chart.
  58089. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  58090. }
  58091. function createBar(data, opt, symbolMeta, isUpdate) {
  58092. // bar is the main element for each data.
  58093. var bar = new Group(); // bundle is used for location and clip.
  58094. var bundle = new Group();
  58095. bar.add(bundle);
  58096. bar.__pictorialBundle = bundle;
  58097. bundle.x = symbolMeta.bundlePosition[0];
  58098. bundle.y = symbolMeta.bundlePosition[1];
  58099. if (symbolMeta.symbolRepeat) {
  58100. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  58101. } else {
  58102. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  58103. }
  58104. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  58105. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  58106. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  58107. bar.__pictorialSymbolMeta = symbolMeta;
  58108. return bar;
  58109. }
  58110. function updateBar(bar, opt, symbolMeta) {
  58111. var animationModel = symbolMeta.animationModel;
  58112. var dataIndex = symbolMeta.dataIndex;
  58113. var bundle = bar.__pictorialBundle;
  58114. updateProps(bundle, {
  58115. x: symbolMeta.bundlePosition[0],
  58116. y: symbolMeta.bundlePosition[1]
  58117. }, animationModel, dataIndex);
  58118. if (symbolMeta.symbolRepeat) {
  58119. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  58120. } else {
  58121. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  58122. }
  58123. createOrUpdateBarRect(bar, symbolMeta, true);
  58124. createOrUpdateClip(bar, opt, symbolMeta, true);
  58125. }
  58126. function removeBar(data, dataIndex, animationModel, bar) {
  58127. // Not show text when animating
  58128. var labelRect = bar.__pictorialBarRect;
  58129. labelRect && labelRect.removeTextContent();
  58130. var pathes = [];
  58131. eachPath(bar, function (path) {
  58132. pathes.push(path);
  58133. });
  58134. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  58135. bar.__pictorialClipPath && (animationModel = null);
  58136. each(pathes, function (path) {
  58137. removeElement(path, {
  58138. scaleX: 0,
  58139. scaleY: 0
  58140. }, animationModel, dataIndex, function () {
  58141. bar.parent && bar.parent.remove(bar);
  58142. });
  58143. });
  58144. data.setItemGraphicEl(dataIndex, null);
  58145. }
  58146. function getShapeStr(data, symbolMeta) {
  58147. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  58148. }
  58149. function eachPath(bar, cb, context) {
  58150. // Do not use Group#eachChild, because it do not support remove.
  58151. each(bar.__pictorialBundle.children(), function (el) {
  58152. el !== bar.__pictorialBarRect && cb.call(context, el);
  58153. });
  58154. }
  58155. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  58156. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  58157. if (symbolMeta.symbolClip && !isUpdate) {
  58158. animationAttrs && el.attr(animationAttrs);
  58159. } else {
  58160. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  58161. }
  58162. }
  58163. function updateCommon$1(bar, opt, symbolMeta) {
  58164. var dataIndex = symbolMeta.dataIndex;
  58165. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  58166. // Because symbol provide setColor individually to set fill and stroke
  58167. var emphasisModel = itemModel.getModel('emphasis');
  58168. var emphasisStyle = emphasisModel.getModel('itemStyle').getItemStyle();
  58169. var blurStyle = itemModel.getModel(['blur', 'itemStyle']).getItemStyle();
  58170. var selectStyle = itemModel.getModel(['select', 'itemStyle']).getItemStyle();
  58171. var cursorStyle = itemModel.getShallow('cursor');
  58172. var focus = emphasisModel.get('focus');
  58173. var blurScope = emphasisModel.get('blurScope');
  58174. var hoverScale = emphasisModel.get('scale');
  58175. eachPath(bar, function (path) {
  58176. if (path instanceof ZRImage) {
  58177. var pathStyle = path.style;
  58178. path.useStyle(extend({
  58179. // TODO other properties like dx, dy ?
  58180. image: pathStyle.image,
  58181. x: pathStyle.x,
  58182. y: pathStyle.y,
  58183. width: pathStyle.width,
  58184. height: pathStyle.height
  58185. }, symbolMeta.style));
  58186. } else {
  58187. path.useStyle(symbolMeta.style);
  58188. }
  58189. var emphasisState = path.ensureState('emphasis');
  58190. emphasisState.style = emphasisStyle;
  58191. if (hoverScale) {
  58192. // NOTE: Must after scale is set after updateAttr
  58193. emphasisState.scaleX = path.scaleX * 1.1;
  58194. emphasisState.scaleY = path.scaleY * 1.1;
  58195. }
  58196. path.ensureState('blur').style = blurStyle;
  58197. path.ensureState('select').style = selectStyle;
  58198. cursorStyle && (path.cursor = cursorStyle);
  58199. path.z2 = symbolMeta.z2;
  58200. });
  58201. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  58202. var barRect = bar.__pictorialBarRect;
  58203. setLabelStyle(barRect, getLabelStatesModels(itemModel), {
  58204. labelFetcher: opt.seriesModel,
  58205. labelDataIndex: dataIndex,
  58206. defaultText: getDefaultLabel(opt.seriesModel.getData(), dataIndex),
  58207. inheritColor: symbolMeta.style.fill,
  58208. defaultOpacity: symbolMeta.style.opacity,
  58209. defaultOutsidePosition: barPositionOutside
  58210. });
  58211. enableHoverEmphasis(bar, focus, blurScope);
  58212. }
  58213. function toIntTimes(times) {
  58214. var roundedTimes = Math.round(times); // Escapse accurate error
  58215. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  58216. }
  58217. var PictorialBarSeriesModel =
  58218. /** @class */
  58219. function (_super) {
  58220. __extends(PictorialBarSeriesModel, _super);
  58221. function PictorialBarSeriesModel() {
  58222. var _this = _super !== null && _super.apply(this, arguments) || this;
  58223. _this.type = PictorialBarSeriesModel.type;
  58224. _this.hasSymbolVisual = true;
  58225. _this.defaultSymbol = 'roundRect';
  58226. return _this;
  58227. }
  58228. PictorialBarSeriesModel.prototype.getInitialData = function (option) {
  58229. // Disable stack.
  58230. option.stack = null;
  58231. return _super.prototype.getInitialData.apply(this, arguments);
  58232. };
  58233. PictorialBarSeriesModel.type = 'series.pictorialBar';
  58234. PictorialBarSeriesModel.dependencies = ['grid'];
  58235. PictorialBarSeriesModel.defaultOption = inheritDefaultOption(BaseBarSeriesModel.defaultOption, {
  58236. symbol: 'circle',
  58237. symbolSize: null,
  58238. symbolRotate: null,
  58239. symbolPosition: null,
  58240. symbolOffset: null,
  58241. symbolMargin: null,
  58242. symbolRepeat: false,
  58243. symbolRepeatDirection: 'end',
  58244. symbolClip: false,
  58245. symbolBoundingData: null,
  58246. symbolPatternSize: 400,
  58247. barGap: '-100%',
  58248. // z can be set in data item, which is z2 actually.
  58249. // Disable progressive
  58250. progressive: 0,
  58251. emphasis: {
  58252. // By default pictorialBar do not hover scale. Hover scale is not suitable
  58253. // for the case that both has foreground and background.
  58254. scale: false
  58255. },
  58256. select: {
  58257. itemStyle: {
  58258. borderColor: '#212121'
  58259. }
  58260. }
  58261. });
  58262. return PictorialBarSeriesModel;
  58263. }(BaseBarSeriesModel);
  58264. function install$o(registers) {
  58265. registers.registerChartView(PictorialBarView);
  58266. registers.registerSeriesModel(PictorialBarSeriesModel);
  58267. registers.registerLayout(curry(layout, 'pictorialBar'));
  58268. }
  58269. var ThemeRiverView =
  58270. /** @class */
  58271. function (_super) {
  58272. __extends(ThemeRiverView, _super);
  58273. function ThemeRiverView() {
  58274. var _this = _super !== null && _super.apply(this, arguments) || this;
  58275. _this.type = ThemeRiverView.type;
  58276. _this._layers = [];
  58277. return _this;
  58278. }
  58279. ThemeRiverView.prototype.render = function (seriesModel, ecModel, api) {
  58280. var data = seriesModel.getData();
  58281. var self = this;
  58282. var group = this.group;
  58283. var layersSeries = seriesModel.getLayerSeries();
  58284. var layoutInfo = data.getLayout('layoutInfo');
  58285. var rect = layoutInfo.rect;
  58286. var boundaryGap = layoutInfo.boundaryGap;
  58287. group.x = 0;
  58288. group.y = rect.y + boundaryGap[0];
  58289. function keyGetter(item) {
  58290. return item.name;
  58291. }
  58292. var dataDiffer = new DataDiffer(this._layersSeries || [], layersSeries, keyGetter, keyGetter);
  58293. var newLayersGroups = [];
  58294. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  58295. function process(status, idx, oldIdx) {
  58296. var oldLayersGroups = self._layers;
  58297. if (status === 'remove') {
  58298. group.remove(oldLayersGroups[idx]);
  58299. return;
  58300. }
  58301. var points0 = [];
  58302. var points1 = [];
  58303. var style;
  58304. var indices = layersSeries[idx].indices;
  58305. var j = 0;
  58306. for (; j < indices.length; j++) {
  58307. var layout = data.getItemLayout(indices[j]);
  58308. var x = layout.x;
  58309. var y0 = layout.y0;
  58310. var y = layout.y;
  58311. points0.push(x, y0);
  58312. points1.push(x, y0 + y);
  58313. style = data.getItemVisual(indices[j], 'style');
  58314. }
  58315. var polygon;
  58316. var textLayout = data.getItemLayout(indices[0]);
  58317. var labelModel = seriesModel.getModel('label');
  58318. var margin = labelModel.get('margin');
  58319. var emphasisModel = seriesModel.getModel('emphasis');
  58320. if (status === 'add') {
  58321. var layerGroup = newLayersGroups[idx] = new Group();
  58322. polygon = new ECPolygon({
  58323. shape: {
  58324. points: points0,
  58325. stackedOnPoints: points1,
  58326. smooth: 0.4,
  58327. stackedOnSmooth: 0.4,
  58328. smoothConstraint: false
  58329. },
  58330. z2: 0
  58331. });
  58332. layerGroup.add(polygon);
  58333. group.add(layerGroup);
  58334. if (seriesModel.isAnimationEnabled()) {
  58335. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  58336. polygon.removeClipPath();
  58337. }));
  58338. }
  58339. } else {
  58340. var layerGroup = oldLayersGroups[oldIdx];
  58341. polygon = layerGroup.childAt(0);
  58342. group.add(layerGroup);
  58343. newLayersGroups[idx] = layerGroup;
  58344. updateProps(polygon, {
  58345. shape: {
  58346. points: points0,
  58347. stackedOnPoints: points1
  58348. }
  58349. }, seriesModel);
  58350. }
  58351. setLabelStyle(polygon, getLabelStatesModels(seriesModel), {
  58352. labelDataIndex: indices[j - 1],
  58353. defaultText: data.getName(indices[j - 1]),
  58354. inheritColor: style.fill
  58355. }, {
  58356. normal: {
  58357. verticalAlign: 'middle' // align: 'right'
  58358. }
  58359. });
  58360. polygon.setTextConfig({
  58361. position: null,
  58362. local: true
  58363. });
  58364. var labelEl = polygon.getTextContent(); // TODO More label position options.
  58365. if (labelEl) {
  58366. labelEl.x = textLayout.x - margin;
  58367. labelEl.y = textLayout.y0 + textLayout.y / 2;
  58368. }
  58369. polygon.useStyle(style);
  58370. data.setItemGraphicEl(idx, polygon);
  58371. setStatesStylesFromModel(polygon, seriesModel);
  58372. enableHoverEmphasis(polygon, emphasisModel.get('focus'), emphasisModel.get('blurScope'));
  58373. }
  58374. this._layersSeries = layersSeries;
  58375. this._layers = newLayersGroups;
  58376. };
  58377. ThemeRiverView.type = 'themeRiver';
  58378. return ThemeRiverView;
  58379. }(ChartView);
  58380. function createGridClipShape$2(rect, seriesModel, cb) {
  58381. var rectEl = new Rect({
  58382. shape: {
  58383. x: rect.x - 10,
  58384. y: rect.y - 10,
  58385. width: 0,
  58386. height: rect.height + 20
  58387. }
  58388. });
  58389. initProps(rectEl, {
  58390. shape: {
  58391. x: rect.x - 50,
  58392. width: rect.width + 100,
  58393. height: rect.height + 20
  58394. }
  58395. }, seriesModel, cb);
  58396. return rectEl;
  58397. }
  58398. var DATA_NAME_INDEX = 2;
  58399. var ThemeRiverSeriesModel =
  58400. /** @class */
  58401. function (_super) {
  58402. __extends(ThemeRiverSeriesModel, _super);
  58403. function ThemeRiverSeriesModel() {
  58404. var _this = _super !== null && _super.apply(this, arguments) || this;
  58405. _this.type = ThemeRiverSeriesModel.type;
  58406. _this.useColorPaletteOnData = true;
  58407. return _this;
  58408. }
  58409. /**
  58410. * @override
  58411. */
  58412. ThemeRiverSeriesModel.prototype.init = function (option) {
  58413. // eslint-disable-next-line
  58414. _super.prototype.init.apply(this, arguments); // Put this function here is for the sake of consistency of code style.
  58415. // Enable legend selection for each data item
  58416. // Use a function instead of direct access because data reference may changed
  58417. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  58418. };
  58419. /**
  58420. * If there is no value of a certain point in the time for some event,set it value to 0.
  58421. *
  58422. * @param {Array} data initial data in the option
  58423. * @return {Array}
  58424. */
  58425. ThemeRiverSeriesModel.prototype.fixData = function (data) {
  58426. var rawDataLength = data.length;
  58427. /**
  58428. * Make sure every layer data get the same keys.
  58429. * The value index tells which layer has visited.
  58430. * {
  58431. * 2014/01/01: -1
  58432. * }
  58433. */
  58434. var timeValueKeys = {}; // grouped data by name
  58435. var groupResult = groupData(data, function (item) {
  58436. if (!timeValueKeys.hasOwnProperty(item[0] + '')) {
  58437. timeValueKeys[item[0] + ''] = -1;
  58438. }
  58439. return item[2];
  58440. });
  58441. var layerData = [];
  58442. groupResult.buckets.each(function (items, key) {
  58443. layerData.push({
  58444. name: key,
  58445. dataList: items
  58446. });
  58447. });
  58448. var layerNum = layerData.length;
  58449. for (var k = 0; k < layerNum; ++k) {
  58450. var name_1 = layerData[k].name;
  58451. for (var j = 0; j < layerData[k].dataList.length; ++j) {
  58452. var timeValue = layerData[k].dataList[j][0] + '';
  58453. timeValueKeys[timeValue] = k;
  58454. }
  58455. for (var timeValue in timeValueKeys) {
  58456. if (timeValueKeys.hasOwnProperty(timeValue) && timeValueKeys[timeValue] !== k) {
  58457. timeValueKeys[timeValue] = k;
  58458. data[rawDataLength] = [timeValue, 0, name_1];
  58459. rawDataLength++;
  58460. }
  58461. }
  58462. }
  58463. return data;
  58464. };
  58465. /**
  58466. * @override
  58467. * @param option the initial option that user gived
  58468. * @param ecModel the model object for themeRiver option
  58469. */
  58470. ThemeRiverSeriesModel.prototype.getInitialData = function (option, ecModel) {
  58471. var singleAxisModel = this.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  58472. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  58473. var filterData = filter(option.data, function (dataItem) {
  58474. return dataItem[2] !== undefined;
  58475. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  58476. var data = this.fixData(filterData || []);
  58477. var nameList = [];
  58478. var nameMap = this.nameMap = createHashMap();
  58479. var count = 0;
  58480. for (var i = 0; i < data.length; ++i) {
  58481. nameList.push(data[i][DATA_NAME_INDEX]);
  58482. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  58483. nameMap.set(data[i][DATA_NAME_INDEX], count);
  58484. count++;
  58485. }
  58486. }
  58487. var dimensionsInfo = createDimensions(data, {
  58488. coordDimensions: ['single'],
  58489. dimensionsDefine: [{
  58490. name: 'time',
  58491. type: getDimensionTypeByAxis(axisType)
  58492. }, {
  58493. name: 'value',
  58494. type: 'float'
  58495. }, {
  58496. name: 'name',
  58497. type: 'ordinal'
  58498. }],
  58499. encodeDefine: {
  58500. single: 0,
  58501. value: 1,
  58502. itemName: 2
  58503. }
  58504. });
  58505. var list = new List(dimensionsInfo, this);
  58506. list.initData(data);
  58507. return list;
  58508. };
  58509. /**
  58510. * The raw data is divided into multiple layers and each layer
  58511. * has same name.
  58512. */
  58513. ThemeRiverSeriesModel.prototype.getLayerSeries = function () {
  58514. var data = this.getData();
  58515. var lenCount = data.count();
  58516. var indexArr = [];
  58517. for (var i = 0; i < lenCount; ++i) {
  58518. indexArr[i] = i;
  58519. }
  58520. var timeDim = data.mapDimension('single'); // data group by name
  58521. var groupResult = groupData(indexArr, function (index) {
  58522. return data.get('name', index);
  58523. });
  58524. var layerSeries = [];
  58525. groupResult.buckets.each(function (items, key) {
  58526. items.sort(function (index1, index2) {
  58527. return data.get(timeDim, index1) - data.get(timeDim, index2);
  58528. });
  58529. layerSeries.push({
  58530. name: key,
  58531. indices: items
  58532. });
  58533. });
  58534. return layerSeries;
  58535. };
  58536. /**
  58537. * Get data indices for show tooltip content
  58538. */
  58539. ThemeRiverSeriesModel.prototype.getAxisTooltipData = function (dim, value, baseAxis) {
  58540. if (!isArray(dim)) {
  58541. dim = dim ? [dim] : [];
  58542. }
  58543. var data = this.getData();
  58544. var layerSeries = this.getLayerSeries();
  58545. var indices = [];
  58546. var layerNum = layerSeries.length;
  58547. var nestestValue;
  58548. for (var i = 0; i < layerNum; ++i) {
  58549. var minDist = Number.MAX_VALUE;
  58550. var nearestIdx = -1;
  58551. var pointNum = layerSeries[i].indices.length;
  58552. for (var j = 0; j < pointNum; ++j) {
  58553. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  58554. var dist = Math.abs(theValue - value);
  58555. if (dist <= minDist) {
  58556. nestestValue = theValue;
  58557. minDist = dist;
  58558. nearestIdx = layerSeries[i].indices[j];
  58559. }
  58560. }
  58561. indices.push(nearestIdx);
  58562. }
  58563. return {
  58564. dataIndices: indices,
  58565. nestestValue: nestestValue
  58566. };
  58567. };
  58568. ThemeRiverSeriesModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  58569. var data = this.getData();
  58570. var name = data.getName(dataIndex);
  58571. var value = data.get(data.mapDimension('value'), dataIndex);
  58572. return createTooltipMarkup('nameValue', {
  58573. name: name,
  58574. value: value
  58575. });
  58576. };
  58577. ThemeRiverSeriesModel.type = 'series.themeRiver';
  58578. ThemeRiverSeriesModel.dependencies = ['singleAxis'];
  58579. ThemeRiverSeriesModel.defaultOption = {
  58580. zlevel: 0,
  58581. z: 2,
  58582. coordinateSystem: 'singleAxis',
  58583. // gap in axis's orthogonal orientation
  58584. boundaryGap: ['10%', '10%'],
  58585. // legendHoverLink: true,
  58586. singleAxisIndex: 0,
  58587. animationEasing: 'linear',
  58588. label: {
  58589. margin: 4,
  58590. show: true,
  58591. position: 'left',
  58592. fontSize: 11
  58593. },
  58594. emphasis: {
  58595. label: {
  58596. show: true
  58597. }
  58598. }
  58599. };
  58600. return ThemeRiverSeriesModel;
  58601. }(SeriesModel);
  58602. function themeRiverLayout(ecModel, api) {
  58603. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  58604. var data = seriesModel.getData();
  58605. var single = seriesModel.coordinateSystem;
  58606. var layoutInfo = {}; // use the axis boundingRect for view
  58607. var rect = single.getRect();
  58608. layoutInfo.rect = rect;
  58609. var boundaryGap = seriesModel.get('boundaryGap');
  58610. var axis = single.getAxis();
  58611. layoutInfo.boundaryGap = boundaryGap;
  58612. if (axis.orient === 'horizontal') {
  58613. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  58614. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  58615. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  58616. doThemeRiverLayout(data, seriesModel, height);
  58617. } else {
  58618. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  58619. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  58620. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  58621. doThemeRiverLayout(data, seriesModel, width);
  58622. }
  58623. data.setLayout('layoutInfo', layoutInfo);
  58624. });
  58625. }
  58626. /**
  58627. * The layout information about themeriver
  58628. *
  58629. * @param data data in the series
  58630. * @param seriesModel the model object of themeRiver series
  58631. * @param height value used to compute every series height
  58632. */
  58633. function doThemeRiverLayout(data, seriesModel, height) {
  58634. if (!data.count()) {
  58635. return;
  58636. }
  58637. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  58638. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  58639. var timeDim = data.mapDimension('single');
  58640. var valueDim = data.mapDimension('value');
  58641. var layerPoints = map(layerSeries, function (singleLayer) {
  58642. return map(singleLayer.indices, function (idx) {
  58643. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  58644. pt[1] = data.get(valueDim, idx);
  58645. return pt;
  58646. });
  58647. });
  58648. var base = computeBaseline(layerPoints);
  58649. var baseLine = base.y0;
  58650. var ky = height / base.max; // set layout information for each item.
  58651. var n = layerSeries.length;
  58652. var m = layerSeries[0].indices.length;
  58653. var baseY0;
  58654. for (var j = 0; j < m; ++j) {
  58655. baseY0 = baseLine[j] * ky;
  58656. data.setItemLayout(layerSeries[0].indices[j], {
  58657. layerIndex: 0,
  58658. x: layerPoints[0][j][0],
  58659. y0: baseY0,
  58660. y: layerPoints[0][j][1] * ky
  58661. });
  58662. for (var i = 1; i < n; ++i) {
  58663. baseY0 += layerPoints[i - 1][j][1] * ky;
  58664. data.setItemLayout(layerSeries[i].indices[j], {
  58665. layerIndex: i,
  58666. x: layerPoints[i][j][0],
  58667. y0: baseY0,
  58668. y: layerPoints[i][j][1] * ky
  58669. });
  58670. }
  58671. }
  58672. }
  58673. /**
  58674. * Compute the baseLine of the rawdata
  58675. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  58676. *
  58677. * @param data the points in each layer
  58678. */
  58679. function computeBaseline(data) {
  58680. var layerNum = data.length;
  58681. var pointNum = data[0].length;
  58682. var sums = [];
  58683. var y0 = [];
  58684. var max = 0;
  58685. for (var i = 0; i < pointNum; ++i) {
  58686. var temp = 0;
  58687. for (var j = 0; j < layerNum; ++j) {
  58688. temp += data[j][i][1];
  58689. }
  58690. if (temp > max) {
  58691. max = temp;
  58692. }
  58693. sums.push(temp);
  58694. }
  58695. for (var k = 0; k < pointNum; ++k) {
  58696. y0[k] = (max - sums[k]) / 2;
  58697. }
  58698. max = 0;
  58699. for (var l = 0; l < pointNum; ++l) {
  58700. var sum = sums[l] + y0[l];
  58701. if (sum > max) {
  58702. max = sum;
  58703. }
  58704. }
  58705. return {
  58706. y0: y0,
  58707. max: max
  58708. };
  58709. }
  58710. function install$p(registers) {
  58711. registers.registerChartView(ThemeRiverView);
  58712. registers.registerSeriesModel(ThemeRiverSeriesModel);
  58713. registers.registerLayout(themeRiverLayout);
  58714. registers.registerProcessor(dataFilter('themeRiver'));
  58715. }
  58716. var DEFAULT_SECTOR_Z = 2;
  58717. var DEFAULT_TEXT_Z = 4;
  58718. /**
  58719. * Sunburstce of Sunburst including Sector, Label, LabelLine
  58720. */
  58721. var SunburstPiece =
  58722. /** @class */
  58723. function (_super) {
  58724. __extends(SunburstPiece, _super);
  58725. function SunburstPiece(node, seriesModel, ecModel, api) {
  58726. var _this = _super.call(this) || this;
  58727. _this.z2 = DEFAULT_SECTOR_Z;
  58728. _this.textConfig = {
  58729. inside: true
  58730. };
  58731. getECData(_this).seriesIndex = seriesModel.seriesIndex;
  58732. var text = new ZRText({
  58733. z2: DEFAULT_TEXT_Z,
  58734. silent: node.getModel().get(['label', 'silent'])
  58735. });
  58736. _this.setTextContent(text);
  58737. _this.updateData(true, node, seriesModel, ecModel, api);
  58738. return _this;
  58739. }
  58740. SunburstPiece.prototype.updateData = function (firstCreate, node, // state: 'emphasis' | 'normal' | 'highlight' | 'downplay',
  58741. seriesModel, ecModel, api) {
  58742. this.node = node;
  58743. node.piece = this;
  58744. seriesModel = seriesModel || this._seriesModel;
  58745. ecModel = ecModel || this._ecModel;
  58746. var sector = this;
  58747. getECData(sector).dataIndex = node.dataIndex;
  58748. var itemModel = node.getModel();
  58749. var emphasisModel = itemModel.getModel('emphasis');
  58750. var layout = node.getLayout();
  58751. var sectorShape = extend({}, layout);
  58752. sectorShape.label = null;
  58753. var normalStyle = node.getVisual('style');
  58754. normalStyle.lineJoin = 'bevel';
  58755. var decal = node.getVisual('decal');
  58756. if (decal) {
  58757. normalStyle.decal = createOrUpdatePatternFromDecal(decal, api);
  58758. }
  58759. var cornerRadius = getSectorCornerRadius(itemModel.getModel('itemStyle'), sectorShape);
  58760. extend(sectorShape, cornerRadius);
  58761. each(SPECIAL_STATES, function (stateName) {
  58762. var state = sector.ensureState(stateName);
  58763. var itemStyleModel = itemModel.getModel([stateName, 'itemStyle']);
  58764. state.style = itemStyleModel.getItemStyle(); // border radius
  58765. var cornerRadius = getSectorCornerRadius(itemStyleModel, sectorShape);
  58766. if (cornerRadius) {
  58767. state.shape = cornerRadius;
  58768. }
  58769. });
  58770. if (firstCreate) {
  58771. sector.setShape(sectorShape);
  58772. sector.shape.r = layout.r0;
  58773. updateProps(sector, {
  58774. shape: {
  58775. r: layout.r
  58776. }
  58777. }, seriesModel, node.dataIndex);
  58778. } else {
  58779. // Disable animation for gradient since no interpolation method
  58780. // is supported for gradient
  58781. updateProps(sector, {
  58782. shape: sectorShape
  58783. }, seriesModel);
  58784. }
  58785. sector.useStyle(normalStyle);
  58786. this._updateLabel(seriesModel);
  58787. var cursorStyle = itemModel.getShallow('cursor');
  58788. cursorStyle && sector.attr('cursor', cursorStyle);
  58789. this._seriesModel = seriesModel || this._seriesModel;
  58790. this._ecModel = ecModel || this._ecModel;
  58791. var focus = emphasisModel.get('focus');
  58792. var focusDataIndices = focus === 'ancestor' ? node.getAncestorsIndices() : focus === 'descendant' ? node.getDescendantIndices() : null;
  58793. enableHoverEmphasis(this, focusDataIndices || focus, emphasisModel.get('blurScope'));
  58794. };
  58795. SunburstPiece.prototype._updateLabel = function (seriesModel) {
  58796. var _this = this;
  58797. var itemModel = this.node.getModel();
  58798. var normalLabelModel = itemModel.getModel('label');
  58799. var layout = this.node.getLayout();
  58800. var angle = layout.endAngle - layout.startAngle;
  58801. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  58802. var dx = Math.cos(midAngle);
  58803. var dy = Math.sin(midAngle);
  58804. var sector = this;
  58805. var label = sector.getTextContent();
  58806. var dataIndex = this.node.dataIndex;
  58807. var labelMinAngle = normalLabelModel.get('minAngle') / 180 * Math.PI;
  58808. var isNormalShown = normalLabelModel.get('show') && !(labelMinAngle != null && Math.abs(angle) < labelMinAngle);
  58809. label.ignore = !isNormalShown; // TODO use setLabelStyle
  58810. each(DISPLAY_STATES, function (stateName) {
  58811. var labelStateModel = stateName === 'normal' ? itemModel.getModel('label') : itemModel.getModel([stateName, 'label']);
  58812. var isNormal = stateName === 'normal';
  58813. var state = isNormal ? label : label.ensureState(stateName);
  58814. var text = seriesModel.getFormattedLabel(dataIndex, stateName);
  58815. if (isNormal) {
  58816. text = text || _this.node.name;
  58817. }
  58818. state.style = createTextStyle(labelStateModel, {}, null, stateName !== 'normal', true);
  58819. if (text) {
  58820. state.style.text = text;
  58821. } // Not displaying text when angle is too small
  58822. var isShown = labelStateModel.get('show');
  58823. if (isShown != null && !isNormal) {
  58824. state.ignore = !isShown;
  58825. }
  58826. var labelPosition = getLabelAttr(labelStateModel, 'position');
  58827. var sectorState = isNormal ? sector : sector.states[stateName];
  58828. var labelColor = sectorState.style.fill;
  58829. sectorState.textConfig = {
  58830. outsideFill: labelStateModel.get('color') === 'inherit' ? labelColor : null,
  58831. inside: labelPosition !== 'outside'
  58832. };
  58833. var r;
  58834. var labelPadding = getLabelAttr(labelStateModel, 'distance') || 0;
  58835. var textAlign = getLabelAttr(labelStateModel, 'align');
  58836. if (labelPosition === 'outside') {
  58837. r = layout.r + labelPadding;
  58838. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  58839. } else {
  58840. if (!textAlign || textAlign === 'center') {
  58841. r = (layout.r + layout.r0) / 2;
  58842. textAlign = 'center';
  58843. } else if (textAlign === 'left') {
  58844. r = layout.r0 + labelPadding;
  58845. if (midAngle > Math.PI / 2) {
  58846. textAlign = 'right';
  58847. }
  58848. } else if (textAlign === 'right') {
  58849. r = layout.r - labelPadding;
  58850. if (midAngle > Math.PI / 2) {
  58851. textAlign = 'left';
  58852. }
  58853. }
  58854. }
  58855. state.style.align = textAlign;
  58856. state.style.verticalAlign = getLabelAttr(labelStateModel, 'verticalAlign') || 'middle';
  58857. state.x = r * dx + layout.cx;
  58858. state.y = r * dy + layout.cy;
  58859. var rotateType = getLabelAttr(labelStateModel, 'rotate');
  58860. var rotate = 0;
  58861. if (rotateType === 'radial') {
  58862. rotate = -midAngle;
  58863. if (rotate < -Math.PI / 2) {
  58864. rotate += Math.PI;
  58865. }
  58866. } else if (rotateType === 'tangential') {
  58867. rotate = Math.PI / 2 - midAngle;
  58868. if (rotate > Math.PI / 2) {
  58869. rotate -= Math.PI;
  58870. } else if (rotate < -Math.PI / 2) {
  58871. rotate += Math.PI;
  58872. }
  58873. } else if (typeof rotateType === 'number') {
  58874. rotate = rotateType * Math.PI / 180;
  58875. }
  58876. state.rotation = rotate;
  58877. });
  58878. function getLabelAttr(model, name) {
  58879. var stateAttr = model.get(name);
  58880. if (stateAttr == null) {
  58881. return normalLabelModel.get(name);
  58882. }
  58883. return stateAttr;
  58884. }
  58885. label.dirtyStyle();
  58886. };
  58887. return SunburstPiece;
  58888. }(Sector);
  58889. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  58890. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  58891. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  58892. function installSunburstAction(registers) {
  58893. registers.registerAction({
  58894. type: ROOT_TO_NODE_ACTION,
  58895. update: 'updateView'
  58896. }, function (payload, ecModel) {
  58897. ecModel.eachComponent({
  58898. mainType: 'series',
  58899. subType: 'sunburst',
  58900. query: payload
  58901. }, handleRootToNode);
  58902. function handleRootToNode(model, index) {
  58903. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION], model);
  58904. if (targetInfo) {
  58905. var originViewRoot = model.getViewRoot();
  58906. if (originViewRoot) {
  58907. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  58908. }
  58909. model.resetViewRoot(targetInfo.node);
  58910. }
  58911. }
  58912. });
  58913. registers.registerAction({
  58914. type: HIGHLIGHT_ACTION,
  58915. update: 'none'
  58916. }, function (payload, ecModel, api) {
  58917. // Clone
  58918. payload = extend({}, payload);
  58919. ecModel.eachComponent({
  58920. mainType: 'series',
  58921. subType: 'sunburst',
  58922. query: payload
  58923. }, handleHighlight);
  58924. function handleHighlight(model) {
  58925. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  58926. if (targetInfo) {
  58927. payload.dataIndex = targetInfo.node.dataIndex;
  58928. }
  58929. }
  58930. if ("development" !== 'production') {
  58931. deprecateReplaceLog('highlight', 'sunburstHighlight');
  58932. } // Fast forward action
  58933. api.dispatchAction(extend(payload, {
  58934. type: 'highlight'
  58935. }));
  58936. });
  58937. registers.registerAction({
  58938. type: UNHIGHLIGHT_ACTION,
  58939. update: 'updateView'
  58940. }, function (payload, ecModel, api) {
  58941. payload = extend({}, payload);
  58942. if ("development" !== 'production') {
  58943. deprecateReplaceLog('downplay', 'sunburstUnhighlight');
  58944. }
  58945. api.dispatchAction(extend(payload, {
  58946. type: 'downplay'
  58947. }));
  58948. });
  58949. }
  58950. var SunburstView =
  58951. /** @class */
  58952. function (_super) {
  58953. __extends(SunburstView, _super);
  58954. function SunburstView() {
  58955. var _this = _super !== null && _super.apply(this, arguments) || this;
  58956. _this.type = SunburstView.type;
  58957. return _this;
  58958. }
  58959. SunburstView.prototype.render = function (seriesModel, ecModel, api, // @ts-ignore
  58960. payload) {
  58961. var self = this;
  58962. this.seriesModel = seriesModel;
  58963. this.api = api;
  58964. this.ecModel = ecModel;
  58965. var data = seriesModel.getData();
  58966. var virtualRoot = data.tree.root;
  58967. var newRoot = seriesModel.getViewRoot();
  58968. var group = this.group;
  58969. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  58970. var newChildren = [];
  58971. newRoot.eachNode(function (node) {
  58972. newChildren.push(node);
  58973. });
  58974. var oldChildren = this._oldChildren || [];
  58975. dualTravel(newChildren, oldChildren);
  58976. renderRollUp(virtualRoot, newRoot);
  58977. this._initEvents();
  58978. this._oldChildren = newChildren;
  58979. function dualTravel(newChildren, oldChildren) {
  58980. if (newChildren.length === 0 && oldChildren.length === 0) {
  58981. return;
  58982. }
  58983. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  58984. function getKey(node) {
  58985. return node.getId();
  58986. }
  58987. function processNode(newIdx, oldIdx) {
  58988. var newNode = newIdx == null ? null : newChildren[newIdx];
  58989. var oldNode = oldIdx == null ? null : oldChildren[oldIdx];
  58990. doRenderNode(newNode, oldNode);
  58991. }
  58992. }
  58993. function doRenderNode(newNode, oldNode) {
  58994. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  58995. // Not render data with value 0
  58996. newNode = null;
  58997. }
  58998. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  58999. if (oldNode && oldNode.piece) {
  59000. if (newNode) {
  59001. // Update
  59002. oldNode.piece.updateData(false, newNode, seriesModel, ecModel, api); // For tooltip
  59003. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  59004. } else {
  59005. // Remove
  59006. removeNode(oldNode);
  59007. }
  59008. } else if (newNode) {
  59009. // Add
  59010. var piece = new SunburstPiece(newNode, seriesModel, ecModel, api);
  59011. group.add(piece); // For tooltip
  59012. data.setItemGraphicEl(newNode.dataIndex, piece);
  59013. }
  59014. }
  59015. }
  59016. function removeNode(node) {
  59017. if (!node) {
  59018. return;
  59019. }
  59020. if (node.piece) {
  59021. group.remove(node.piece);
  59022. node.piece = null;
  59023. }
  59024. }
  59025. function renderRollUp(virtualRoot, viewRoot) {
  59026. if (viewRoot.depth > 0) {
  59027. // Render
  59028. if (self.virtualPiece) {
  59029. // Update
  59030. self.virtualPiece.updateData(false, virtualRoot, seriesModel, ecModel, api);
  59031. } else {
  59032. // Add
  59033. self.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel, api);
  59034. group.add(self.virtualPiece);
  59035. } // TODO event scope
  59036. viewRoot.piece.off('click');
  59037. self.virtualPiece.on('click', function (e) {
  59038. self._rootToNode(viewRoot.parentNode);
  59039. });
  59040. } else if (self.virtualPiece) {
  59041. // Remove
  59042. group.remove(self.virtualPiece);
  59043. self.virtualPiece = null;
  59044. }
  59045. }
  59046. };
  59047. /**
  59048. * @private
  59049. */
  59050. SunburstView.prototype._initEvents = function () {
  59051. var _this = this;
  59052. this.group.off('click');
  59053. this.group.on('click', function (e) {
  59054. var targetFound = false;
  59055. var viewRoot = _this.seriesModel.getViewRoot();
  59056. viewRoot.eachNode(function (node) {
  59057. if (!targetFound && node.piece && node.piece === e.target) {
  59058. var nodeClick = node.getModel().get('nodeClick');
  59059. if (nodeClick === 'rootToNode') {
  59060. _this._rootToNode(node);
  59061. } else if (nodeClick === 'link') {
  59062. var itemModel = node.getModel();
  59063. var link = itemModel.get('link');
  59064. if (link) {
  59065. var linkTarget = itemModel.get('target', true) || '_blank';
  59066. windowOpen(link, linkTarget);
  59067. }
  59068. }
  59069. targetFound = true;
  59070. }
  59071. });
  59072. });
  59073. };
  59074. /**
  59075. * @private
  59076. */
  59077. SunburstView.prototype._rootToNode = function (node) {
  59078. if (node !== this.seriesModel.getViewRoot()) {
  59079. this.api.dispatchAction({
  59080. type: ROOT_TO_NODE_ACTION,
  59081. from: this.uid,
  59082. seriesId: this.seriesModel.id,
  59083. targetNode: node
  59084. });
  59085. }
  59086. };
  59087. /**
  59088. * @implement
  59089. */
  59090. SunburstView.prototype.containPoint = function (point, seriesModel) {
  59091. var treeRoot = seriesModel.getData();
  59092. var itemLayout = treeRoot.getItemLayout(0);
  59093. if (itemLayout) {
  59094. var dx = point[0] - itemLayout.cx;
  59095. var dy = point[1] - itemLayout.cy;
  59096. var radius = Math.sqrt(dx * dx + dy * dy);
  59097. return radius <= itemLayout.r && radius >= itemLayout.r0;
  59098. }
  59099. };
  59100. SunburstView.type = 'sunburst';
  59101. return SunburstView;
  59102. }(ChartView);
  59103. var SunburstSeriesModel =
  59104. /** @class */
  59105. function (_super) {
  59106. __extends(SunburstSeriesModel, _super);
  59107. function SunburstSeriesModel() {
  59108. var _this = _super !== null && _super.apply(this, arguments) || this;
  59109. _this.type = SunburstSeriesModel.type;
  59110. _this.ignoreStyleOnData = true;
  59111. return _this;
  59112. }
  59113. SunburstSeriesModel.prototype.getInitialData = function (option, ecModel) {
  59114. // Create a virtual root.
  59115. var root = {
  59116. name: option.name,
  59117. children: option.data
  59118. };
  59119. completeTreeValue$1(root);
  59120. var levelModels = map(option.levels || [], function (levelDefine) {
  59121. return new Model(levelDefine, this, ecModel);
  59122. }, this); // Make sure always a new tree is created when setOption,
  59123. // in TreemapView, we check whether oldTree === newTree
  59124. // to choose mappings approach among old shapes and new shapes.
  59125. var tree = Tree.createTree(root, this, beforeLink);
  59126. function beforeLink(nodeData) {
  59127. nodeData.wrapMethod('getItemModel', function (model, idx) {
  59128. var node = tree.getNodeByDataIndex(idx);
  59129. var levelModel = levelModels[node.depth];
  59130. levelModel && (model.parentModel = levelModel);
  59131. return model;
  59132. });
  59133. }
  59134. return tree.data;
  59135. };
  59136. SunburstSeriesModel.prototype.optionUpdated = function () {
  59137. this.resetViewRoot();
  59138. };
  59139. /*
  59140. * @override
  59141. */
  59142. SunburstSeriesModel.prototype.getDataParams = function (dataIndex) {
  59143. var params = _super.prototype.getDataParams.apply(this, arguments);
  59144. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  59145. params.treePathInfo = wrapTreePathInfo(node, this);
  59146. return params;
  59147. };
  59148. SunburstSeriesModel.prototype.getViewRoot = function () {
  59149. return this._viewRoot;
  59150. };
  59151. SunburstSeriesModel.prototype.resetViewRoot = function (viewRoot) {
  59152. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  59153. var root = this.getRawData().tree.root;
  59154. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  59155. this._viewRoot = root;
  59156. }
  59157. };
  59158. SunburstSeriesModel.prototype.enableAriaDecal = function () {
  59159. enableAriaDecalForTree(this);
  59160. };
  59161. SunburstSeriesModel.type = 'series.sunburst';
  59162. SunburstSeriesModel.defaultOption = {
  59163. zlevel: 0,
  59164. z: 2,
  59165. // 默认全局居中
  59166. center: ['50%', '50%'],
  59167. radius: [0, '75%'],
  59168. // 默认顺时针
  59169. clockwise: true,
  59170. startAngle: 90,
  59171. // 最小角度改为0
  59172. minAngle: 0,
  59173. // If still show when all data zero.
  59174. stillShowZeroSum: true,
  59175. // 'rootToNode', 'link', or false
  59176. nodeClick: 'rootToNode',
  59177. renderLabelForZeroData: false,
  59178. label: {
  59179. // could be: 'radial', 'tangential', or 'none'
  59180. rotate: 'radial',
  59181. show: true,
  59182. opacity: 1,
  59183. // 'left' is for inner side of inside, and 'right' is for outter
  59184. // side for inside
  59185. align: 'center',
  59186. position: 'inside',
  59187. distance: 5,
  59188. silent: true
  59189. },
  59190. itemStyle: {
  59191. borderWidth: 1,
  59192. borderColor: 'white',
  59193. borderType: 'solid',
  59194. shadowBlur: 0,
  59195. shadowColor: 'rgba(0, 0, 0, 0.2)',
  59196. shadowOffsetX: 0,
  59197. shadowOffsetY: 0,
  59198. opacity: 1
  59199. },
  59200. emphasis: {
  59201. focus: 'descendant'
  59202. },
  59203. blur: {
  59204. itemStyle: {
  59205. opacity: 0.2
  59206. },
  59207. label: {
  59208. opacity: 0.1
  59209. }
  59210. },
  59211. // Animation type canbe expansion, scale
  59212. animationType: 'expansion',
  59213. animationDuration: 1000,
  59214. animationDurationUpdate: 500,
  59215. data: [],
  59216. levels: [],
  59217. /**
  59218. * Sort order.
  59219. *
  59220. * Valid values: 'desc', 'asc', null, or callback function.
  59221. * 'desc' and 'asc' for descend and ascendant order;
  59222. * null for not sorting;
  59223. * example of callback function:
  59224. * function(nodeA, nodeB) {
  59225. * return nodeA.getValue() - nodeB.getValue();
  59226. * }
  59227. */
  59228. sort: 'desc'
  59229. };
  59230. return SunburstSeriesModel;
  59231. }(SeriesModel);
  59232. function completeTreeValue$1(dataNode) {
  59233. // Postorder travel tree.
  59234. // If value of none-leaf node is not set,
  59235. // calculate it by suming up the value of all children.
  59236. var sum = 0;
  59237. each(dataNode.children, function (child) {
  59238. completeTreeValue$1(child);
  59239. var childValue = child.value; // TODO First value of array must be a number
  59240. isArray(childValue) && (childValue = childValue[0]);
  59241. sum += childValue;
  59242. });
  59243. var thisValue = dataNode.value;
  59244. if (isArray(thisValue)) {
  59245. thisValue = thisValue[0];
  59246. }
  59247. if (thisValue == null || isNaN(thisValue)) {
  59248. thisValue = sum;
  59249. } // Value should not less than 0.
  59250. if (thisValue < 0) {
  59251. thisValue = 0;
  59252. }
  59253. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  59254. }
  59255. var RADIAN$2 = Math.PI / 180;
  59256. function sunburstLayout(seriesType, ecModel, api) {
  59257. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  59258. var center = seriesModel.get('center');
  59259. var radius = seriesModel.get('radius');
  59260. if (!isArray(radius)) {
  59261. radius = [0, radius];
  59262. }
  59263. if (!isArray(center)) {
  59264. center = [center, center];
  59265. }
  59266. var width = api.getWidth();
  59267. var height = api.getHeight();
  59268. var size = Math.min(width, height);
  59269. var cx = parsePercent$1(center[0], width);
  59270. var cy = parsePercent$1(center[1], height);
  59271. var r0 = parsePercent$1(radius[0], size / 2);
  59272. var r = parsePercent$1(radius[1], size / 2);
  59273. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  59274. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  59275. var virtualRoot = seriesModel.getData().tree.root;
  59276. var treeRoot = seriesModel.getViewRoot();
  59277. var rootDepth = treeRoot.depth;
  59278. var sort = seriesModel.get('sort');
  59279. if (sort != null) {
  59280. initChildren$1(treeRoot, sort);
  59281. }
  59282. var validDataCount = 0;
  59283. each(treeRoot.children, function (child) {
  59284. !isNaN(child.getValue()) && validDataCount++;
  59285. });
  59286. var sum = treeRoot.getValue(); // Sum may be 0
  59287. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  59288. var renderRollupNode = treeRoot.depth > 0;
  59289. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  59290. var rPerLevel = (r - r0) / (levels || 1);
  59291. var clockwise = seriesModel.get('clockwise');
  59292. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  59293. // let restAngle = PI2;
  59294. // let valueSumLargerThanMinAngle = 0;
  59295. var dir = clockwise ? 1 : -1;
  59296. /**
  59297. * Render a tree
  59298. * @return increased angle
  59299. */
  59300. var renderNode = function (node, startAngle) {
  59301. if (!node) {
  59302. return;
  59303. }
  59304. var endAngle = startAngle; // Render self
  59305. if (node !== virtualRoot) {
  59306. // Tree node is virtual, so it doesn't need to be drawn
  59307. var value = node.getValue();
  59308. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  59309. if (angle < minAngle) {
  59310. angle = minAngle; // restAngle -= minAngle;
  59311. } // else {
  59312. // valueSumLargerThanMinAngle += value;
  59313. // }
  59314. endAngle = startAngle + dir * angle;
  59315. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  59316. var rStart = r0 + rPerLevel * depth;
  59317. var rEnd = r0 + rPerLevel * (depth + 1);
  59318. var itemModel = node.getModel(); // @ts-ignore. TODO this is not provided to developer yet. Rename it.
  59319. if (itemModel.get('r0') != null) {
  59320. // @ts-ignore
  59321. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  59322. } // @ts-ignore
  59323. if (itemModel.get('r') != null) {
  59324. // @ts-ignore
  59325. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  59326. }
  59327. node.setLayout({
  59328. angle: angle,
  59329. startAngle: startAngle,
  59330. endAngle: endAngle,
  59331. clockwise: clockwise,
  59332. cx: cx,
  59333. cy: cy,
  59334. r0: rStart,
  59335. r: rEnd
  59336. });
  59337. } // Render children
  59338. if (node.children && node.children.length) {
  59339. // currentAngle = startAngle;
  59340. var siblingAngle_1 = 0;
  59341. each(node.children, function (node) {
  59342. siblingAngle_1 += renderNode(node, startAngle + siblingAngle_1);
  59343. });
  59344. }
  59345. return endAngle - startAngle;
  59346. }; // Virtual root node for roll up
  59347. if (renderRollupNode) {
  59348. var rStart = r0;
  59349. var rEnd = r0 + rPerLevel;
  59350. var angle = Math.PI * 2;
  59351. virtualRoot.setLayout({
  59352. angle: angle,
  59353. startAngle: startAngle,
  59354. endAngle: startAngle + angle,
  59355. clockwise: clockwise,
  59356. cx: cx,
  59357. cy: cy,
  59358. r0: rStart,
  59359. r: rEnd
  59360. });
  59361. }
  59362. renderNode(treeRoot, startAngle);
  59363. });
  59364. }
  59365. /**
  59366. * Init node children by order and update visual
  59367. */
  59368. function initChildren$1(node, sortOrder) {
  59369. var children = node.children || [];
  59370. node.children = sort$2(children, sortOrder); // Init children recursively
  59371. if (children.length) {
  59372. each(node.children, function (child) {
  59373. initChildren$1(child, sortOrder);
  59374. });
  59375. }
  59376. }
  59377. /**
  59378. * Sort children nodes
  59379. *
  59380. * @param {TreeNode[]} children children of node to be sorted
  59381. * @param {string | function | null} sort sort method
  59382. * See SunburstSeries.js for details.
  59383. */
  59384. function sort$2(children, sortOrder) {
  59385. if (typeof sortOrder === 'function') {
  59386. var sortTargets = map(children, function (child, idx) {
  59387. var value = child.getValue();
  59388. return {
  59389. params: {
  59390. depth: child.depth,
  59391. height: child.height,
  59392. dataIndex: child.dataIndex,
  59393. getValue: function () {
  59394. return value;
  59395. }
  59396. },
  59397. index: idx
  59398. };
  59399. });
  59400. sortTargets.sort(function (a, b) {
  59401. return sortOrder(a.params, b.params);
  59402. });
  59403. return map(sortTargets, function (target) {
  59404. return children[target.index];
  59405. });
  59406. } else {
  59407. var isAsc_1 = sortOrder === 'asc';
  59408. return children.sort(function (a, b) {
  59409. var diff = (a.getValue() - b.getValue()) * (isAsc_1 ? 1 : -1);
  59410. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc_1 ? -1 : 1) : diff;
  59411. });
  59412. }
  59413. }
  59414. function sunburstVisual(ecModel) {
  59415. var paletteScope = {}; // Default color strategy
  59416. function pickColor(node, seriesModel, treeHeight) {
  59417. // Choose color from palette based on the first level.
  59418. var current = node;
  59419. while (current && current.depth > 1) {
  59420. current = current.parentNode;
  59421. }
  59422. var color = seriesModel.getColorFromPalette(current.name || current.dataIndex + '', paletteScope);
  59423. if (node.depth > 1 && typeof color === 'string') {
  59424. // Lighter on the deeper level.
  59425. color = lift(color, (node.depth - 1) / (treeHeight - 1) * 0.5);
  59426. }
  59427. return color;
  59428. }
  59429. ecModel.eachSeriesByType('sunburst', function (seriesModel) {
  59430. var data = seriesModel.getData();
  59431. var tree = data.tree;
  59432. tree.eachNode(function (node) {
  59433. var model = node.getModel();
  59434. var style = model.getModel('itemStyle').getItemStyle();
  59435. if (!style.fill) {
  59436. style.fill = pickColor(node, seriesModel, tree.root.height);
  59437. }
  59438. var existsStyle = data.ensureUniqueItemVisual(node.dataIndex, 'style');
  59439. extend(existsStyle, style);
  59440. });
  59441. });
  59442. }
  59443. function install$q(registers) {
  59444. registers.registerChartView(SunburstView);
  59445. registers.registerSeriesModel(SunburstSeriesModel);
  59446. registers.registerLayout(curry(sunburstLayout, 'sunburst'));
  59447. registers.registerProcessor(curry(dataFilter, 'sunburst'));
  59448. registers.registerVisual(sunburstVisual);
  59449. installSunburstAction(registers);
  59450. }
  59451. function dataToCoordSize(dataSize, dataItem) {
  59452. // dataItem is necessary in log axis.
  59453. dataItem = dataItem || [0, 0];
  59454. return map(['x', 'y'], function (dim, dimIdx) {
  59455. var axis = this.getAxis(dim);
  59456. var val = dataItem[dimIdx];
  59457. var halfSize = dataSize[dimIdx] / 2;
  59458. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  59459. }, this);
  59460. }
  59461. function cartesianPrepareCustom(coordSys) {
  59462. var rect = coordSys.master.getRect();
  59463. return {
  59464. coordSys: {
  59465. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  59466. type: 'cartesian2d',
  59467. x: rect.x,
  59468. y: rect.y,
  59469. width: rect.width,
  59470. height: rect.height
  59471. },
  59472. api: {
  59473. coord: function (data) {
  59474. // do not provide "out" param
  59475. return coordSys.dataToPoint(data);
  59476. },
  59477. size: bind(dataToCoordSize, coordSys)
  59478. }
  59479. };
  59480. }
  59481. function dataToCoordSize$1(dataSize, dataItem) {
  59482. dataItem = dataItem || [0, 0];
  59483. return map([0, 1], function (dimIdx) {
  59484. var val = dataItem[dimIdx];
  59485. var halfSize = dataSize[dimIdx] / 2;
  59486. var p1 = [];
  59487. var p2 = [];
  59488. p1[dimIdx] = val - halfSize;
  59489. p2[dimIdx] = val + halfSize;
  59490. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  59491. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  59492. }, this);
  59493. }
  59494. function geoPrepareCustom(coordSys) {
  59495. var rect = coordSys.getBoundingRect();
  59496. return {
  59497. coordSys: {
  59498. type: 'geo',
  59499. x: rect.x,
  59500. y: rect.y,
  59501. width: rect.width,
  59502. height: rect.height,
  59503. zoom: coordSys.getZoom()
  59504. },
  59505. api: {
  59506. coord: function (data) {
  59507. // do not provide "out" and noRoam param,
  59508. // Compatible with this usage:
  59509. // echarts.util.map(item.points, api.coord)
  59510. return coordSys.dataToPoint(data);
  59511. },
  59512. size: bind(dataToCoordSize$1, coordSys)
  59513. }
  59514. };
  59515. }
  59516. function dataToCoordSize$2(dataSize, dataItem) {
  59517. // dataItem is necessary in log axis.
  59518. var axis = this.getAxis();
  59519. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  59520. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  59521. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  59522. }
  59523. function singlePrepareCustom(coordSys) {
  59524. var rect = coordSys.getRect();
  59525. return {
  59526. coordSys: {
  59527. type: 'singleAxis',
  59528. x: rect.x,
  59529. y: rect.y,
  59530. width: rect.width,
  59531. height: rect.height
  59532. },
  59533. api: {
  59534. coord: function (val) {
  59535. // do not provide "out" param
  59536. return coordSys.dataToPoint(val);
  59537. },
  59538. size: bind(dataToCoordSize$2, coordSys)
  59539. }
  59540. };
  59541. }
  59542. function dataToCoordSize$3(dataSize, dataItem) {
  59543. // dataItem is necessary in log axis.
  59544. dataItem = dataItem || [0, 0];
  59545. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  59546. var getterName = 'get' + dim + 'Axis'; // TODO: TYPE Check Angle Axis
  59547. var axis = this[getterName]();
  59548. var val = dataItem[dimIdx];
  59549. var halfSize = dataSize[dimIdx] / 2;
  59550. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  59551. if (dim === 'Angle') {
  59552. result = result * Math.PI / 180;
  59553. }
  59554. return result;
  59555. }, this);
  59556. }
  59557. function polarPrepareCustom(coordSys) {
  59558. var radiusAxis = coordSys.getRadiusAxis();
  59559. var angleAxis = coordSys.getAngleAxis();
  59560. var radius = radiusAxis.getExtent();
  59561. radius[0] > radius[1] && radius.reverse();
  59562. return {
  59563. coordSys: {
  59564. type: 'polar',
  59565. cx: coordSys.cx,
  59566. cy: coordSys.cy,
  59567. r: radius[1],
  59568. r0: radius[0]
  59569. },
  59570. api: {
  59571. coord: function (data) {
  59572. var radius = radiusAxis.dataToRadius(data[0]);
  59573. var angle = angleAxis.dataToAngle(data[1]);
  59574. var coord = coordSys.coordToPoint([radius, angle]);
  59575. coord.push(radius, angle * Math.PI / 180);
  59576. return coord;
  59577. },
  59578. size: bind(dataToCoordSize$3, coordSys)
  59579. }
  59580. };
  59581. }
  59582. /*
  59583. * Licensed to the Apache Software Foundation (ASF) under one
  59584. * or more contributor license agreements. See the NOTICE file
  59585. * distributed with this work for additional information
  59586. * regarding copyright ownership. The ASF licenses this file
  59587. * to you under the Apache License, Version 2.0 (the
  59588. * "License"); you may not use this file except in compliance
  59589. * with the License. You may obtain a copy of the License at
  59590. *
  59591. * http://www.apache.org/licenses/LICENSE-2.0
  59592. *
  59593. * Unless required by applicable law or agreed to in writing,
  59594. * software distributed under the License is distributed on an
  59595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59596. * KIND, either express or implied. See the License for the
  59597. * specific language governing permissions and limitations
  59598. * under the License.
  59599. */
  59600. /**
  59601. * AUTO-GENERATED FILE. DO NOT MODIFY.
  59602. */
  59603. /*
  59604. * Licensed to the Apache Software Foundation (ASF) under one
  59605. * or more contributor license agreements. See the NOTICE file
  59606. * distributed with this work for additional information
  59607. * regarding copyright ownership. The ASF licenses this file
  59608. * to you under the Apache License, Version 2.0 (the
  59609. * "License"); you may not use this file except in compliance
  59610. * with the License. You may obtain a copy of the License at
  59611. *
  59612. * http://www.apache.org/licenses/LICENSE-2.0
  59613. *
  59614. * Unless required by applicable law or agreed to in writing,
  59615. * software distributed under the License is distributed on an
  59616. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59617. * KIND, either express or implied. See the License for the
  59618. * specific language governing permissions and limitations
  59619. * under the License.
  59620. */
  59621. function calendarPrepareCustom(coordSys) {
  59622. var rect = coordSys.getRect();
  59623. var rangeInfo = coordSys.getRangeInfo();
  59624. return {
  59625. coordSys: {
  59626. type: 'calendar',
  59627. x: rect.x,
  59628. y: rect.y,
  59629. width: rect.width,
  59630. height: rect.height,
  59631. cellWidth: coordSys.getCellWidth(),
  59632. cellHeight: coordSys.getCellHeight(),
  59633. rangeInfo: {
  59634. start: rangeInfo.start,
  59635. end: rangeInfo.end,
  59636. weeks: rangeInfo.weeks,
  59637. dayCount: rangeInfo.allDay
  59638. }
  59639. },
  59640. api: {
  59641. coord: function (data, clamp) {
  59642. return coordSys.dataToPoint(data, clamp);
  59643. }
  59644. }
  59645. };
  59646. }
  59647. var deprecatedLogs = {};
  59648. /**
  59649. * Whether need to call `convertEC4CompatibleStyle`.
  59650. */
  59651. function isEC4CompatibleStyle(style, elType, hasOwnTextContentOption, hasOwnTextConfig) {
  59652. // Since echarts5, `RectText` is separated from its host element and style.text
  59653. // does not exist any more. The compat work brings some extra burden on performance.
  59654. // So we provide:
  59655. // `legacy: true` force make compat.
  59656. // `legacy: false`, force do not compat.
  59657. // `legacy` not set: auto detect wheter legacy.
  59658. // But in this case we do not compat (difficult to detect and rare case):
  59659. // Becuse custom series and graphic component support "merge", users may firstly
  59660. // only set `textStrokeWidth` style or secondly only set `text`.
  59661. return style && (style.legacy || style.legacy !== false && !hasOwnTextContentOption && !hasOwnTextConfig && elType !== 'tspan' // Difficult to detect whether legacy for a "text" el.
  59662. && (elType === 'text' || hasOwn(style, 'text')));
  59663. }
  59664. /**
  59665. * `EC4CompatibleStyle` is style that might be in echarts4 format or echarts5 format.
  59666. * @param hostStyle The properties might be modified.
  59667. * @return If be text el, `textContentStyle` and `textConfig` will not be retured.
  59668. * Otherwise a `textContentStyle` and `textConfig` will be created, whose props area
  59669. * retried from the `hostStyle`.
  59670. */
  59671. function convertFromEC4CompatibleStyle(hostStyle, elType, isNormal) {
  59672. var srcStyle = hostStyle;
  59673. var textConfig;
  59674. var textContent;
  59675. var textContentStyle;
  59676. if (elType === 'text') {
  59677. textContentStyle = srcStyle;
  59678. } else {
  59679. textContentStyle = {};
  59680. hasOwn(srcStyle, 'text') && (textContentStyle.text = srcStyle.text);
  59681. hasOwn(srcStyle, 'rich') && (textContentStyle.rich = srcStyle.rich);
  59682. hasOwn(srcStyle, 'textFill') && (textContentStyle.fill = srcStyle.textFill);
  59683. hasOwn(srcStyle, 'textStroke') && (textContentStyle.stroke = srcStyle.textStroke);
  59684. textContent = {
  59685. type: 'text',
  59686. style: textContentStyle,
  59687. // ec4 do not support rectText trigger.
  59688. // And when text postion is different in normal and emphasis
  59689. // => hover text trigger emphasis;
  59690. // => text position changed, leave mouse pointer immediately;
  59691. // That might cause state incorrect.
  59692. silent: true
  59693. };
  59694. textConfig = {};
  59695. var hasOwnPos = hasOwn(srcStyle, 'textPosition');
  59696. if (isNormal) {
  59697. textConfig.position = hasOwnPos ? srcStyle.textPosition : 'inside';
  59698. } else {
  59699. hasOwnPos && (textConfig.position = srcStyle.textPosition);
  59700. }
  59701. hasOwn(srcStyle, 'textPosition') && (textConfig.position = srcStyle.textPosition);
  59702. hasOwn(srcStyle, 'textOffset') && (textConfig.offset = srcStyle.textOffset);
  59703. hasOwn(srcStyle, 'textRotation') && (textConfig.rotation = srcStyle.textRotation);
  59704. hasOwn(srcStyle, 'textDistance') && (textConfig.distance = srcStyle.textDistance);
  59705. }
  59706. convertEC4CompatibleRichItem(textContentStyle, hostStyle);
  59707. each(textContentStyle.rich, function (richItem) {
  59708. convertEC4CompatibleRichItem(richItem, richItem);
  59709. });
  59710. return {
  59711. textConfig: textConfig,
  59712. textContent: textContent
  59713. };
  59714. }
  59715. /**
  59716. * The result will be set to `out`.
  59717. */
  59718. function convertEC4CompatibleRichItem(out, richItem) {
  59719. if (!richItem) {
  59720. return;
  59721. } // (1) For simplicity, make textXXX properties (deprecated since ec5) has
  59722. // higher priority. For example, consider in ec4 `borderColor: 5, textBorderColor: 10`
  59723. // on a rect means `borderColor: 4` on the rect and `borderColor: 10` on an attached
  59724. // richText in ec5.
  59725. // (2) `out === richItem` if and only if `out` is text el or rich item.
  59726. // So we can overwite existing props in `out` since textXXX has higher priority.
  59727. richItem.font = richItem.textFont || richItem.font;
  59728. hasOwn(richItem, 'textStrokeWidth') && (out.lineWidth = richItem.textStrokeWidth);
  59729. hasOwn(richItem, 'textAlign') && (out.align = richItem.textAlign);
  59730. hasOwn(richItem, 'textVerticalAlign') && (out.verticalAlign = richItem.textVerticalAlign);
  59731. hasOwn(richItem, 'textLineHeight') && (out.lineHeight = richItem.textLineHeight);
  59732. hasOwn(richItem, 'textWidth') && (out.width = richItem.textWidth);
  59733. hasOwn(richItem, 'textHeight') && (out.height = richItem.textHeight);
  59734. hasOwn(richItem, 'textBackgroundColor') && (out.backgroundColor = richItem.textBackgroundColor);
  59735. hasOwn(richItem, 'textPadding') && (out.padding = richItem.textPadding);
  59736. hasOwn(richItem, 'textBorderColor') && (out.borderColor = richItem.textBorderColor);
  59737. hasOwn(richItem, 'textBorderWidth') && (out.borderWidth = richItem.textBorderWidth);
  59738. hasOwn(richItem, 'textBorderRadius') && (out.borderRadius = richItem.textBorderRadius);
  59739. hasOwn(richItem, 'textBoxShadowColor') && (out.shadowColor = richItem.textBoxShadowColor);
  59740. hasOwn(richItem, 'textBoxShadowBlur') && (out.shadowBlur = richItem.textBoxShadowBlur);
  59741. hasOwn(richItem, 'textBoxShadowOffsetX') && (out.shadowOffsetX = richItem.textBoxShadowOffsetX);
  59742. hasOwn(richItem, 'textBoxShadowOffsetY') && (out.shadowOffsetY = richItem.textBoxShadowOffsetY);
  59743. }
  59744. /**
  59745. * Convert to pure echarts4 format style.
  59746. * `itemStyle` will be modified, added with ec4 style properties from
  59747. * `textStyle` and `textConfig`.
  59748. *
  59749. * [Caveat]: For simplicity, `insideRollback` in ec4 does not compat, where
  59750. * `styleEmphasis: {textFill: 'red'}` will remove the normal auto added stroke.
  59751. */
  59752. function convertToEC4StyleForCustomSerise(itemStl, txStl, txCfg) {
  59753. var out = itemStl; // See `custom.ts`, a trick to set extra `textPosition` firstly.
  59754. out.textPosition = out.textPosition || txCfg.position || 'inside';
  59755. txCfg.offset != null && (out.textOffset = txCfg.offset);
  59756. txCfg.rotation != null && (out.textRotation = txCfg.rotation);
  59757. txCfg.distance != null && (out.textDistance = txCfg.distance);
  59758. var isInside = out.textPosition.indexOf('inside') >= 0;
  59759. var hostFill = itemStl.fill || '#000';
  59760. convertToEC4RichItem(out, txStl);
  59761. var textFillNotSet = out.textFill == null;
  59762. if (isInside) {
  59763. if (textFillNotSet) {
  59764. out.textFill = txCfg.insideFill || '#fff';
  59765. !out.textStroke && txCfg.insideStroke && (out.textStroke = txCfg.insideStroke);
  59766. !out.textStroke && (out.textStroke = hostFill);
  59767. out.textStrokeWidth == null && (out.textStrokeWidth = 2);
  59768. }
  59769. } else {
  59770. if (textFillNotSet) {
  59771. out.textFill = txCfg.outsideFill || hostFill;
  59772. }
  59773. !out.textStroke && txCfg.outsideStroke && (out.textStroke = txCfg.outsideStroke);
  59774. }
  59775. out.text = txStl.text;
  59776. out.rich = txStl.rich;
  59777. each(txStl.rich, function (richItem) {
  59778. convertToEC4RichItem(richItem, richItem);
  59779. });
  59780. return out;
  59781. }
  59782. function convertToEC4RichItem(out, richItem) {
  59783. if (!richItem) {
  59784. return;
  59785. }
  59786. hasOwn(richItem, 'fill') && (out.textFill = richItem.fill);
  59787. hasOwn(richItem, 'stroke') && (out.textStroke = richItem.fill);
  59788. hasOwn(richItem, 'lineWidth') && (out.textStrokeWidth = richItem.lineWidth);
  59789. hasOwn(richItem, 'font') && (out.font = richItem.font);
  59790. hasOwn(richItem, 'fontStyle') && (out.fontStyle = richItem.fontStyle);
  59791. hasOwn(richItem, 'fontWeight') && (out.fontWeight = richItem.fontWeight);
  59792. hasOwn(richItem, 'fontSize') && (out.fontSize = richItem.fontSize);
  59793. hasOwn(richItem, 'fontFamily') && (out.fontFamily = richItem.fontFamily);
  59794. hasOwn(richItem, 'align') && (out.textAlign = richItem.align);
  59795. hasOwn(richItem, 'verticalAlign') && (out.textVerticalAlign = richItem.verticalAlign);
  59796. hasOwn(richItem, 'lineHeight') && (out.textLineHeight = richItem.lineHeight);
  59797. hasOwn(richItem, 'width') && (out.textWidth = richItem.width);
  59798. hasOwn(richItem, 'height') && (out.textHeight = richItem.height);
  59799. hasOwn(richItem, 'backgroundColor') && (out.textBackgroundColor = richItem.backgroundColor);
  59800. hasOwn(richItem, 'padding') && (out.textPadding = richItem.padding);
  59801. hasOwn(richItem, 'borderColor') && (out.textBorderColor = richItem.borderColor);
  59802. hasOwn(richItem, 'borderWidth') && (out.textBorderWidth = richItem.borderWidth);
  59803. hasOwn(richItem, 'borderRadius') && (out.textBorderRadius = richItem.borderRadius);
  59804. hasOwn(richItem, 'shadowColor') && (out.textBoxShadowColor = richItem.shadowColor);
  59805. hasOwn(richItem, 'shadowBlur') && (out.textBoxShadowBlur = richItem.shadowBlur);
  59806. hasOwn(richItem, 'shadowOffsetX') && (out.textBoxShadowOffsetX = richItem.shadowOffsetX);
  59807. hasOwn(richItem, 'shadowOffsetY') && (out.textBoxShadowOffsetY = richItem.shadowOffsetY);
  59808. hasOwn(richItem, 'textShadowColor') && (out.textShadowColor = richItem.textShadowColor);
  59809. hasOwn(richItem, 'textShadowBlur') && (out.textShadowBlur = richItem.textShadowBlur);
  59810. hasOwn(richItem, 'textShadowOffsetX') && (out.textShadowOffsetX = richItem.textShadowOffsetX);
  59811. hasOwn(richItem, 'textShadowOffsetY') && (out.textShadowOffsetY = richItem.textShadowOffsetY);
  59812. }
  59813. function warnDeprecated(deprecated, insteadApproach) {
  59814. if ("development" !== 'production') {
  59815. var key = deprecated + '^_^' + insteadApproach;
  59816. if (!deprecatedLogs[key]) {
  59817. console.warn("[ECharts] DEPRECATED: \"" + deprecated + "\" has been deprecated. " + insteadApproach);
  59818. deprecatedLogs[key] = true;
  59819. }
  59820. }
  59821. }
  59822. var CMD$4 = PathProxy.CMD;
  59823. var PI2$a = Math.PI * 2;
  59824. var PROP_XY = ['x', 'y'];
  59825. var PROP_WH = ['width', 'height'];
  59826. var tmpArr$1 = [];
  59827. function aroundEqual(a, b) {
  59828. return Math.abs(a - b) < 1e-5;
  59829. }
  59830. function pathToBezierCurves(path) {
  59831. var data = path.data;
  59832. var len = path.len();
  59833. var bezierArray = [];
  59834. var currentSubpath;
  59835. var xi = 0;
  59836. var yi = 0;
  59837. var x0 = 0;
  59838. var y0 = 0;
  59839. function createNewSubpath(x, y) {
  59840. if (currentSubpath && currentSubpath.length > 2) {
  59841. bezierArray.push(currentSubpath);
  59842. }
  59843. currentSubpath = [x, y];
  59844. }
  59845. function addLine(x0, y0, x1, y1) {
  59846. if (!(aroundEqual(x0, x1) && aroundEqual(y0, y1))) {
  59847. currentSubpath.push(x0, y0, x1, y1, x1, y1);
  59848. }
  59849. }
  59850. function addArc(startAngle, endAngle, cx, cy, rx, ry) {
  59851. var delta = Math.abs(endAngle - startAngle);
  59852. var len = Math.tan(delta / 4) * 4 / 3;
  59853. var dir = endAngle < startAngle ? -1 : 1;
  59854. var c1 = Math.cos(startAngle);
  59855. var s1 = Math.sin(startAngle);
  59856. var c2 = Math.cos(endAngle);
  59857. var s2 = Math.sin(endAngle);
  59858. var x1 = c1 * rx + cx;
  59859. var y1 = s1 * ry + cy;
  59860. var x4 = c2 * rx + cx;
  59861. var y4 = s2 * ry + cy;
  59862. var hx = rx * len * dir;
  59863. var hy = ry * len * dir;
  59864. currentSubpath.push(x1 - hx * s1, y1 + hy * c1, x4 + hx * s2, y4 - hy * c2, x4, y4);
  59865. }
  59866. var x1;
  59867. var y1;
  59868. var x2;
  59869. var y2;
  59870. for (var i = 0; i < len;) {
  59871. var cmd = data[i++];
  59872. var isFirst = i === 1;
  59873. if (isFirst) {
  59874. xi = data[i];
  59875. yi = data[i + 1];
  59876. x0 = xi;
  59877. y0 = yi;
  59878. if (cmd === CMD$4.L || cmd === CMD$4.C || cmd === CMD$4.Q) {
  59879. currentSubpath = [x0, y0];
  59880. }
  59881. }
  59882. switch (cmd) {
  59883. case CMD$4.M:
  59884. xi = x0 = data[i++];
  59885. yi = y0 = data[i++];
  59886. createNewSubpath(x0, y0);
  59887. break;
  59888. case CMD$4.L:
  59889. x1 = data[i++];
  59890. y1 = data[i++];
  59891. addLine(xi, yi, x1, y1);
  59892. xi = x1;
  59893. yi = y1;
  59894. break;
  59895. case CMD$4.C:
  59896. currentSubpath.push(data[i++], data[i++], data[i++], data[i++], xi = data[i++], yi = data[i++]);
  59897. break;
  59898. case CMD$4.Q:
  59899. x1 = data[i++];
  59900. y1 = data[i++];
  59901. x2 = data[i++];
  59902. y2 = data[i++];
  59903. currentSubpath.push(xi + 2 / 3 * (x1 - xi), yi + 2 / 3 * (y1 - yi), x2 + 2 / 3 * (x1 - x2), y2 + 2 / 3 * (y1 - y2), x2, y2);
  59904. xi = x2;
  59905. yi = y2;
  59906. break;
  59907. case CMD$4.A:
  59908. var cx = data[i++];
  59909. var cy = data[i++];
  59910. var rx = data[i++];
  59911. var ry = data[i++];
  59912. var startAngle = data[i++];
  59913. var endAngle = data[i++] + startAngle;
  59914. i += 1;
  59915. var anticlockwise = !data[i++];
  59916. x1 = Math.cos(startAngle) * rx + cx;
  59917. y1 = Math.sin(startAngle) * ry + cy;
  59918. if (isFirst) {
  59919. x0 = x1;
  59920. y0 = y1;
  59921. createNewSubpath(x0, y0);
  59922. }
  59923. else {
  59924. addLine(xi, yi, x1, y1);
  59925. }
  59926. xi = Math.cos(endAngle) * rx + cx;
  59927. yi = Math.sin(endAngle) * ry + cy;
  59928. var step = (anticlockwise ? -1 : 1) * Math.PI / 2;
  59929. for (var angle = startAngle; anticlockwise ? angle > endAngle : angle < endAngle; angle += step) {
  59930. var nextAngle = anticlockwise ? Math.max(angle + step, endAngle)
  59931. : Math.min(angle + step, endAngle);
  59932. addArc(angle, nextAngle, cx, cy, rx, ry);
  59933. }
  59934. break;
  59935. case CMD$4.R:
  59936. x0 = xi = data[i++];
  59937. y0 = yi = data[i++];
  59938. x1 = x0 + data[i++];
  59939. y1 = y0 + data[i++];
  59940. createNewSubpath(x1, y0);
  59941. addLine(x1, y0, x1, y1);
  59942. addLine(x1, y1, x0, y1);
  59943. addLine(x0, y1, x0, y0);
  59944. addLine(x0, y0, x1, y0);
  59945. break;
  59946. case CMD$4.Z:
  59947. currentSubpath && addLine(xi, yi, x0, y0);
  59948. xi = x0;
  59949. yi = y0;
  59950. break;
  59951. }
  59952. }
  59953. if (currentSubpath && currentSubpath.length > 2) {
  59954. bezierArray.push(currentSubpath);
  59955. }
  59956. return bezierArray;
  59957. }
  59958. function alignSubpath(subpath1, subpath2) {
  59959. var len1 = subpath1.length;
  59960. var len2 = subpath2.length;
  59961. if (len1 === len2) {
  59962. return [subpath1, subpath2];
  59963. }
  59964. var shorterPath = len1 < len2 ? subpath1 : subpath2;
  59965. var shorterLen = Math.min(len1, len2);
  59966. var diff = Math.abs(len2 - len1) / 6;
  59967. var shorterBezierCount = (shorterLen - 2) / 6;
  59968. var eachCurveSubDivCount = Math.ceil(diff / shorterBezierCount) + 1;
  59969. var newSubpath = [shorterPath[0], shorterPath[1]];
  59970. var remained = diff;
  59971. var tmpSegX = [];
  59972. var tmpSegY = [];
  59973. for (var i = 2; i < shorterLen;) {
  59974. var x0 = shorterPath[i - 2];
  59975. var y0 = shorterPath[i - 1];
  59976. var x1 = shorterPath[i++];
  59977. var y1 = shorterPath[i++];
  59978. var x2 = shorterPath[i++];
  59979. var y2 = shorterPath[i++];
  59980. var x3 = shorterPath[i++];
  59981. var y3 = shorterPath[i++];
  59982. if (remained <= 0) {
  59983. newSubpath.push(x1, y1, x2, y2, x3, y3);
  59984. continue;
  59985. }
  59986. var actualSubDivCount = Math.min(remained, eachCurveSubDivCount - 1) + 1;
  59987. for (var k = 1; k <= actualSubDivCount; k++) {
  59988. var p = k / actualSubDivCount;
  59989. cubicSubdivide(x0, x1, x2, x3, p, tmpSegX);
  59990. cubicSubdivide(y0, y1, y2, y3, p, tmpSegY);
  59991. x0 = tmpSegX[3];
  59992. y0 = tmpSegY[3];
  59993. newSubpath.push(tmpSegX[1], tmpSegY[1], tmpSegX[2], tmpSegY[2], x0, y0);
  59994. x1 = tmpSegX[5];
  59995. y1 = tmpSegY[5];
  59996. x2 = tmpSegX[6];
  59997. y2 = tmpSegY[6];
  59998. }
  59999. remained -= actualSubDivCount - 1;
  60000. }
  60001. return shorterPath === subpath1 ? [newSubpath, subpath2] : [subpath1, newSubpath];
  60002. }
  60003. function createSubpath(lastSubpathSubpath, otherSubpath) {
  60004. var len = lastSubpathSubpath.length;
  60005. var lastX = lastSubpathSubpath[len - 2];
  60006. var lastY = lastSubpathSubpath[len - 1];
  60007. var newSubpath = [];
  60008. for (var i = 0; i < otherSubpath.length;) {
  60009. newSubpath[i++] = lastX;
  60010. newSubpath[i++] = lastY;
  60011. }
  60012. return newSubpath;
  60013. }
  60014. function alignBezierCurves(array1, array2) {
  60015. var _a;
  60016. var lastSubpath1;
  60017. var lastSubpath2;
  60018. var newArray1 = [];
  60019. var newArray2 = [];
  60020. for (var i = 0; i < Math.max(array1.length, array2.length); i++) {
  60021. var subpath1 = array1[i];
  60022. var subpath2 = array2[i];
  60023. var newSubpath1 = void 0;
  60024. var newSubpath2 = void 0;
  60025. if (!subpath1) {
  60026. newSubpath1 = createSubpath(lastSubpath1 || subpath2, subpath2);
  60027. newSubpath2 = subpath2;
  60028. }
  60029. else if (!subpath2) {
  60030. newSubpath2 = createSubpath(lastSubpath2 || subpath1, subpath1);
  60031. newSubpath1 = subpath1;
  60032. }
  60033. else {
  60034. _a = alignSubpath(subpath1, subpath2), newSubpath1 = _a[0], newSubpath2 = _a[1];
  60035. lastSubpath1 = newSubpath1;
  60036. lastSubpath2 = newSubpath2;
  60037. }
  60038. newArray1.push(newSubpath1);
  60039. newArray2.push(newSubpath2);
  60040. }
  60041. return [newArray1, newArray2];
  60042. }
  60043. function centroid(array) {
  60044. var signedArea = 0;
  60045. var cx = 0;
  60046. var cy = 0;
  60047. var len = array.length;
  60048. for (var i = 0, j = len - 2; i < len; j = i, i += 2) {
  60049. var x0 = array[j];
  60050. var y0 = array[j + 1];
  60051. var x1 = array[i];
  60052. var y1 = array[i + 1];
  60053. var a = x0 * y1 - x1 * y0;
  60054. signedArea += a;
  60055. cx += (x0 + x1) * a;
  60056. cy += (y0 + y1) * a;
  60057. }
  60058. if (signedArea === 0) {
  60059. return [array[0] || 0, array[1] || 0];
  60060. }
  60061. return [cx / signedArea / 3, cy / signedArea / 3, signedArea];
  60062. }
  60063. function findBestRingOffset(fromSubBeziers, toSubBeziers, fromCp, toCp) {
  60064. var bezierCount = (fromSubBeziers.length - 2) / 6;
  60065. var bestScore = Infinity;
  60066. var bestOffset = 0;
  60067. var len = fromSubBeziers.length;
  60068. var len2 = len - 2;
  60069. for (var offset = 0; offset < bezierCount; offset++) {
  60070. var cursorOffset = offset * 6;
  60071. var score = 0;
  60072. for (var k = 0; k < len; k += 2) {
  60073. var idx = k === 0 ? cursorOffset : ((cursorOffset + k - 2) % len2 + 2);
  60074. var x0 = fromSubBeziers[idx] - fromCp[0];
  60075. var y0 = fromSubBeziers[idx + 1] - fromCp[1];
  60076. var x1 = toSubBeziers[k] - toCp[0];
  60077. var y1 = toSubBeziers[k + 1] - toCp[1];
  60078. var dx = x1 - x0;
  60079. var dy = y1 - y0;
  60080. score += dx * dx + dy * dy;
  60081. }
  60082. if (score < bestScore) {
  60083. bestScore = score;
  60084. bestOffset = offset;
  60085. }
  60086. }
  60087. return bestOffset;
  60088. }
  60089. function reverse(array) {
  60090. var newArr = [];
  60091. var len = array.length;
  60092. for (var i = 0; i < len; i += 2) {
  60093. newArr[i] = array[len - i - 2];
  60094. newArr[i + 1] = array[len - i - 1];
  60095. }
  60096. return newArr;
  60097. }
  60098. function findBestMorphingRotation(fromArr, toArr, searchAngleIteration, searchAngleRange) {
  60099. var result = [];
  60100. var fromNeedsReverse;
  60101. for (var i = 0; i < fromArr.length; i++) {
  60102. var fromSubpathBezier = fromArr[i];
  60103. var toSubpathBezier = toArr[i];
  60104. var fromCp = centroid(fromSubpathBezier);
  60105. var toCp = centroid(toSubpathBezier);
  60106. if (fromNeedsReverse == null) {
  60107. fromNeedsReverse = fromCp[2] < 0 !== toCp[2] < 0;
  60108. }
  60109. var newFromSubpathBezier = [];
  60110. var newToSubpathBezier = [];
  60111. var bestAngle = 0;
  60112. var bestScore = Infinity;
  60113. var tmpArr_1 = [];
  60114. var len = fromSubpathBezier.length;
  60115. if (fromNeedsReverse) {
  60116. fromSubpathBezier = reverse(fromSubpathBezier);
  60117. }
  60118. var offset = findBestRingOffset(fromSubpathBezier, toSubpathBezier, fromCp, toCp) * 6;
  60119. var len2 = len - 2;
  60120. for (var k = 0; k < len2; k += 2) {
  60121. var idx = (offset + k) % len2 + 2;
  60122. newFromSubpathBezier[k + 2] = fromSubpathBezier[idx] - fromCp[0];
  60123. newFromSubpathBezier[k + 3] = fromSubpathBezier[idx + 1] - fromCp[1];
  60124. }
  60125. newFromSubpathBezier[0] = fromSubpathBezier[offset] - fromCp[0];
  60126. newFromSubpathBezier[1] = fromSubpathBezier[offset + 1] - fromCp[1];
  60127. if (searchAngleIteration > 0) {
  60128. var step = searchAngleRange / searchAngleIteration;
  60129. for (var angle = -searchAngleRange / 2; angle <= searchAngleRange / 2; angle += step) {
  60130. var sa = Math.sin(angle);
  60131. var ca = Math.cos(angle);
  60132. var score = 0;
  60133. for (var k = 0; k < fromSubpathBezier.length; k += 2) {
  60134. var x0 = newFromSubpathBezier[k];
  60135. var y0 = newFromSubpathBezier[k + 1];
  60136. var x1 = toSubpathBezier[k] - toCp[0];
  60137. var y1 = toSubpathBezier[k + 1] - toCp[1];
  60138. var newX1 = x1 * ca - y1 * sa;
  60139. var newY1 = x1 * sa + y1 * ca;
  60140. tmpArr_1[k] = newX1;
  60141. tmpArr_1[k + 1] = newY1;
  60142. var dx = newX1 - x0;
  60143. var dy = newY1 - y0;
  60144. score += dx * dx + dy * dy;
  60145. }
  60146. if (score < bestScore) {
  60147. bestScore = score;
  60148. bestAngle = angle;
  60149. for (var m = 0; m < tmpArr_1.length; m++) {
  60150. newToSubpathBezier[m] = tmpArr_1[m];
  60151. }
  60152. }
  60153. }
  60154. }
  60155. else {
  60156. for (var i_1 = 0; i_1 < len; i_1 += 2) {
  60157. newToSubpathBezier[i_1] = toSubpathBezier[i_1] - toCp[0];
  60158. newToSubpathBezier[i_1 + 1] = toSubpathBezier[i_1 + 1] - toCp[1];
  60159. }
  60160. }
  60161. result.push({
  60162. from: newFromSubpathBezier,
  60163. to: newToSubpathBezier,
  60164. fromCp: fromCp,
  60165. toCp: toCp,
  60166. rotation: -bestAngle
  60167. });
  60168. }
  60169. return result;
  60170. }
  60171. function morphPath(fromPath, toPath, animationOpts) {
  60172. var fromPathProxy;
  60173. var toPathProxy;
  60174. if (!fromPath || !toPath) {
  60175. return toPath;
  60176. }
  60177. !fromPath.path && fromPath.createPathProxy();
  60178. fromPathProxy = fromPath.path;
  60179. fromPathProxy.beginPath();
  60180. fromPath.buildPath(fromPathProxy, fromPath.shape);
  60181. !toPath.path && toPath.createPathProxy();
  60182. toPathProxy = toPath.path;
  60183. toPathProxy === fromPathProxy && (toPathProxy = new PathProxy(false));
  60184. toPathProxy.beginPath();
  60185. if (isIndividualMorphingPath(toPath)) {
  60186. toPath.__oldBuildPath(toPathProxy, toPath.shape);
  60187. }
  60188. else {
  60189. toPath.buildPath(toPathProxy, toPath.shape);
  60190. }
  60191. var _a = alignBezierCurves(pathToBezierCurves(fromPathProxy), pathToBezierCurves(toPathProxy)), fromBezierCurves = _a[0], toBezierCurves = _a[1];
  60192. var morphingData = findBestMorphingRotation(fromBezierCurves, toBezierCurves, 10, Math.PI);
  60193. becomeIndividualMorphingPath(toPath, morphingData, 0);
  60194. var oldDone = animationOpts && animationOpts.done;
  60195. var oldAborted = animationOpts && animationOpts.aborted;
  60196. var oldDuring = animationOpts && animationOpts.during;
  60197. toPath.animateTo({
  60198. __morphT: 1
  60199. }, defaults({
  60200. during: function (p) {
  60201. toPath.dirtyShape();
  60202. oldDuring && oldDuring(p);
  60203. },
  60204. done: function () {
  60205. restoreIndividualMorphingPath(toPath);
  60206. toPath.createPathProxy();
  60207. toPath.dirtyShape();
  60208. oldDone && oldDone();
  60209. },
  60210. aborted: function () {
  60211. oldAborted && oldAborted();
  60212. }
  60213. }, animationOpts));
  60214. return toPath;
  60215. }
  60216. function morphingPathBuildPath(path) {
  60217. var morphingData = this.__morphingData;
  60218. var t = this.__morphT;
  60219. var onet = 1 - t;
  60220. var newCp = [];
  60221. for (var i = 0; i < morphingData.length; i++) {
  60222. var item = morphingData[i];
  60223. var from = item.from;
  60224. var to = item.to;
  60225. var angle = item.rotation * t;
  60226. var fromCp = item.fromCp;
  60227. var toCp = item.toCp;
  60228. var sa = Math.sin(angle);
  60229. var ca = Math.cos(angle);
  60230. lerp(newCp, fromCp, toCp, t);
  60231. for (var m = 0; m < from.length; m += 2) {
  60232. var x0 = from[m];
  60233. var y0 = from[m + 1];
  60234. var x1 = to[m];
  60235. var y1 = to[m + 1];
  60236. var x = x0 * onet + x1 * t;
  60237. var y = y0 * onet + y1 * t;
  60238. tmpArr$1[m] = (x * ca - y * sa) + newCp[0];
  60239. tmpArr$1[m + 1] = (x * sa + y * ca) + newCp[1];
  60240. }
  60241. for (var m = 0; m < from.length;) {
  60242. if (m === 0) {
  60243. path.moveTo(tmpArr$1[m++], tmpArr$1[m++]);
  60244. }
  60245. path.bezierCurveTo(tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++], tmpArr$1[m++]);
  60246. }
  60247. }
  60248. }
  60249. function becomeIndividualMorphingPath(path, morphingData, morphT) {
  60250. if (isIndividualMorphingPath(path)) {
  60251. updateIndividualMorphingPath(path, morphingData, morphT);
  60252. return;
  60253. }
  60254. var morphingPath = path;
  60255. morphingPath.__oldBuildPath = morphingPath.buildPath;
  60256. morphingPath.buildPath = morphingPathBuildPath;
  60257. updateIndividualMorphingPath(morphingPath, morphingData, morphT);
  60258. }
  60259. function updateIndividualMorphingPath(morphingPath, morphingData, morphT) {
  60260. morphingPath.__morphingData = morphingData;
  60261. morphingPath.__morphT = morphT;
  60262. }
  60263. function restoreIndividualMorphingPath(path) {
  60264. if (isIndividualMorphingPath(path)) {
  60265. path.buildPath = path.__oldBuildPath;
  60266. path.__oldBuildPath = path.__morphingData = null;
  60267. }
  60268. }
  60269. function isIndividualMorphingPath(path) {
  60270. return path.__oldBuildPath != null;
  60271. }
  60272. function isCombiningPath(path) {
  60273. return !!path.__combiningSubList;
  60274. }
  60275. function isInAnyMorphing(path) {
  60276. return isIndividualMorphingPath(path) || isCombiningPath(path);
  60277. }
  60278. function combine(fromPathList, toPath, animationOpts, copyPropsIfDivided) {
  60279. var fromIndividuals = [];
  60280. var separateCount = 0;
  60281. for (var i = 0; i < fromPathList.length; i++) {
  60282. var fromPath = fromPathList[i];
  60283. if (isCombiningPath(fromPath)) {
  60284. var fromCombiningSubList = fromPath.__combiningSubList;
  60285. for (var j = 0; j < fromCombiningSubList.length; j++) {
  60286. fromIndividuals.push(fromCombiningSubList[j]);
  60287. }
  60288. separateCount += fromCombiningSubList.length;
  60289. }
  60290. else {
  60291. fromIndividuals.push(fromPath);
  60292. separateCount++;
  60293. }
  60294. }
  60295. if (!separateCount) {
  60296. return;
  60297. }
  60298. var dividingMethod = animationOpts ? animationOpts.dividingMethod : null;
  60299. var toPathSplittedList = divideShape(toPath, separateCount, dividingMethod);
  60300. assert(toPathSplittedList.length === separateCount);
  60301. var oldDone = animationOpts && animationOpts.done;
  60302. var oldAborted = animationOpts && animationOpts.aborted;
  60303. var oldDuring = animationOpts && animationOpts.during;
  60304. var doneCount = 0;
  60305. var abortedCalled = false;
  60306. var morphAnimationOpts = defaults({
  60307. during: function (p) {
  60308. oldDuring && oldDuring(p);
  60309. },
  60310. done: function () {
  60311. doneCount++;
  60312. if (doneCount === toPathSplittedList.length) {
  60313. restoreCombiningPath(toPath);
  60314. oldDone && oldDone();
  60315. }
  60316. },
  60317. aborted: function () {
  60318. if (!abortedCalled) {
  60319. abortedCalled = true;
  60320. oldAborted && oldAborted();
  60321. }
  60322. }
  60323. }, animationOpts);
  60324. for (var i = 0; i < separateCount; i++) {
  60325. var from = fromIndividuals[i];
  60326. var to = toPathSplittedList[i];
  60327. copyPropsIfDivided && copyPropsIfDivided(toPath, to, true);
  60328. morphPath(from, to, morphAnimationOpts);
  60329. }
  60330. becomeCombiningPath(toPath, toPathSplittedList);
  60331. return {
  60332. fromIndividuals: fromIndividuals,
  60333. toIndividuals: toPathSplittedList,
  60334. count: separateCount
  60335. };
  60336. }
  60337. function becomeCombiningPath(path, combiningSubList) {
  60338. if (isCombiningPath(path)) {
  60339. updateCombiningPathSubList(path, combiningSubList);
  60340. return;
  60341. }
  60342. var combiningPath = path;
  60343. updateCombiningPathSubList(combiningPath, combiningSubList);
  60344. combiningPath.__oldAddSelfToZr = path.addSelfToZr;
  60345. combiningPath.__oldRemoveSelfFromZr = path.removeSelfFromZr;
  60346. combiningPath.addSelfToZr = combiningAddSelfToZr;
  60347. combiningPath.removeSelfFromZr = combiningRemoveSelfFromZr;
  60348. combiningPath.__oldBuildPath = combiningPath.buildPath;
  60349. combiningPath.buildPath = noop;
  60350. combiningPath.childrenRef = combiningChildrenRef;
  60351. }
  60352. function restoreCombiningPath(path) {
  60353. if (!isCombiningPath(path)) {
  60354. return;
  60355. }
  60356. var combiningPath = path;
  60357. updateCombiningPathSubList(combiningPath, null);
  60358. combiningPath.addSelfToZr = combiningPath.__oldAddSelfToZr;
  60359. combiningPath.removeSelfFromZr = combiningPath.__oldRemoveSelfFromZr;
  60360. combiningPath.buildPath = combiningPath.__oldBuildPath;
  60361. combiningPath.childrenRef =
  60362. combiningPath.__combiningSubList =
  60363. combiningPath.__oldAddSelfToZr =
  60364. combiningPath.__oldRemoveSelfFromZr =
  60365. combiningPath.__oldBuildPath = null;
  60366. }
  60367. function updateCombiningPathSubList(combiningPath, combiningSubList) {
  60368. if (combiningPath.__combiningSubList !== combiningSubList) {
  60369. combiningPathSubListAddRemoveWithZr(combiningPath, 'removeSelfFromZr');
  60370. combiningPath.__combiningSubList = combiningSubList;
  60371. if (combiningSubList) {
  60372. for (var i = 0; i < combiningSubList.length; i++) {
  60373. combiningSubList[i].parent = combiningPath;
  60374. }
  60375. }
  60376. combiningPathSubListAddRemoveWithZr(combiningPath, 'addSelfToZr');
  60377. }
  60378. }
  60379. function combiningAddSelfToZr(zr) {
  60380. this.__oldAddSelfToZr(zr);
  60381. combiningPathSubListAddRemoveWithZr(this, 'addSelfToZr');
  60382. }
  60383. function combiningPathSubListAddRemoveWithZr(path, method) {
  60384. var combiningSubList = path.__combiningSubList;
  60385. var zr = path.__zr;
  60386. if (combiningSubList && zr) {
  60387. for (var i = 0; i < combiningSubList.length; i++) {
  60388. var child = combiningSubList[i];
  60389. child[method](zr);
  60390. }
  60391. }
  60392. }
  60393. function combiningRemoveSelfFromZr(zr) {
  60394. this.__oldRemoveSelfFromZr(zr);
  60395. var combiningSubList = this.__combiningSubList;
  60396. for (var i = 0; i < combiningSubList.length; i++) {
  60397. var child = combiningSubList[i];
  60398. child.removeSelfFromZr(zr);
  60399. }
  60400. }
  60401. function combiningChildrenRef() {
  60402. return this.__combiningSubList;
  60403. }
  60404. function separate(fromPath, toPathList, animationOpts, copyPropsIfDivided) {
  60405. var toPathListLen = toPathList.length;
  60406. var fromPathList;
  60407. var dividingMethod = animationOpts ? animationOpts.dividingMethod : null;
  60408. var copyProps = false;
  60409. if (isCombiningPath(fromPath)) {
  60410. var fromCombiningSubList = fromPath.__combiningSubList;
  60411. if (fromCombiningSubList.length === toPathListLen) {
  60412. fromPathList = fromCombiningSubList;
  60413. }
  60414. else {
  60415. fromPathList = divideShape(fromPath, toPathListLen, dividingMethod);
  60416. copyProps = true;
  60417. }
  60418. }
  60419. else {
  60420. fromPathList = divideShape(fromPath, toPathListLen, dividingMethod);
  60421. copyProps = true;
  60422. }
  60423. assert(fromPathList.length === toPathListLen);
  60424. for (var i = 0; i < toPathListLen; i++) {
  60425. if (copyProps && copyPropsIfDivided) {
  60426. copyPropsIfDivided(fromPath, fromPathList[i], false);
  60427. }
  60428. morphPath(fromPathList[i], toPathList[i], animationOpts);
  60429. }
  60430. return {
  60431. fromIndividuals: fromPathList,
  60432. toIndividuals: toPathList,
  60433. count: toPathListLen
  60434. };
  60435. }
  60436. function divideShape(path, separateCount, dividingMethod) {
  60437. return dividingMethod === 'duplicate'
  60438. ? duplicateShape(path, separateCount)
  60439. : splitShape(path, separateCount);
  60440. }
  60441. function splitShape(path, separateCount) {
  60442. var resultPaths = [];
  60443. if (separateCount <= 0) {
  60444. return resultPaths;
  60445. }
  60446. if (separateCount === 1) {
  60447. return duplicateShape(path, separateCount);
  60448. }
  60449. if (path instanceof Rect) {
  60450. var toPathShape = path.shape;
  60451. var splitPropIdx = toPathShape.height > toPathShape.width ? 1 : 0;
  60452. var propWH = PROP_WH[splitPropIdx];
  60453. var propXY = PROP_XY[splitPropIdx];
  60454. var subWH = toPathShape[propWH] / separateCount;
  60455. var xyCurr = toPathShape[propXY];
  60456. for (var i = 0; i < separateCount; i++, xyCurr += subWH) {
  60457. var subShape = {
  60458. x: toPathShape.x,
  60459. y: toPathShape.y,
  60460. width: toPathShape.width,
  60461. height: toPathShape.height
  60462. };
  60463. subShape[propXY] = xyCurr;
  60464. subShape[propWH] = i < separateCount - 1
  60465. ? subWH
  60466. : toPathShape[propXY] + toPathShape[propWH] - xyCurr;
  60467. var splitted = new Rect({ shape: subShape });
  60468. resultPaths.push(splitted);
  60469. }
  60470. }
  60471. else if (path instanceof Sector) {
  60472. var toPathShape = path.shape;
  60473. var clockwise = toPathShape.clockwise;
  60474. var startAngle = toPathShape.startAngle;
  60475. var endAngle = toPathShape.endAngle;
  60476. var endAngleNormalized = normalizeRadian$1(startAngle, toPathShape.endAngle, clockwise);
  60477. var step = (endAngleNormalized - startAngle) / separateCount;
  60478. var angleCurr = startAngle;
  60479. for (var i = 0; i < separateCount; i++, angleCurr += step) {
  60480. var splitted = new Sector({
  60481. shape: {
  60482. cx: toPathShape.cx,
  60483. cy: toPathShape.cy,
  60484. r: toPathShape.r,
  60485. r0: toPathShape.r0,
  60486. clockwise: clockwise,
  60487. startAngle: angleCurr,
  60488. endAngle: i === separateCount - 1 ? endAngle : angleCurr + step
  60489. }
  60490. });
  60491. resultPaths.push(splitted);
  60492. }
  60493. }
  60494. else {
  60495. return duplicateShape(path, separateCount);
  60496. }
  60497. return resultPaths;
  60498. }
  60499. function duplicateShape(path, separateCount) {
  60500. var resultPaths = [];
  60501. if (separateCount <= 0) {
  60502. return resultPaths;
  60503. }
  60504. var ctor = path.constructor;
  60505. for (var i = 0; i < separateCount; i++) {
  60506. var sub = new ctor({
  60507. shape: clone(path.shape)
  60508. });
  60509. resultPaths.push(sub);
  60510. }
  60511. return resultPaths;
  60512. }
  60513. function normalizeRadian$1(start, end, clockwise) {
  60514. return end + PI2$a * (Math[clockwise ? 'ceil' : 'floor']((start - end) / PI2$a));
  60515. }
  60516. var inner$b = makeInner();
  60517. var TRANSFORM_PROPS = {
  60518. x: 1,
  60519. y: 1,
  60520. scaleX: 1,
  60521. scaleY: 1,
  60522. originX: 1,
  60523. originY: 1,
  60524. rotation: 1
  60525. };
  60526. var transformPropNamesStr = keys(TRANSFORM_PROPS).join(', ');
  60527. // `visual('color') visual('borderColor')` is supported.
  60528. var STYLE_VISUAL_TYPE = {
  60529. color: 'fill',
  60530. borderColor: 'stroke'
  60531. };
  60532. var NON_STYLE_VISUAL_PROPS = {
  60533. symbol: 1,
  60534. symbolSize: 1,
  60535. symbolKeepAspect: 1,
  60536. legendSymbol: 1,
  60537. visualMeta: 1,
  60538. liftZ: 1,
  60539. decal: 1
  60540. };
  60541. var EMPHASIS = 'emphasis';
  60542. var NORMAL = 'normal';
  60543. var BLUR = 'blur';
  60544. var SELECT = 'select';
  60545. var STATES = [NORMAL, EMPHASIS, BLUR, SELECT];
  60546. var PATH_ITEM_STYLE = {
  60547. normal: ['itemStyle'],
  60548. emphasis: [EMPHASIS, 'itemStyle'],
  60549. blur: [BLUR, 'itemStyle'],
  60550. select: [SELECT, 'itemStyle']
  60551. };
  60552. var PATH_LABEL = {
  60553. normal: ['label'],
  60554. emphasis: [EMPHASIS, 'label'],
  60555. blur: [BLUR, 'label'],
  60556. select: [SELECT, 'label']
  60557. }; // Use prefix to avoid index to be the same as el.name,
  60558. // which will cause weird update animation.
  60559. var GROUP_DIFF_PREFIX = 'e\0\0';
  60560. var attachedTxInfoTmp = {
  60561. normal: {},
  60562. emphasis: {},
  60563. blur: {},
  60564. select: {}
  60565. };
  60566. var LEGACY_TRANSFORM_PROPS = {
  60567. position: ['x', 'y'],
  60568. scale: ['scaleX', 'scaleY'],
  60569. origin: ['originX', 'originY']
  60570. };
  60571. var tmpTransformable = new Transformable();
  60572. /**
  60573. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  60574. * of each coordinate systems are not required by each coordinate systems directly, but
  60575. * required by the module `custom`.
  60576. *
  60577. * prepareInfoForCustomSeries {Function}: optional
  60578. * @return {Object} {coordSys: {...}, api: {
  60579. * coord: function (data, clamp) {}, // return point in global.
  60580. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  60581. * }}
  60582. */
  60583. var prepareCustoms = {
  60584. cartesian2d: cartesianPrepareCustom,
  60585. geo: geoPrepareCustom,
  60586. singleAxis: singlePrepareCustom,
  60587. polar: polarPrepareCustom,
  60588. calendar: calendarPrepareCustom
  60589. };
  60590. var CustomSeriesModel =
  60591. /** @class */
  60592. function (_super) {
  60593. __extends(CustomSeriesModel, _super);
  60594. function CustomSeriesModel() {
  60595. var _this = _super !== null && _super.apply(this, arguments) || this;
  60596. _this.type = CustomSeriesModel.type;
  60597. return _this;
  60598. }
  60599. CustomSeriesModel.prototype.optionUpdated = function () {
  60600. this.currentZLevel = this.get('zlevel', true);
  60601. this.currentZ = this.get('z', true);
  60602. };
  60603. CustomSeriesModel.prototype.getInitialData = function (option, ecModel) {
  60604. return createListFromArray(this.getSource(), this);
  60605. };
  60606. CustomSeriesModel.prototype.getDataParams = function (dataIndex, dataType, el) {
  60607. var params = _super.prototype.getDataParams.call(this, dataIndex, dataType);
  60608. el && (params.info = inner$b(el).info);
  60609. return params;
  60610. };
  60611. CustomSeriesModel.type = 'series.custom';
  60612. CustomSeriesModel.dependencies = ['grid', 'polar', 'geo', 'singleAxis', 'calendar'];
  60613. CustomSeriesModel.defaultOption = {
  60614. coordinateSystem: 'cartesian2d',
  60615. zlevel: 0,
  60616. z: 2,
  60617. legendHoverLink: true,
  60618. // Custom series will not clip by default.
  60619. // Some case will use custom series to draw label
  60620. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  60621. clip: false // Cartesian coordinate system
  60622. // xAxisIndex: 0,
  60623. // yAxisIndex: 0,
  60624. // Polar coordinate system
  60625. // polarIndex: 0,
  60626. // Geo coordinate system
  60627. // geoIndex: 0,
  60628. };
  60629. return CustomSeriesModel;
  60630. }(SeriesModel);
  60631. var CustomSeriesView =
  60632. /** @class */
  60633. function (_super) {
  60634. __extends(CustomSeriesView, _super);
  60635. function CustomSeriesView() {
  60636. var _this = _super !== null && _super.apply(this, arguments) || this;
  60637. _this.type = CustomSeriesView.type;
  60638. return _this;
  60639. }
  60640. CustomSeriesView.prototype.render = function (customSeries, ecModel, api, payload) {
  60641. var oldData = this._data;
  60642. var data = customSeries.getData();
  60643. var group = this.group;
  60644. var renderItem = makeRenderItem(customSeries, data, ecModel, api); // By default, merge mode is applied. In most cases, custom series is
  60645. // used in the scenario that data amount is not large but graphic elements
  60646. // is complicated, where merge mode is probably necessary for optimization.
  60647. // For example, reuse graphic elements and only update the transform when
  60648. // roam or data zoom according to `actionType`.
  60649. var transOpt = customSeries.__transientTransitionOpt; // Enable user to disable transition animation by both set
  60650. // `from` and `to` dimension as `null`/`undefined`.
  60651. if (transOpt && (transOpt.from == null || transOpt.to == null)) {
  60652. oldData && oldData.each(function (oldIdx) {
  60653. doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
  60654. });
  60655. data.each(function (newIdx) {
  60656. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, null);
  60657. });
  60658. } else {
  60659. var morphPreparation_1 = new MorphPreparation(customSeries, transOpt);
  60660. var diffMode = transOpt ? 'multiple' : 'oneToOne';
  60661. new DataDiffer(oldData ? oldData.getIndices() : [], data.getIndices(), createGetKey(oldData, diffMode, transOpt && transOpt.from), createGetKey(data, diffMode, transOpt && transOpt.to), null, diffMode).add(function (newIdx) {
  60662. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, null);
  60663. }).remove(function (oldIdx) {
  60664. doRemoveEl(oldData.getItemGraphicEl(oldIdx), customSeries, group);
  60665. }).update(function (newIdx, oldIdx) {
  60666. morphPreparation_1.reset('oneToOne');
  60667. var oldEl = oldData.getItemGraphicEl(oldIdx);
  60668. morphPreparation_1.findAndAddFrom(oldEl); // PENDING:
  60669. // if may morph, currently we alway recreate the whole el.
  60670. // because if reuse some of the el in the group tree, the old el has to
  60671. // be removed from the group, and consequently we can not calculate
  60672. // the "global transition" of the old element.
  60673. // But is there performance issue?
  60674. if (morphPreparation_1.hasFrom()) {
  60675. removeElementDirectly(oldEl, group);
  60676. oldEl = null;
  60677. }
  60678. createOrUpdateItem(api, oldEl, newIdx, renderItem(newIdx, payload), customSeries, group, data, morphPreparation_1);
  60679. morphPreparation_1.applyMorphing();
  60680. }).updateManyToOne(function (newIdx, oldIndices) {
  60681. morphPreparation_1.reset('manyToOne');
  60682. for (var i = 0; i < oldIndices.length; i++) {
  60683. var oldEl = oldData.getItemGraphicEl(oldIndices[i]);
  60684. morphPreparation_1.findAndAddFrom(oldEl);
  60685. removeElementDirectly(oldEl, group);
  60686. }
  60687. createOrUpdateItem(api, null, newIdx, renderItem(newIdx, payload), customSeries, group, data, morphPreparation_1);
  60688. morphPreparation_1.applyMorphing();
  60689. }).updateOneToMany(function (newIndices, oldIdx) {
  60690. morphPreparation_1.reset('oneToMany');
  60691. var newLen = newIndices.length;
  60692. var oldEl = oldData.getItemGraphicEl(oldIdx);
  60693. morphPreparation_1.findAndAddFrom(oldEl);
  60694. removeElementDirectly(oldEl, group);
  60695. for (var i = 0; i < newLen; i++) {
  60696. createOrUpdateItem(api, null, newIndices[i], renderItem(newIndices[i], payload), customSeries, group, data, morphPreparation_1);
  60697. }
  60698. morphPreparation_1.applyMorphing();
  60699. }).execute();
  60700. } // Do clipping
  60701. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  60702. if (clipPath) {
  60703. group.setClipPath(clipPath);
  60704. } else {
  60705. group.removeClipPath();
  60706. }
  60707. this._data = data;
  60708. };
  60709. CustomSeriesView.prototype.incrementalPrepareRender = function (customSeries, ecModel, api) {
  60710. this.group.removeAll();
  60711. this._data = null;
  60712. };
  60713. CustomSeriesView.prototype.incrementalRender = function (params, customSeries, ecModel, api, payload) {
  60714. var data = customSeries.getData();
  60715. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  60716. function setIncrementalAndHoverLayer(el) {
  60717. if (!el.isGroup) {
  60718. el.incremental = true;
  60719. el.ensureState('emphasis').hoverLayer = true;
  60720. }
  60721. }
  60722. for (var idx = params.start; idx < params.end; idx++) {
  60723. var el = createOrUpdateItem(null, null, idx, renderItem(idx, payload), customSeries, this.group, data, null);
  60724. el.traverse(setIncrementalAndHoverLayer);
  60725. }
  60726. };
  60727. CustomSeriesView.prototype.filterForExposedEvent = function (eventType, query, targetEl, packedEvent) {
  60728. var elementName = query.element;
  60729. if (elementName == null || targetEl.name === elementName) {
  60730. return true;
  60731. } // Enable to give a name on a group made by `renderItem`, and listen
  60732. // events that triggerd by its descendents.
  60733. while ((targetEl = targetEl.__hostTarget || targetEl.parent) && targetEl !== this.group) {
  60734. if (targetEl.name === elementName) {
  60735. return true;
  60736. }
  60737. }
  60738. return false;
  60739. };
  60740. CustomSeriesView.type = 'custom';
  60741. return CustomSeriesView;
  60742. }(ChartView);
  60743. function createGetKey(data, diffMode, dimension) {
  60744. if (!data) {
  60745. return;
  60746. }
  60747. if (diffMode === 'oneToOne') {
  60748. return function (rawIdx, dataIndex) {
  60749. return data.getId(dataIndex);
  60750. };
  60751. }
  60752. var diffByDimName = data.getDimension(dimension);
  60753. var dimInfo = data.getDimensionInfo(diffByDimName);
  60754. if (!dimInfo) {
  60755. var errMsg = '';
  60756. if ("development" !== 'production') {
  60757. errMsg = dimension + " is not a valid dimension.";
  60758. }
  60759. throwError(errMsg);
  60760. }
  60761. var ordinalMeta = dimInfo.ordinalMeta;
  60762. return function (rawIdx, dataIndex) {
  60763. var key = data.get(diffByDimName, dataIndex);
  60764. if (ordinalMeta) {
  60765. key = ordinalMeta.categories[key];
  60766. }
  60767. return key == null || eqNaN(key) ? rawIdx + '' : '_ec_' + key;
  60768. };
  60769. }
  60770. function createEl(elOption) {
  60771. var graphicType = elOption.type;
  60772. var el; // Those graphic elements are not shapes. They should not be
  60773. // overwritten by users, so do them first.
  60774. if (graphicType === 'path') {
  60775. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  60776. var pathRect = shape.width != null && shape.height != null ? {
  60777. x: shape.x || 0,
  60778. y: shape.y || 0,
  60779. width: shape.width,
  60780. height: shape.height
  60781. } : null;
  60782. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  60783. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  60784. inner$b(el).customPathData = pathData;
  60785. } else if (graphicType === 'image') {
  60786. el = new ZRImage({});
  60787. inner$b(el).customImagePath = elOption.style.image;
  60788. } else if (graphicType === 'text') {
  60789. el = new ZRText({}); // inner(el).customText = (elOption.style as TextStyleProps).text;
  60790. } else if (graphicType === 'group') {
  60791. el = new Group();
  60792. } else if (graphicType === 'compoundPath') {
  60793. throw new Error('"compoundPath" is not supported yet.');
  60794. } else {
  60795. var Clz = getShapeClass(graphicType);
  60796. if (!Clz) {
  60797. var errMsg = '';
  60798. if ("development" !== 'production') {
  60799. errMsg = 'graphic type "' + graphicType + '" can not be found.';
  60800. }
  60801. throwError(errMsg);
  60802. }
  60803. el = new Clz();
  60804. }
  60805. inner$b(el).customGraphicType = graphicType;
  60806. el.name = elOption.name; // Compat ec4: the default z2 lift is 1. If changing the number,
  60807. // some cases probably be broken: hierarchy layout along z, like circle packing,
  60808. // where emphasis only intending to modify color/border rather than lift z2.
  60809. el.z2EmphasisLift = 1;
  60810. el.z2SelectLift = 1;
  60811. return el;
  60812. }
  60813. /**
  60814. * ----------------------------------------------------------
  60815. * [STRATEGY_MERGE] Merge properties or erase all properties:
  60816. *
  60817. * Based on the fact that the existing zr element probably be reused, we now consider whether
  60818. * merge or erase all properties to the exsiting elements.
  60819. * That is, if a certain props is not specified in the lastest return of `renderItem`:
  60820. * + "Merge" means that do not modify the value on the existing element.
  60821. * + "Erase all" means that use a default value to the existing element.
  60822. *
  60823. * "Merge" might bring some unexpected state retaining for users and "erase all" seams to be
  60824. * more safe. "erase all" force users to specify all of the props each time, which is recommanded
  60825. * in most cases.
  60826. * But "erase all" theoretically disables the chance of performance optimization (e.g., just
  60827. * generete shape and style at the first time rather than always do that).
  60828. * So we still use "merge" rather than "erase all". If users need "erase all", they can
  60829. * simple always set all of the props each time.
  60830. * Some "object-like" config like `textConfig`, `textContent`, `style` which are not needed for
  60831. * every elment, so we replace them only when user specify them. And the that is a total replace.
  60832. *
  60833. * TODO: there is no hint of 'isFirst' to users. So the performance enhancement can not be
  60834. * performed yet. Consider the case:
  60835. * (1) setOption to "mergeChildren" with a smaller children count
  60836. * (2) Use dataZoom to make an item disappear.
  60837. * (3) User dataZoom to make the item display again. At that time, renderItem need to return the
  60838. * full option rather than partial option to recreate the element.
  60839. *
  60840. * ----------------------------------------------
  60841. * [STRATEGY_NULL] `hasOwnProperty` or `== null`:
  60842. *
  60843. * Ditinguishing "own property" probably bring little trouble to user when make el options.
  60844. * So we trade a {xx: null} or {xx: undefined} as "not specified" if possible rather than
  60845. * "set them to null/undefined". In most cases, props can not be cleared. Some typicall
  60846. * clearable props like `style`/`textConfig`/`textContent` we enable `false` to means
  60847. * "clear". In some othere special cases that the prop is able to set as null/undefined,
  60848. * but not suitable to use `false`, `hasOwnProperty` is checked.
  60849. *
  60850. * ---------------------------------------------
  60851. * [STRATEGY_TRANSITION] The rule of transition:
  60852. * + For props on the root level of a element:
  60853. * If there is no `transition` specified, tansform props will be transitioned by default,
  60854. * which is the same as the previous setting in echarts4 and suitable for the scenario
  60855. * of dataZoom change.
  60856. * If `transition` specified, only the specified props will be transitioned.
  60857. * + For props in `shape` and `style`:
  60858. * Only props specified in `transition` will be transitioned.
  60859. * + Break:
  60860. * Since ec5, do not make transition to shape by default, because it might result in
  60861. * performance issue (especially `points` of polygon) and do not necessary in most cases.
  60862. *
  60863. * @return if `isMorphTo`, return `allPropsFinal`.
  60864. */
  60865. function updateElNormal( // Can be null/undefined
  60866. api, el, // Whether be a morph target.
  60867. isMorphTo, dataIndex, elOption, styleOpt, attachedTxInfo, seriesModel, isInit, isTextContent) {
  60868. var transFromProps = {};
  60869. var allPropsFinal = {};
  60870. var elDisplayable = el.isGroup ? null : el; // If be "morph to", delay the `updateElNormal` when all of the els in
  60871. // this data item processed. Because at that time we can get all of the
  60872. // "morph from" and make correct separate/combine.
  60873. !isMorphTo && prepareShapeOrExtraTransitionFrom('shape', el, null, elOption, transFromProps, isInit);
  60874. prepareShapeOrExtraAllPropsFinal('shape', elOption, allPropsFinal);
  60875. !isMorphTo && prepareShapeOrExtraTransitionFrom('extra', el, null, elOption, transFromProps, isInit);
  60876. prepareShapeOrExtraAllPropsFinal('extra', elOption, allPropsFinal);
  60877. !isMorphTo && prepareTransformTransitionFrom(el, null, elOption, transFromProps, isInit);
  60878. prepareTransformAllPropsFinal(elOption, allPropsFinal);
  60879. var txCfgOpt = attachedTxInfo && attachedTxInfo.normal.cfg;
  60880. if (txCfgOpt) {
  60881. // PENDING: whether use user object directly rather than clone?
  60882. // TODO:5.0 textConfig transition animation?
  60883. el.setTextConfig(txCfgOpt);
  60884. }
  60885. if (el.type === 'text' && styleOpt) {
  60886. var textOptionStyle = styleOpt; // Compatible with ec4: if `textFill` or `textStroke` exists use them.
  60887. hasOwn(textOptionStyle, 'textFill') && (textOptionStyle.fill = textOptionStyle.textFill);
  60888. hasOwn(textOptionStyle, 'textStroke') && (textOptionStyle.stroke = textOptionStyle.textStroke);
  60889. }
  60890. if (styleOpt) {
  60891. var decalPattern = void 0;
  60892. var decalObj = isPath$1(el) ? styleOpt.decal : null;
  60893. if (api && decalObj) {
  60894. decalObj.dirty = true;
  60895. decalPattern = createOrUpdatePatternFromDecal(decalObj, api);
  60896. } // Always overwrite in case user specify this prop.
  60897. styleOpt.__decalPattern = decalPattern;
  60898. }
  60899. !isMorphTo && prepareStyleTransitionFrom(el, null, elOption, styleOpt, transFromProps, isInit);
  60900. if (elDisplayable) {
  60901. hasOwn(elOption, 'invisible') && (elDisplayable.invisible = elOption.invisible);
  60902. } // If `isMorphTo`, we should not update these props to el directly, otherwise,
  60903. // when applying morph finally, the original prop are missing for making "animation from".
  60904. if (!isMorphTo) {
  60905. applyPropsFinal(el, allPropsFinal, styleOpt);
  60906. applyTransitionFrom(el, dataIndex, elOption, seriesModel, transFromProps, isInit);
  60907. } // Merge by default.
  60908. hasOwn(elOption, 'silent') && (el.silent = elOption.silent);
  60909. hasOwn(elOption, 'ignore') && (el.ignore = elOption.ignore);
  60910. if (!isTextContent) {
  60911. // `elOption.info` enables user to mount some info on
  60912. // elements and use them in event handlers.
  60913. // Update them only when user specified, otherwise, remain.
  60914. hasOwn(elOption, 'info') && (inner$b(el).info = elOption.info);
  60915. }
  60916. styleOpt ? el.dirty() : el.markRedraw();
  60917. return isMorphTo ? allPropsFinal : null;
  60918. }
  60919. function applyPropsFinal(el, // Can be null/undefined
  60920. allPropsFinal, styleOpt) {
  60921. var elDisplayable = el.isGroup ? null : el;
  60922. if (elDisplayable && styleOpt) {
  60923. var decalPattern = styleOpt.__decalPattern;
  60924. var originalDecalObj = void 0;
  60925. if (decalPattern) {
  60926. originalDecalObj = styleOpt.decal;
  60927. styleOpt.decal = decalPattern;
  60928. } // PENDING: here the input style object is used directly.
  60929. // Good for performance but bad for compatibility control.
  60930. elDisplayable.useStyle(styleOpt);
  60931. if (decalPattern) {
  60932. styleOpt.decal = originalDecalObj;
  60933. } // When style object changed, how to trade the existing animation?
  60934. // It is probably conplicated and not needed to cover all the cases.
  60935. // But still need consider the case:
  60936. // (1) When using init animation on `style.opacity`, and before the animation
  60937. // ended users triggers an update by mousewhell. At that time the init
  60938. // animation should better be continued rather than terminated.
  60939. // So after `useStyle` called, we should change the animation target manually
  60940. // to continue the effect of the init animation.
  60941. // (2) PENDING: If the previous animation targeted at a `val1`, and currently we need
  60942. // to update the value to `val2` and no animation declared, should be terminate
  60943. // the previous animation or just modify the target of the animation?
  60944. // Therotically That will happen not only on `style` but also on `shape` and
  60945. // `transfrom` props. But we haven't handle this case at present yet.
  60946. // (3) PENDING: Is it proper to visit `animators` and `targetName`?
  60947. var animators = elDisplayable.animators;
  60948. for (var i = 0; i < animators.length; i++) {
  60949. var animator = animators[i]; // targetName is the "topKey".
  60950. if (animator.targetName === 'style') {
  60951. animator.changeTarget(elDisplayable.style);
  60952. }
  60953. }
  60954. } // Set el to the final state firstly.
  60955. allPropsFinal && el.attr(allPropsFinal);
  60956. }
  60957. function applyTransitionFrom(el, dataIndex, elOption, seriesModel, // Can be null/undefined
  60958. transFromProps, isInit) {
  60959. if (transFromProps) {
  60960. // Do not use `el.updateDuringAnimation` here becuase `el.updateDuringAnimation` will
  60961. // be called mutiple time in each animation frame. For example, if both "transform" props
  60962. // and shape props and style props changed, it will generate three animator and called
  60963. // one-by-one in each animation frame.
  60964. // We use the during in `animateTo/From` params.
  60965. var userDuring = elOption.during; // For simplicity, if during not specified, the previous during will not work any more.
  60966. inner$b(el).userDuring = userDuring;
  60967. var cfgDuringCall = userDuring ? bind(duringCall, {
  60968. el: el,
  60969. userDuring: userDuring
  60970. }) : null;
  60971. var cfg = {
  60972. dataIndex: dataIndex,
  60973. isFrom: true,
  60974. during: cfgDuringCall
  60975. };
  60976. isInit ? initProps(el, transFromProps, seriesModel, cfg) : updateProps(el, transFromProps, seriesModel, cfg);
  60977. }
  60978. } // See [STRATEGY_TRANSITION]
  60979. function prepareShapeOrExtraTransitionFrom(mainAttr, el, morphFromEl, elOption, transFromProps, isInit) {
  60980. var attrOpt = elOption[mainAttr];
  60981. if (!attrOpt) {
  60982. return;
  60983. }
  60984. var elPropsInAttr = el[mainAttr];
  60985. var transFromPropsInAttr;
  60986. var enterFrom = attrOpt.enterFrom;
  60987. if (isInit && enterFrom) {
  60988. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  60989. var enterFromKeys = keys(enterFrom);
  60990. for (var i = 0; i < enterFromKeys.length; i++) {
  60991. // `enterFrom` props are not necessarily also declared in `shape`/`style`/...,
  60992. // for example, `opacity` can only declared in `enterFrom` but not in `style`.
  60993. var key = enterFromKeys[i]; // Do not clone, animator will perform that clone.
  60994. transFromPropsInAttr[key] = enterFrom[key];
  60995. }
  60996. }
  60997. if (!isInit && elPropsInAttr // Just ignore shape animation in morphing.
  60998. && !(morphFromEl != null && mainAttr === 'shape')) {
  60999. if (attrOpt.transition) {
  61000. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  61001. var transitionKeys = normalizeToArray(attrOpt.transition);
  61002. for (var i = 0; i < transitionKeys.length; i++) {
  61003. var key = transitionKeys[i];
  61004. var elVal = elPropsInAttr[key];
  61005. if ("development" !== 'production') {
  61006. checkNonStyleTansitionRefer(key, attrOpt[key], elVal);
  61007. } // Do not clone, see `checkNonStyleTansitionRefer`.
  61008. transFromPropsInAttr[key] = elVal;
  61009. }
  61010. } else if (indexOf(elOption.transition, mainAttr) >= 0) {
  61011. !transFromPropsInAttr && (transFromPropsInAttr = transFromProps[mainAttr] = {});
  61012. var elPropsInAttrKeys = keys(elPropsInAttr);
  61013. for (var i = 0; i < elPropsInAttrKeys.length; i++) {
  61014. var key = elPropsInAttrKeys[i];
  61015. var elVal = elPropsInAttr[key];
  61016. if (isNonStyleTransitionEnabled(attrOpt[key], elVal)) {
  61017. transFromPropsInAttr[key] = elVal;
  61018. }
  61019. }
  61020. }
  61021. }
  61022. var leaveTo = attrOpt.leaveTo;
  61023. if (leaveTo) {
  61024. var leaveToProps = getOrCreateLeaveToPropsFromEl(el);
  61025. var leaveToPropsInAttr = leaveToProps[mainAttr] || (leaveToProps[mainAttr] = {});
  61026. var leaveToKeys = keys(leaveTo);
  61027. for (var i = 0; i < leaveToKeys.length; i++) {
  61028. var key = leaveToKeys[i];
  61029. leaveToPropsInAttr[key] = leaveTo[key];
  61030. }
  61031. }
  61032. }
  61033. function prepareShapeOrExtraAllPropsFinal(mainAttr, elOption, allProps) {
  61034. var attrOpt = elOption[mainAttr];
  61035. if (!attrOpt) {
  61036. return;
  61037. }
  61038. var allPropsInAttr = allProps[mainAttr] = {};
  61039. var keysInAttr = keys(attrOpt);
  61040. for (var i = 0; i < keysInAttr.length; i++) {
  61041. var key = keysInAttr[i]; // To avoid share one object with different element, and
  61042. // to avoid user modify the object inexpectedly, have to clone.
  61043. allPropsInAttr[key] = cloneValue(attrOpt[key]);
  61044. }
  61045. } // See [STRATEGY_TRANSITION].
  61046. function prepareTransformTransitionFrom(el, morphFromEl, elOption, transFromProps, isInit) {
  61047. var enterFrom = elOption.enterFrom;
  61048. if (isInit && enterFrom) {
  61049. var enterFromKeys = keys(enterFrom);
  61050. for (var i = 0; i < enterFromKeys.length; i++) {
  61051. var key = enterFromKeys[i];
  61052. if ("development" !== 'production') {
  61053. checkTransformPropRefer(key, 'el.enterFrom');
  61054. } // Do not clone, animator will perform that clone.
  61055. transFromProps[key] = enterFrom[key];
  61056. }
  61057. }
  61058. if (!isInit) {
  61059. // If morphing, force transition all transform props.
  61060. // otherwise might have incorrect morphing animation.
  61061. if (morphFromEl) {
  61062. var fromTransformable = calcOldElLocalTransformBasedOnNewElParent(morphFromEl, el);
  61063. setTransformPropToTransitionFrom(transFromProps, 'x', fromTransformable);
  61064. setTransformPropToTransitionFrom(transFromProps, 'y', fromTransformable);
  61065. setTransformPropToTransitionFrom(transFromProps, 'scaleX', fromTransformable);
  61066. setTransformPropToTransitionFrom(transFromProps, 'scaleY', fromTransformable);
  61067. setTransformPropToTransitionFrom(transFromProps, 'originX', fromTransformable);
  61068. setTransformPropToTransitionFrom(transFromProps, 'originY', fromTransformable);
  61069. setTransformPropToTransitionFrom(transFromProps, 'rotation', fromTransformable);
  61070. } else if (elOption.transition) {
  61071. var transitionKeys = normalizeToArray(elOption.transition);
  61072. for (var i = 0; i < transitionKeys.length; i++) {
  61073. var key = transitionKeys[i];
  61074. if (key === 'style' || key === 'shape' || key === 'extra') {
  61075. continue;
  61076. }
  61077. var elVal = el[key];
  61078. if ("development" !== 'production') {
  61079. checkTransformPropRefer(key, 'el.transition');
  61080. checkNonStyleTansitionRefer(key, elOption[key], elVal);
  61081. } // Do not clone, see `checkNonStyleTansitionRefer`.
  61082. transFromProps[key] = elVal;
  61083. }
  61084. } // This default transition see [STRATEGY_TRANSITION]
  61085. else {
  61086. setTransformPropToTransitionFrom(transFromProps, 'x', el);
  61087. setTransformPropToTransitionFrom(transFromProps, 'y', el);
  61088. }
  61089. }
  61090. var leaveTo = elOption.leaveTo;
  61091. if (leaveTo) {
  61092. var leaveToProps = getOrCreateLeaveToPropsFromEl(el);
  61093. var leaveToKeys = keys(leaveTo);
  61094. for (var i = 0; i < leaveToKeys.length; i++) {
  61095. var key = leaveToKeys[i];
  61096. if ("development" !== 'production') {
  61097. checkTransformPropRefer(key, 'el.leaveTo');
  61098. }
  61099. leaveToProps[key] = leaveTo[key];
  61100. }
  61101. }
  61102. }
  61103. function prepareTransformAllPropsFinal(elOption, allProps) {
  61104. setLagecyTransformProp(elOption, allProps, 'position');
  61105. setLagecyTransformProp(elOption, allProps, 'scale');
  61106. setLagecyTransformProp(elOption, allProps, 'origin');
  61107. setTransformProp(elOption, allProps, 'x');
  61108. setTransformProp(elOption, allProps, 'y');
  61109. setTransformProp(elOption, allProps, 'scaleX');
  61110. setTransformProp(elOption, allProps, 'scaleY');
  61111. setTransformProp(elOption, allProps, 'originX');
  61112. setTransformProp(elOption, allProps, 'originY');
  61113. setTransformProp(elOption, allProps, 'rotation');
  61114. } // See [STRATEGY_TRANSITION].
  61115. function prepareStyleTransitionFrom(el, morphFromEl, elOption, styleOpt, transFromProps, isInit) {
  61116. if (!styleOpt) {
  61117. return;
  61118. } // At present in "many-to-one"/"one-to-many" case, to not support "many" have
  61119. // different styles and make style transitions. That might be a rare case.
  61120. var fromEl = morphFromEl || el;
  61121. var fromElStyle = fromEl.style;
  61122. var transFromStyleProps;
  61123. var enterFrom = styleOpt.enterFrom;
  61124. if (isInit && enterFrom) {
  61125. var enterFromKeys = keys(enterFrom);
  61126. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  61127. for (var i = 0; i < enterFromKeys.length; i++) {
  61128. var key = enterFromKeys[i]; // Do not clone, animator will perform that clone.
  61129. transFromStyleProps[key] = enterFrom[key];
  61130. }
  61131. }
  61132. if (!isInit && fromElStyle) {
  61133. if (styleOpt.transition) {
  61134. var transitionKeys = normalizeToArray(styleOpt.transition);
  61135. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  61136. for (var i = 0; i < transitionKeys.length; i++) {
  61137. var key = transitionKeys[i];
  61138. var elVal = fromElStyle[key]; // Do not clone, see `checkNonStyleTansitionRefer`.
  61139. transFromStyleProps[key] = elVal;
  61140. }
  61141. } else if (el.getAnimationStyleProps && indexOf(elOption.transition, 'style') >= 0) {
  61142. var animationProps = el.getAnimationStyleProps();
  61143. var animationStyleProps = animationProps ? animationProps.style : null;
  61144. if (animationStyleProps) {
  61145. !transFromStyleProps && (transFromStyleProps = transFromProps.style = {});
  61146. var styleKeys = keys(styleOpt);
  61147. for (var i = 0; i < styleKeys.length; i++) {
  61148. var key = styleKeys[i];
  61149. if (animationStyleProps[key]) {
  61150. var elVal = fromElStyle[key];
  61151. transFromStyleProps[key] = elVal;
  61152. }
  61153. }
  61154. }
  61155. }
  61156. }
  61157. var leaveTo = styleOpt.leaveTo;
  61158. if (leaveTo) {
  61159. var leaveToKeys = keys(leaveTo);
  61160. var leaveToProps = getOrCreateLeaveToPropsFromEl(el);
  61161. var leaveToStyleProps = leaveToProps.style || (leaveToProps.style = {});
  61162. for (var i = 0; i < leaveToKeys.length; i++) {
  61163. var key = leaveToKeys[i];
  61164. leaveToStyleProps[key] = leaveTo[key];
  61165. }
  61166. }
  61167. }
  61168. /**
  61169. * If make "transform"(x/y/scaleX/scaleY/orient/originX/originY) transition between
  61170. * two path elements that have different hierarchy, before we retrieve the "from" props,
  61171. * we have to calculate the local transition of the "oldPath" based on the parent of
  61172. * the "newPath".
  61173. * At present, the case only happend in "morphing". Without morphing, the transform
  61174. * transition are all between elements in the same hierarchy, where this kind of process
  61175. * is not needed.
  61176. *
  61177. * [CAVEAT]:
  61178. * This method makes sense only if: (very tricky)
  61179. * (1) "newEl" has been added to its final parent.
  61180. * (2) Local transform props of "newPath.parent" are not at their final value but already
  61181. * have been at the "from value".
  61182. * This is currently ensured by:
  61183. * (2.1) "graphicUtil.animationFrom", which will set the element to the "from value"
  61184. * immediately.
  61185. * (2.2) "morph" option is not allowed to be set on Group, so all of the groups have
  61186. * been finished their "updateElNormal" when calling this method in morphing process.
  61187. */
  61188. function calcOldElLocalTransformBasedOnNewElParent(oldEl, newEl) {
  61189. if (!oldEl || oldEl === newEl || oldEl.parent === newEl.parent) {
  61190. return oldEl;
  61191. } // Not sure oldEl is rendered (may have "lazyUpdate"),
  61192. // so always call `getComputedTransform`.
  61193. var tmpM = tmpTransformable.transform || (tmpTransformable.transform = identity([]));
  61194. var oldGlobalTransform = oldEl.getComputedTransform();
  61195. oldGlobalTransform ? copy$1(tmpM, oldGlobalTransform) : identity(tmpM);
  61196. var newParent = newEl.parent;
  61197. if (newParent) {
  61198. newParent.getComputedTransform();
  61199. }
  61200. tmpTransformable.originX = oldEl.originX;
  61201. tmpTransformable.originY = oldEl.originY;
  61202. tmpTransformable.parent = newParent;
  61203. tmpTransformable.decomposeTransform();
  61204. return tmpTransformable;
  61205. }
  61206. var checkNonStyleTansitionRefer;
  61207. if ("development" !== 'production') {
  61208. checkNonStyleTansitionRefer = function (propName, optVal, elVal) {
  61209. if (!isArrayLike(optVal)) {
  61210. assert(optVal != null && isFinite(optVal), 'Prop `' + propName + '` must refer to a finite number or ArrayLike for transition.');
  61211. } else {
  61212. // Try not to copy array for performance, but if user use the same object in different
  61213. // call of `renderItem`, it will casue animation transition fail.
  61214. assert(optVal !== elVal, 'Prop `' + propName + '` must use different Array object each time for transition.');
  61215. }
  61216. };
  61217. }
  61218. function isNonStyleTransitionEnabled(optVal, elVal) {
  61219. // The same as `checkNonStyleTansitionRefer`.
  61220. return !isArrayLike(optVal) ? optVal != null && isFinite(optVal) : optVal !== elVal;
  61221. }
  61222. var checkTransformPropRefer;
  61223. if ("development" !== 'production') {
  61224. checkTransformPropRefer = function (key, usedIn) {
  61225. assert(hasOwn(TRANSFORM_PROPS, key), 'Prop `' + key + '` is not a permitted in `' + usedIn + '`. ' + 'Only `' + keys(TRANSFORM_PROPS).join('`, `') + '` are permitted.');
  61226. };
  61227. }
  61228. function getOrCreateLeaveToPropsFromEl(el) {
  61229. var innerEl = inner$b(el);
  61230. return innerEl.leaveToProps || (innerEl.leaveToProps = {});
  61231. } // Use it to avoid it be exposed to user.
  61232. var tmpDuringScope = {};
  61233. var customDuringAPI = {
  61234. // Usually other props do not need to be changed in animation during.
  61235. setTransform: function (key, val) {
  61236. if ("development" !== 'production') {
  61237. assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `setTransform`.');
  61238. }
  61239. tmpDuringScope.el[key] = val;
  61240. return this;
  61241. },
  61242. getTransform: function (key) {
  61243. if ("development" !== 'production') {
  61244. assert(hasOwn(TRANSFORM_PROPS, key), 'Only ' + transformPropNamesStr + ' available in `getTransform`.');
  61245. }
  61246. return tmpDuringScope.el[key];
  61247. },
  61248. setShape: function (key, val) {
  61249. if ("development" !== 'production') {
  61250. assertNotReserved(key);
  61251. }
  61252. var shape = tmpDuringScope.el.shape || (tmpDuringScope.el.shape = {});
  61253. shape[key] = val;
  61254. tmpDuringScope.isShapeDirty = true;
  61255. return this;
  61256. },
  61257. getShape: function (key) {
  61258. if ("development" !== 'production') {
  61259. assertNotReserved(key);
  61260. }
  61261. var shape = tmpDuringScope.el.shape;
  61262. if (shape) {
  61263. return shape[key];
  61264. }
  61265. },
  61266. setStyle: function (key, val) {
  61267. if ("development" !== 'production') {
  61268. assertNotReserved(key);
  61269. }
  61270. var style = tmpDuringScope.el.style;
  61271. if (style) {
  61272. if ("development" !== 'production') {
  61273. if (eqNaN(val)) {
  61274. warn('style.' + key + ' must not be assigned with NaN.');
  61275. }
  61276. }
  61277. style[key] = val;
  61278. tmpDuringScope.isStyleDirty = true;
  61279. }
  61280. return this;
  61281. },
  61282. getStyle: function (key) {
  61283. if ("development" !== 'production') {
  61284. assertNotReserved(key);
  61285. }
  61286. var style = tmpDuringScope.el.style;
  61287. if (style) {
  61288. return style[key];
  61289. }
  61290. },
  61291. setExtra: function (key, val) {
  61292. if ("development" !== 'production') {
  61293. assertNotReserved(key);
  61294. }
  61295. var extra = tmpDuringScope.el.extra || (tmpDuringScope.el.extra = {});
  61296. extra[key] = val;
  61297. return this;
  61298. },
  61299. getExtra: function (key) {
  61300. if ("development" !== 'production') {
  61301. assertNotReserved(key);
  61302. }
  61303. var extra = tmpDuringScope.el.extra;
  61304. if (extra) {
  61305. return extra[key];
  61306. }
  61307. }
  61308. };
  61309. function assertNotReserved(key) {
  61310. if ("development" !== 'production') {
  61311. if (key === 'transition' || key === 'enterFrom' || key === 'leaveTo') {
  61312. throw new Error('key must not be "' + key + '"');
  61313. }
  61314. }
  61315. }
  61316. function duringCall() {
  61317. // Do not provide "percent" until some requirements come.
  61318. // Because consider thies case:
  61319. // enterFrom: {x: 100, y: 30}, transition: 'x'.
  61320. // And enter duration is different from update duration.
  61321. // Thus it might be confused about the meaning of "percent" in during callback.
  61322. var scope = this;
  61323. var el = scope.el;
  61324. if (!el) {
  61325. return;
  61326. } // If el is remove from zr by reason like legend, during still need to called,
  61327. // becuase el will be added back to zr and the prop value should not be incorrect.
  61328. var newstUserDuring = inner$b(el).userDuring;
  61329. var scopeUserDuring = scope.userDuring; // Ensured a during is only called once in each animation frame.
  61330. // If a during is called multiple times in one frame, maybe some users' calulation logic
  61331. // might be wrong (not sure whether this usage exists).
  61332. // The case of a during might be called twice can be: by default there is a animator for
  61333. // 'x', 'y' when init. Before the init animation finished, call `setOption` to start
  61334. // another animators for 'style'/'shape'/'extra'.
  61335. if (newstUserDuring !== scopeUserDuring) {
  61336. // release
  61337. scope.el = scope.userDuring = null;
  61338. return;
  61339. }
  61340. tmpDuringScope.el = el;
  61341. tmpDuringScope.isShapeDirty = false;
  61342. tmpDuringScope.isStyleDirty = false; // Give no `this` to user in "during" calling.
  61343. scopeUserDuring(customDuringAPI);
  61344. if (tmpDuringScope.isShapeDirty && el.dirtyShape) {
  61345. el.dirtyShape();
  61346. }
  61347. if (tmpDuringScope.isStyleDirty && el.dirtyStyle) {
  61348. el.dirtyStyle();
  61349. } // markRedraw() will be called by default in during.
  61350. // FIXME `this.markRedraw();` directly ?
  61351. // FIXME: if in future meet the case that some prop will be both modified in `during` and `state`,
  61352. // consider the issue that the prop might be incorrect when return to "normal" state.
  61353. }
  61354. function updateElOnState(state, el, elStateOpt, styleOpt, attachedTxInfo, isRoot, isTextContent) {
  61355. var elDisplayable = el.isGroup ? null : el;
  61356. var txCfgOpt = attachedTxInfo && attachedTxInfo[state].cfg; // PENDING:5.0 support customize scale change and transition animation?
  61357. if (elDisplayable) {
  61358. // By default support auto lift color when hover whether `emphasis` specified.
  61359. var stateObj = elDisplayable.ensureState(state);
  61360. if (styleOpt === false) {
  61361. var existingEmphasisState = elDisplayable.getState(state);
  61362. if (existingEmphasisState) {
  61363. existingEmphasisState.style = null;
  61364. }
  61365. } else {
  61366. // style is needed to enable defaut emphasis.
  61367. stateObj.style = styleOpt || null;
  61368. } // If `elOption.styleEmphasis` or `elOption.emphasis.style` is `false`,
  61369. // remove hover style.
  61370. // If `elOption.textConfig` or `elOption.emphasis.textConfig` is null/undefined, it does not
  61371. // make sense. So for simplicity, we do not ditinguish `hasOwnProperty` and null/undefined.
  61372. if (txCfgOpt) {
  61373. stateObj.textConfig = txCfgOpt;
  61374. }
  61375. setDefaultStateProxy(elDisplayable);
  61376. }
  61377. }
  61378. function updateZ$1(el, elOption, seriesModel, attachedTxInfo) {
  61379. // Group not support textContent and not support z yet.
  61380. if (el.isGroup) {
  61381. return;
  61382. }
  61383. var elDisplayable = el;
  61384. var currentZ = seriesModel.currentZ;
  61385. var currentZLevel = seriesModel.currentZLevel; // Always erase.
  61386. elDisplayable.z = currentZ;
  61387. elDisplayable.zlevel = currentZLevel; // z2 must not be null/undefined, otherwise sort error may occur.
  61388. var optZ2 = elOption.z2;
  61389. optZ2 != null && (elDisplayable.z2 = optZ2 || 0);
  61390. for (var i = 0; i < STATES.length; i++) {
  61391. updateZForEachState(elDisplayable, elOption, STATES[i]);
  61392. }
  61393. }
  61394. function updateZForEachState(elDisplayable, elOption, state) {
  61395. var isNormal = state === NORMAL;
  61396. var elStateOpt = isNormal ? elOption : retrieveStateOption(elOption, state);
  61397. var optZ2 = elStateOpt ? elStateOpt.z2 : null;
  61398. var stateObj;
  61399. if (optZ2 != null) {
  61400. // Do not `ensureState` until required.
  61401. stateObj = isNormal ? elDisplayable : elDisplayable.ensureState(state);
  61402. stateObj.z2 = optZ2 || 0;
  61403. }
  61404. }
  61405. function setLagecyTransformProp(elOption, targetProps, legacyName, fromTransformable // If provided, retrieve from the element.
  61406. ) {
  61407. var legacyArr = elOption[legacyName];
  61408. var xyName = LEGACY_TRANSFORM_PROPS[legacyName];
  61409. if (legacyArr) {
  61410. if (fromTransformable) {
  61411. targetProps[xyName[0]] = fromTransformable[xyName[0]];
  61412. targetProps[xyName[1]] = fromTransformable[xyName[1]];
  61413. } else {
  61414. targetProps[xyName[0]] = legacyArr[0];
  61415. targetProps[xyName[1]] = legacyArr[1];
  61416. }
  61417. }
  61418. }
  61419. function setTransformProp(elOption, allProps, name, fromTransformable // If provided, retrieve from the element.
  61420. ) {
  61421. if (elOption[name] != null) {
  61422. allProps[name] = fromTransformable ? fromTransformable[name] : elOption[name];
  61423. }
  61424. }
  61425. function setTransformPropToTransitionFrom(transitionFrom, name, fromTransformable // If provided, retrieve from the element.
  61426. ) {
  61427. if (fromTransformable) {
  61428. transitionFrom[name] = fromTransformable[name];
  61429. }
  61430. }
  61431. function makeRenderItem(customSeries, data, ecModel, api) {
  61432. var renderItem = customSeries.get('renderItem');
  61433. var coordSys = customSeries.coordinateSystem;
  61434. var prepareResult = {};
  61435. if (coordSys) {
  61436. if ("development" !== 'production') {
  61437. assert(renderItem, 'series.render is required.');
  61438. assert(coordSys.prepareCustoms || prepareCustoms[coordSys.type], 'This coordSys does not support custom series.');
  61439. } // `coordSys.prepareCustoms` is used for external coord sys like bmap.
  61440. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms(coordSys) : prepareCustoms[coordSys.type](coordSys);
  61441. }
  61442. var userAPI = defaults({
  61443. getWidth: api.getWidth,
  61444. getHeight: api.getHeight,
  61445. getZr: api.getZr,
  61446. getDevicePixelRatio: api.getDevicePixelRatio,
  61447. value: value,
  61448. style: style,
  61449. ordinalRawValue: ordinalRawValue,
  61450. styleEmphasis: styleEmphasis,
  61451. visual: visual,
  61452. barLayout: barLayout,
  61453. currentSeriesIndices: currentSeriesIndices,
  61454. font: font
  61455. }, prepareResult.api || {});
  61456. var userParams = {
  61457. // The life cycle of context: current round of rendering.
  61458. // The global life cycle is probably not necessary, because
  61459. // user can store global status by themselves.
  61460. context: {},
  61461. seriesId: customSeries.id,
  61462. seriesName: customSeries.name,
  61463. seriesIndex: customSeries.seriesIndex,
  61464. coordSys: prepareResult.coordSys,
  61465. dataInsideLength: data.count(),
  61466. encode: wrapEncodeDef(customSeries.getData())
  61467. }; // If someday intending to refactor them to a class, should consider do not
  61468. // break change: currently these attribute member are encapsulated in a closure
  61469. // so that do not need to force user to call these method with a scope.
  61470. // Do not support call `api` asynchronously without dataIndexInside input.
  61471. var currDataIndexInside;
  61472. var currItemModel;
  61473. var currItemStyleModels = {};
  61474. var currLabelModels = {};
  61475. var seriesItemStyleModels = {};
  61476. var seriesLabelModels = {};
  61477. for (var i = 0; i < STATES.length; i++) {
  61478. var stateName = STATES[i];
  61479. seriesItemStyleModels[stateName] = customSeries.getModel(PATH_ITEM_STYLE[stateName]);
  61480. seriesLabelModels[stateName] = customSeries.getModel(PATH_LABEL[stateName]);
  61481. }
  61482. function getItemModel(dataIndexInside) {
  61483. return dataIndexInside === currDataIndexInside ? currItemModel || (currItemModel = data.getItemModel(dataIndexInside)) : data.getItemModel(dataIndexInside);
  61484. }
  61485. function getItemStyleModel(dataIndexInside, state) {
  61486. 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]);
  61487. }
  61488. function getLabelModel(dataIndexInside, state) {
  61489. return !data.hasItemOption ? seriesLabelModels[state] : dataIndexInside === currDataIndexInside ? currLabelModels[state] || (currLabelModels[state] = getItemModel(dataIndexInside).getModel(PATH_LABEL[state])) : getItemModel(dataIndexInside).getModel(PATH_LABEL[state]);
  61490. }
  61491. return function (dataIndexInside, payload) {
  61492. currDataIndexInside = dataIndexInside;
  61493. currItemModel = null;
  61494. currItemStyleModels = {};
  61495. currLabelModels = {};
  61496. return renderItem && renderItem(defaults({
  61497. dataIndexInside: dataIndexInside,
  61498. dataIndex: data.getRawIndex(dataIndexInside),
  61499. // Can be used for optimization when zoom or roam.
  61500. actionType: payload ? payload.type : null
  61501. }, userParams), userAPI);
  61502. };
  61503. /**
  61504. * @public
  61505. * @param dim by default 0.
  61506. * @param dataIndexInside by default `currDataIndexInside`.
  61507. */
  61508. function value(dim, dataIndexInside) {
  61509. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61510. return data.get(data.getDimension(dim || 0), dataIndexInside);
  61511. }
  61512. /**
  61513. * @public
  61514. * @param dim by default 0.
  61515. * @param dataIndexInside by default `currDataIndexInside`.
  61516. */
  61517. function ordinalRawValue(dim, dataIndexInside) {
  61518. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61519. var dimInfo = data.getDimensionInfo(dim || 0);
  61520. if (!dimInfo) {
  61521. return;
  61522. }
  61523. var val = data.get(dimInfo.name, dataIndexInside);
  61524. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  61525. return ordinalMeta ? ordinalMeta.categories[val] : val;
  61526. }
  61527. /**
  61528. * @deprecated The orgininal intention of `api.style` is enable to set itemStyle
  61529. * like other series. But it not necessary and not easy to give a strict definition
  61530. * of what it return. And since echarts5 it needs to be make compat work. So
  61531. * deprecates it since echarts5.
  61532. *
  61533. * By default, `visual` is applied to style (to support visualMap).
  61534. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  61535. * it can be implemented as:
  61536. * `api.style({stroke: api.visual('color'), fill: null})`;
  61537. *
  61538. * [Compat]: since ec5, RectText has been separated from its hosts el.
  61539. * so `api.style()` will only return the style from `itemStyle` but not handle `label`
  61540. * any more. But `series.label` config is never published in doc.
  61541. * We still compat it in `api.style()`. But not encourage to use it and will still not
  61542. * to pulish it to doc.
  61543. * @public
  61544. * @param dataIndexInside by default `currDataIndexInside`.
  61545. */
  61546. function style(userProps, dataIndexInside) {
  61547. if ("development" !== 'production') {
  61548. warnDeprecated('api.style', 'Please write literal style directly instead.');
  61549. }
  61550. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61551. var style = data.getItemVisual(dataIndexInside, 'style');
  61552. var visualColor = style && style.fill;
  61553. var opacity = style && style.opacity;
  61554. var itemStyle = getItemStyleModel(dataIndexInside, NORMAL).getItemStyle();
  61555. visualColor != null && (itemStyle.fill = visualColor);
  61556. opacity != null && (itemStyle.opacity = opacity);
  61557. var opt = {
  61558. inheritColor: isString(visualColor) ? visualColor : '#000'
  61559. };
  61560. var labelModel = getLabelModel(dataIndexInside, NORMAL); // Now that the feture of "auto adjust text fill/stroke" has been migrated to zrender
  61561. // since ec5, we should set `isAttached` as `false` here and make compat in
  61562. // `convertToEC4StyleForCustomSerise`.
  61563. var textStyle = createTextStyle(labelModel, null, opt, false, true);
  61564. textStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  61565. var textConfig = createTextConfig(labelModel, opt, false);
  61566. preFetchFromExtra(userProps, itemStyle);
  61567. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  61568. userProps && applyUserPropsAfter(itemStyle, userProps);
  61569. itemStyle.legacy = true;
  61570. return itemStyle;
  61571. }
  61572. /**
  61573. * @deprecated The reason see `api.style()`
  61574. * @public
  61575. * @param dataIndexInside by default `currDataIndexInside`.
  61576. */
  61577. function styleEmphasis(userProps, dataIndexInside) {
  61578. if ("development" !== 'production') {
  61579. warnDeprecated('api.styleEmphasis', 'Please write literal style directly instead.');
  61580. }
  61581. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61582. var itemStyle = getItemStyleModel(dataIndexInside, EMPHASIS).getItemStyle();
  61583. var labelModel = getLabelModel(dataIndexInside, EMPHASIS);
  61584. var textStyle = createTextStyle(labelModel, null, null, true, true);
  61585. textStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, EMPHASIS), customSeries.getFormattedLabel(dataIndexInside, NORMAL), getDefaultLabel(data, dataIndexInside)) : null;
  61586. var textConfig = createTextConfig(labelModel, null, true);
  61587. preFetchFromExtra(userProps, itemStyle);
  61588. itemStyle = convertToEC4StyleForCustomSerise(itemStyle, textStyle, textConfig);
  61589. userProps && applyUserPropsAfter(itemStyle, userProps);
  61590. itemStyle.legacy = true;
  61591. return itemStyle;
  61592. }
  61593. function applyUserPropsAfter(itemStyle, extra) {
  61594. for (var key in extra) {
  61595. if (hasOwn(extra, key)) {
  61596. itemStyle[key] = extra[key];
  61597. }
  61598. }
  61599. }
  61600. function preFetchFromExtra(extra, itemStyle) {
  61601. // A trick to retrieve those props firstly, which are used to
  61602. // apply auto inside fill/stroke in `convertToEC4StyleForCustomSerise`.
  61603. // (It's not reasonable but only for a degree of compat)
  61604. if (extra) {
  61605. extra.textFill && (itemStyle.textFill = extra.textFill);
  61606. extra.textPosition && (itemStyle.textPosition = extra.textPosition);
  61607. }
  61608. }
  61609. /**
  61610. * @public
  61611. * @param dataIndexInside by default `currDataIndexInside`.
  61612. */
  61613. function visual(visualType, dataIndexInside) {
  61614. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  61615. if (hasOwn(STYLE_VISUAL_TYPE, visualType)) {
  61616. var style_1 = data.getItemVisual(dataIndexInside, 'style');
  61617. return style_1 ? style_1[STYLE_VISUAL_TYPE[visualType]] : null;
  61618. } // Only support these visuals. Other visual might be inner tricky
  61619. // for performance (like `style`), do not expose to users.
  61620. if (hasOwn(NON_STYLE_VISUAL_PROPS, visualType)) {
  61621. return data.getItemVisual(dataIndexInside, visualType);
  61622. }
  61623. }
  61624. /**
  61625. * @public
  61626. * @return If not support, return undefined.
  61627. */
  61628. function barLayout(opt) {
  61629. if (coordSys.type === 'cartesian2d') {
  61630. var baseAxis = coordSys.getBaseAxis();
  61631. return getLayoutOnAxis(defaults({
  61632. axis: baseAxis
  61633. }, opt));
  61634. }
  61635. }
  61636. /**
  61637. * @public
  61638. */
  61639. function currentSeriesIndices() {
  61640. return ecModel.getCurrentSeriesIndices();
  61641. }
  61642. /**
  61643. * @public
  61644. * @return font string
  61645. */
  61646. function font(opt) {
  61647. return getFont(opt, ecModel);
  61648. }
  61649. }
  61650. function wrapEncodeDef(data) {
  61651. var encodeDef = {};
  61652. each(data.dimensions, function (dimName, dataDimIndex) {
  61653. var dimInfo = data.getDimensionInfo(dimName);
  61654. if (!dimInfo.isExtraCoord) {
  61655. var coordDim = dimInfo.coordDim;
  61656. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  61657. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  61658. }
  61659. });
  61660. return encodeDef;
  61661. }
  61662. function createOrUpdateItem(api, el, dataIndex, elOption, seriesModel, group, data, morphPreparation) {
  61663. // [Rule]
  61664. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  61665. // (It seems that violate the "merge" principle, but most of users probably intuitively
  61666. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  61667. // most cases.)
  61668. // The rule or "merge" see [STRATEGY_MERGE].
  61669. // If `elOption` is `null`/`undefined`/`false` (when `renderItem` returns nothing).
  61670. if (!elOption) {
  61671. removeElementDirectly(el, group);
  61672. return;
  61673. }
  61674. el = doCreateOrUpdateEl(api, el, dataIndex, elOption, seriesModel, group, true, morphPreparation);
  61675. el && data.setItemGraphicEl(dataIndex, el);
  61676. enableHoverEmphasis(el, elOption.focus, elOption.blurScope);
  61677. return el;
  61678. }
  61679. function doCreateOrUpdateEl(api, el, dataIndex, elOption, seriesModel, group, isRoot, morphPreparation) {
  61680. if ("development" !== 'production') {
  61681. assert(elOption, 'should not have an null/undefined element setting');
  61682. }
  61683. var toBeReplacedIdx = -1;
  61684. if (el && doesElNeedRecreate(el, elOption) // || (
  61685. // // PENDING: even in one-to-one mapping case, if el is marked as morph,
  61686. // // do not sure whether the el will be mapped to another el with different
  61687. // // hierarchy in Group tree. So always recreate el rather than reuse the el.
  61688. // morphPreparation && morphPreparation.isOneToOneFrom(el)
  61689. // )
  61690. ) {
  61691. // Should keep at the original index, otherwise "merge by index" will be incorrect.
  61692. toBeReplacedIdx = group.childrenRef().indexOf(el);
  61693. el = null;
  61694. }
  61695. var elIsNewCreated = !el;
  61696. if (!el) {
  61697. el = createEl(elOption);
  61698. } else {
  61699. // FIMXE:NEXT unified clearState?
  61700. // If in some case the performance issue arised, consider
  61701. // do not clearState but update cached normal state directly.
  61702. el.clearStates();
  61703. }
  61704. var canMorph = inner$b(el).canMorph = elOption.morph && isPath$1(el);
  61705. var thisElIsMorphTo = canMorph && morphPreparation && morphPreparation.hasFrom(); // Use update animation when morph is enabled.
  61706. var isInit = elIsNewCreated && !thisElIsMorphTo;
  61707. 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;
  61708. attachedTxInfoTmp.isLegacy = false;
  61709. doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfoTmp);
  61710. doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit);
  61711. var pendingAllPropsFinal = updateElNormal(api, el, thisElIsMorphTo, dataIndex, elOption, elOption.style, attachedTxInfoTmp, seriesModel, isInit, false);
  61712. if (thisElIsMorphTo) {
  61713. morphPreparation.addTo(el, elOption, dataIndex, pendingAllPropsFinal);
  61714. }
  61715. for (var i = 0; i < STATES.length; i++) {
  61716. var stateName = STATES[i];
  61717. if (stateName !== NORMAL) {
  61718. var otherStateOpt = retrieveStateOption(elOption, stateName);
  61719. var otherStyleOpt = retrieveStyleOptionOnState(elOption, otherStateOpt, stateName);
  61720. updateElOnState(stateName, el, otherStateOpt, otherStyleOpt, attachedTxInfoTmp);
  61721. }
  61722. }
  61723. updateZ$1(el, elOption, seriesModel);
  61724. if (elOption.type === 'group') {
  61725. mergeChildren(api, el, dataIndex, elOption, seriesModel, morphPreparation);
  61726. }
  61727. if (toBeReplacedIdx >= 0) {
  61728. group.replaceAt(el, toBeReplacedIdx);
  61729. } else {
  61730. group.add(el);
  61731. }
  61732. return el;
  61733. } // `el` must not be null/undefined.
  61734. function doesElNeedRecreate(el, elOption) {
  61735. var elInner = inner$b(el);
  61736. var elOptionType = elOption.type;
  61737. var elOptionShape = elOption.shape;
  61738. var elOptionStyle = elOption.style;
  61739. return (// If `elOptionType` is `null`, follow the merge principle.
  61740. 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?
  61741. // || (elOptionType === 'text'
  61742. // && hasOwn(elOptionStyle, 'text')
  61743. // && (elOptionStyle as TextStyleProps).text !== elInner.customText
  61744. // )
  61745. );
  61746. }
  61747. function doCreateOrUpdateClipPath(el, dataIndex, elOption, seriesModel, isInit) {
  61748. // Based on the "merge" principle, if no clipPath provided,
  61749. // do nothing. The exists clip will be totally removed only if
  61750. // `el.clipPath` is `false`. Otherwise it will be merged/replaced.
  61751. var clipPathOpt = elOption.clipPath;
  61752. if (clipPathOpt === false) {
  61753. if (el && el.getClipPath()) {
  61754. el.removeClipPath();
  61755. }
  61756. } else if (clipPathOpt) {
  61757. var clipPath = el.getClipPath();
  61758. if (clipPath && doesElNeedRecreate(clipPath, clipPathOpt)) {
  61759. clipPath = null;
  61760. }
  61761. if (!clipPath) {
  61762. clipPath = createEl(clipPathOpt);
  61763. if ("development" !== 'production') {
  61764. assert(clipPath instanceof Path, 'Only any type of `path` can be used in `clipPath`, rather than ' + clipPath.type + '.');
  61765. }
  61766. el.setClipPath(clipPath);
  61767. }
  61768. updateElNormal(null, clipPath, null, dataIndex, clipPathOpt, null, null, seriesModel, isInit, false);
  61769. } // If not define `clipPath` in option, do nothing unnecessary.
  61770. }
  61771. function doCreateOrUpdateAttachedTx(el, dataIndex, elOption, seriesModel, isInit, attachedTxInfo) {
  61772. // group do not support textContent temporarily untill necessary.
  61773. if (el.isGroup) {
  61774. return;
  61775. } // Normal must be called before emphasis, for `isLegacy` detection.
  61776. processTxInfo(elOption, null, attachedTxInfo);
  61777. processTxInfo(elOption, EMPHASIS, attachedTxInfo); // If `elOption.textConfig` or `elOption.textContent` is null/undefined, it does not make sence.
  61778. // So for simplicity, if "elOption hasOwnProperty of them but be null/undefined", we do not
  61779. // trade them as set to null to el.
  61780. // Especially:
  61781. // `elOption.textContent: false` means remove textContent.
  61782. // `elOption.textContent.emphasis.style: false` means remove the style from emphasis state.
  61783. var txConOptNormal = attachedTxInfo.normal.conOpt;
  61784. var txConOptEmphasis = attachedTxInfo.emphasis.conOpt;
  61785. var txConOptBlur = attachedTxInfo.blur.conOpt;
  61786. var txConOptSelect = attachedTxInfo.select.conOpt;
  61787. if (txConOptNormal != null || txConOptEmphasis != null || txConOptSelect != null || txConOptBlur != null) {
  61788. var textContent = el.getTextContent();
  61789. if (txConOptNormal === false) {
  61790. textContent && el.removeTextContent();
  61791. } else {
  61792. txConOptNormal = attachedTxInfo.normal.conOpt = txConOptNormal || {
  61793. type: 'text'
  61794. };
  61795. if (!textContent) {
  61796. textContent = createEl(txConOptNormal);
  61797. el.setTextContent(textContent);
  61798. } else {
  61799. // If in some case the performance issue arised, consider
  61800. // do not clearState but update cached normal state directly.
  61801. textContent.clearStates();
  61802. }
  61803. var txConStlOptNormal = txConOptNormal && txConOptNormal.style;
  61804. updateElNormal(null, textContent, null, dataIndex, txConOptNormal, txConStlOptNormal, null, seriesModel, isInit, true);
  61805. for (var i = 0; i < STATES.length; i++) {
  61806. var stateName = STATES[i];
  61807. if (stateName !== NORMAL) {
  61808. var txConOptOtherState = attachedTxInfo[stateName].conOpt;
  61809. updateElOnState(stateName, textContent, txConOptOtherState, retrieveStyleOptionOnState(txConOptNormal, txConOptOtherState, stateName), null);
  61810. }
  61811. }
  61812. txConStlOptNormal ? textContent.dirty() : textContent.markRedraw();
  61813. }
  61814. }
  61815. }
  61816. function processTxInfo(elOption, state, attachedTxInfo) {
  61817. var stateOpt = !state ? elOption : retrieveStateOption(elOption, state);
  61818. var styleOpt = !state ? elOption.style : retrieveStyleOptionOnState(elOption, stateOpt, EMPHASIS);
  61819. var elType = elOption.type;
  61820. var txCfg = stateOpt ? stateOpt.textConfig : null;
  61821. var txConOptNormal = elOption.textContent;
  61822. var txConOpt = !txConOptNormal ? null : !state ? txConOptNormal : retrieveStateOption(txConOptNormal, state);
  61823. if (styleOpt && ( // Because emphasis style has little info to detect legacy,
  61824. // if normal is legacy, emphasis is trade as legacy.
  61825. attachedTxInfo.isLegacy || isEC4CompatibleStyle(styleOpt, elType, !!txCfg, !!txConOpt))) {
  61826. attachedTxInfo.isLegacy = true;
  61827. var convertResult = convertFromEC4CompatibleStyle(styleOpt, elType, !state); // Explicitly specified `textConfig` and `textContent` has higher priority than
  61828. // the ones generated by legacy style. Otherwise if users use them and `api.style`
  61829. // at the same time, they not both work and hardly to known why.
  61830. if (!txCfg && convertResult.textConfig) {
  61831. txCfg = convertResult.textConfig;
  61832. }
  61833. if (!txConOpt && convertResult.textContent) {
  61834. txConOpt = convertResult.textContent;
  61835. }
  61836. }
  61837. if (!state && txConOpt) {
  61838. var txConOptNormal_1 = txConOpt; // `textContent: {type: 'text'}`, the "type" is easy to be missing. So we tolerate it.
  61839. !txConOptNormal_1.type && (txConOptNormal_1.type = 'text');
  61840. if ("development" !== 'production') {
  61841. // Do not tolerate incorret type for forward compat.
  61842. txConOptNormal_1.type !== 'text' && assert(txConOptNormal_1.type === 'text', 'textContent.type must be "text"');
  61843. }
  61844. }
  61845. var info = !state ? attachedTxInfo.normal : attachedTxInfo[state];
  61846. info.cfg = txCfg;
  61847. info.conOpt = txConOpt;
  61848. }
  61849. function retrieveStateOption(elOption, state) {
  61850. return !state ? elOption : elOption ? elOption[state] : null;
  61851. }
  61852. function retrieveStyleOptionOnState(stateOptionNormal, stateOption, state) {
  61853. var style = stateOption && stateOption.style;
  61854. if (style == null && state === EMPHASIS && stateOptionNormal) {
  61855. style = stateOptionNormal.styleEmphasis;
  61856. }
  61857. return style;
  61858. } // Usage:
  61859. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  61860. // the existing children will not be removed, and enables the feature that
  61861. // update some of the props of some of the children simply by construct
  61862. // the returned children of `renderItem` like:
  61863. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  61864. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  61865. // by child.name. But that might be lower performance.
  61866. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  61867. // replaced totally.
  61868. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  61869. //
  61870. // For implementation simpleness, do not provide a direct way to remove sinlge
  61871. // child (otherwise the total indicies of the children array have to be modified).
  61872. // User can remove a single child by set its `ignore` as `true`.
  61873. function mergeChildren(api, el, dataIndex, elOption, seriesModel, morphPreparation) {
  61874. var newChildren = elOption.children;
  61875. var newLen = newChildren ? newChildren.length : 0;
  61876. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  61877. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  61878. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  61879. if (!newLen && !byName && !notMerge) {
  61880. return;
  61881. }
  61882. if (byName) {
  61883. diffGroupChildren({
  61884. api: api,
  61885. oldChildren: el.children() || [],
  61886. newChildren: newChildren || [],
  61887. dataIndex: dataIndex,
  61888. seriesModel: seriesModel,
  61889. group: el,
  61890. morphPreparation: morphPreparation
  61891. });
  61892. return;
  61893. }
  61894. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  61895. // might be better performance.
  61896. var index = 0;
  61897. for (; index < newLen; index++) {
  61898. newChildren[index] && doCreateOrUpdateEl(api, el.childAt(index), dataIndex, newChildren[index], seriesModel, el, false, morphPreparation);
  61899. }
  61900. for (var i = el.childCount() - 1; i >= index; i--) {
  61901. // Do not supprot leave elements that are not mentioned in the latest
  61902. // `renderItem` return. Otherwise users may not have a clear and simple
  61903. // concept that how to contorl all of the elements.
  61904. doRemoveEl(el.childAt(i), seriesModel, el);
  61905. }
  61906. }
  61907. function diffGroupChildren(context) {
  61908. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  61909. }
  61910. function getKey(item, idx) {
  61911. var name = item && item.name;
  61912. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  61913. }
  61914. function processAddUpdate(newIndex, oldIndex) {
  61915. var context = this.context;
  61916. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  61917. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  61918. doCreateOrUpdateEl(context.api, child, context.dataIndex, childOption, context.seriesModel, context.group, false, context.morphPreparation);
  61919. }
  61920. function processRemove(oldIndex) {
  61921. var context = this.context;
  61922. var child = context.oldChildren[oldIndex];
  61923. doRemoveEl(child, context.seriesModel, context.group);
  61924. }
  61925. function doRemoveEl(el, seriesModel, group) {
  61926. if (el) {
  61927. var leaveToProps = inner$b(el).leaveToProps;
  61928. leaveToProps ? updateProps(el, leaveToProps, seriesModel, {
  61929. cb: function () {
  61930. group.remove(el);
  61931. }
  61932. }) : group.remove(el);
  61933. }
  61934. }
  61935. /**
  61936. * @return SVG Path data.
  61937. */
  61938. function getPathData(shape) {
  61939. // "d" follows the SVG convention.
  61940. return shape && (shape.pathData || shape.d);
  61941. }
  61942. function hasOwnPathData(shape) {
  61943. return shape && (hasOwn(shape, 'pathData') || hasOwn(shape, 'd'));
  61944. }
  61945. function isPath$1(el) {
  61946. return el && el instanceof Path;
  61947. }
  61948. function removeElementDirectly(el, group) {
  61949. el && group.remove(el);
  61950. }
  61951. /**
  61952. * Any morph-potential el should added by `morphPreparation.addTo(el)`.
  61953. * And they may apply morph or not when `morphPreparation.applyMorphing()`.
  61954. * But at least, all of the "to" elements will apply all of the updates
  61955. * as `doCreateOrUpdateItem` did.
  61956. */
  61957. var MorphPreparation =
  61958. /** @class */
  61959. function () {
  61960. function MorphPreparation(seriesModel, transOpt) {
  61961. this._fromList = [];
  61962. this._toList = [];
  61963. this._toElOptionList = [];
  61964. this._allPropsFinalList = [];
  61965. this._toDataIndices = []; // Key: `toDataIndex`, not `toIdx`
  61966. this._morphConfigList = [];
  61967. this._seriesModel = seriesModel;
  61968. this._transOpt = transOpt;
  61969. }
  61970. MorphPreparation.prototype.hasFrom = function () {
  61971. return !!this._fromList.length;
  61972. }; // isOneToOneFrom(el: Element): boolean {
  61973. // if (el && inner(el).canMorph) {
  61974. // const fromList = this._fromList;
  61975. // for (let i = 0; i < fromList.length; i++) {
  61976. // if (fromList[i] === el) {
  61977. // return true;
  61978. // }
  61979. // }
  61980. // }
  61981. // }
  61982. MorphPreparation.prototype.findAndAddFrom = function (el) {
  61983. if (!el) {
  61984. return;
  61985. }
  61986. if (inner$b(el).canMorph) {
  61987. this._fromList.push(el);
  61988. }
  61989. if (el.isGroup) {
  61990. var children = el.childrenRef();
  61991. for (var i = 0; i < children.length; i++) {
  61992. this.findAndAddFrom(children[i]);
  61993. }
  61994. }
  61995. };
  61996. MorphPreparation.prototype.addTo = function (path, elOption, dataIndex, allPropsFinal) {
  61997. if (path) {
  61998. this._toList.push(path);
  61999. this._toElOptionList.push(elOption);
  62000. this._toDataIndices.push(dataIndex);
  62001. this._allPropsFinalList.push(allPropsFinal);
  62002. }
  62003. };
  62004. MorphPreparation.prototype.applyMorphing = function () {
  62005. // [MORPHING_LOGIC_HINT]
  62006. // Pay attention to the order:
  62007. // (A) Apply `allPropsFinal` and `styleOption` to "to".
  62008. // (Then "to" becomes to the final state.)
  62009. // (B) Apply `morphPath`/`combine`/`separate`.
  62010. // (Based on the current state of "from" and the final state of "to".)
  62011. // (Then we may get "from.subList" or "to.subList".)
  62012. // (C) Copy the related props from "from" to "from.subList", from "to" to "to.subList".
  62013. // (D) Collect `transitionFromProps` for "to" and "to.subList"
  62014. // (Based on "from" or "from.subList".)
  62015. // (E) Apply `transitionFromProps` to "to" and "to.subList"
  62016. // (It might change the prop values to the first frame value.)
  62017. // Case_I:
  62018. // If (D) should be after (C), we use sequence: A - B - C - D - E
  62019. // Case_II:
  62020. // If (A) should be after (D), we use sequence: D - A - B - C - E
  62021. // [MORPHING_LOGIC_HINT]
  62022. // zrender `morphPath`/`combine`/`separate` only manages the shape animation.
  62023. // Other props (like transfrom, style transition) will handled in echarts).
  62024. // [MORPHING_LOGIC_HINT]
  62025. // Make sure `applyPropsFinal` always be called for "to".
  62026. var type = this._type;
  62027. var fromList = this._fromList;
  62028. var toList = this._toList;
  62029. var toListLen = toList.length;
  62030. var fromListLen = fromList.length;
  62031. if (!fromListLen || !toListLen) {
  62032. return;
  62033. }
  62034. if (type === 'oneToOne') {
  62035. // In one-to-one case, we by default apply a simple rule:
  62036. // map "from" and "to" one by one.
  62037. // For this case: old_data_item_el and new_data_item_el
  62038. // has the same hierarchy of group tree but only some path type changed.
  62039. for (var toIdx = 0; toIdx < toListLen; toIdx++) {
  62040. this._oneToOneForSingleTo(toIdx, toIdx);
  62041. }
  62042. } else if (type === 'manyToOne') {
  62043. // A rough strategy: if there are more than one "to", we simply divide "fromList" equally.
  62044. var fromSingleSegLen = Math.max(1, Math.floor(fromListLen / toListLen));
  62045. for (var toIdx = 0, fromIdxStart = 0; toIdx < toListLen; toIdx++, fromIdxStart += fromSingleSegLen) {
  62046. var fromCount = toIdx + 1 >= toListLen ? fromListLen - fromIdxStart : fromSingleSegLen;
  62047. this._manyToOneForSingleTo(toIdx, fromIdxStart >= fromListLen ? null : fromIdxStart, fromCount);
  62048. }
  62049. } else if (type === 'oneToMany') {
  62050. // A rough strategy: if there are more than one "from", we simply divide "toList" equally.
  62051. var toSingleSegLen = Math.max(1, Math.floor(toListLen / fromListLen));
  62052. for (var toIdxStart = 0, fromIdx = 0; toIdxStart < toListLen; toIdxStart += toSingleSegLen, fromIdx++) {
  62053. var toCount = toIdxStart + toSingleSegLen >= toListLen ? toListLen - toIdxStart : toSingleSegLen;
  62054. this._oneToManyForSingleFrom(toIdxStart, toCount, fromIdx >= fromListLen ? null : fromIdx);
  62055. }
  62056. }
  62057. };
  62058. MorphPreparation.prototype._oneToOneForSingleTo = function ( // "to" must NOT be null/undefined.
  62059. toIdx, // May `fromIdx >= this._fromList.length`
  62060. fromIdx) {
  62061. var to = this._toList[toIdx];
  62062. var toElOption = this._toElOptionList[toIdx];
  62063. var toDataIndex = this._toDataIndices[toIdx];
  62064. var allPropsFinal = this._allPropsFinalList[toIdx];
  62065. var from = this._fromList[fromIdx];
  62066. var elAnimationConfig = this._getOrCreateMorphConfig(toDataIndex);
  62067. var morphDuration = elAnimationConfig.duration;
  62068. if (from && isCombiningPath(from)) {
  62069. applyPropsFinal(to, allPropsFinal, toElOption.style);
  62070. if (morphDuration) {
  62071. var combineResult = combine([from], to, elAnimationConfig, copyPropsWhenDivided);
  62072. this._processResultIndividuals(combineResult, toIdx, null);
  62073. } // The target el will not be displayed and transition from multiple path.
  62074. // transition on the target el does not make sense.
  62075. } else {
  62076. var morphFrom = morphDuration // from === to usually happen in scenarios where internal update like
  62077. // "dataZoom", "legendToggle" happen. If from is not in any morphing,
  62078. // we do not need to call `morphPath`.
  62079. && from && (from !== to || isInAnyMorphing(from)) ? from : null; // See [Case_II] above.
  62080. // In this case, there is probably `from === to`. And the `transitionFromProps` collecting
  62081. // does not depends on morphing. So we collect `transitionFromProps` first.
  62082. var transFromProps = {};
  62083. prepareShapeOrExtraTransitionFrom('shape', to, morphFrom, toElOption, transFromProps, false);
  62084. prepareShapeOrExtraTransitionFrom('extra', to, morphFrom, toElOption, transFromProps, false);
  62085. prepareTransformTransitionFrom(to, morphFrom, toElOption, transFromProps, false);
  62086. prepareStyleTransitionFrom(to, morphFrom, toElOption, toElOption.style, transFromProps, false);
  62087. applyPropsFinal(to, allPropsFinal, toElOption.style);
  62088. if (morphFrom) {
  62089. morphPath(morphFrom, to, elAnimationConfig);
  62090. }
  62091. applyTransitionFrom(to, toDataIndex, toElOption, this._seriesModel, transFromProps, false);
  62092. }
  62093. };
  62094. MorphPreparation.prototype._manyToOneForSingleTo = function ( // "to" must NOT be null/undefined.
  62095. toIdx, // May be null.
  62096. fromIdxStart, fromCount) {
  62097. var to = this._toList[toIdx];
  62098. var toElOption = this._toElOptionList[toIdx];
  62099. var allPropsFinal = this._allPropsFinalList[toIdx];
  62100. applyPropsFinal(to, allPropsFinal, toElOption.style);
  62101. var elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdx]);
  62102. if (elAnimationConfig.duration && fromIdxStart != null) {
  62103. var combineFromList = [];
  62104. for (var fromIdx = fromIdxStart; fromIdx < fromCount; fromIdx++) {
  62105. combineFromList.push(this._fromList[fromIdx]);
  62106. }
  62107. var combineResult = combine(combineFromList, to, elAnimationConfig, copyPropsWhenDivided);
  62108. this._processResultIndividuals(combineResult, toIdx, null);
  62109. }
  62110. };
  62111. MorphPreparation.prototype._oneToManyForSingleFrom = function ( // "to" must NOT be null/undefined.
  62112. toIdxStart, toCount, // May be null
  62113. fromIdx) {
  62114. var from = fromIdx == null ? null : this._fromList[fromIdx];
  62115. var toList = this._toList;
  62116. var separateToList = [];
  62117. for (var toIdx = toIdxStart; toIdx < toCount; toIdx++) {
  62118. var to = toList[toIdx];
  62119. applyPropsFinal(to, this._allPropsFinalList[toIdx], this._toElOptionList[toIdx].style);
  62120. separateToList.push(to);
  62121. }
  62122. var elAnimationConfig = this._getOrCreateMorphConfig(this._toDataIndices[toIdxStart]);
  62123. if (elAnimationConfig.duration && from) {
  62124. var separateResult = separate(from, separateToList, elAnimationConfig, copyPropsWhenDivided);
  62125. this._processResultIndividuals(separateResult, toIdxStart, toCount);
  62126. }
  62127. };
  62128. MorphPreparation.prototype._processResultIndividuals = function (combineSeparateResult, toIdxStart, toCount) {
  62129. var isSeparate = toCount != null;
  62130. for (var i = 0; i < combineSeparateResult.count; i++) {
  62131. var fromIndividual = combineSeparateResult.fromIndividuals[i];
  62132. var toIndividual = combineSeparateResult.toIndividuals[i]; // Here it's a trick:
  62133. // For "combine" case, all of the `toIndividuals` map to the same `toIdx`.
  62134. // For "separate" case, the `toIndividuals` map to some certain segment of `_toList` accurately.
  62135. var toIdx = toIdxStart + (isSeparate ? i : 0);
  62136. var toElOption = this._toElOptionList[toIdx];
  62137. var dataIndex = this._toDataIndices[toIdx];
  62138. var transFromProps = {};
  62139. prepareTransformTransitionFrom(toIndividual, fromIndividual, toElOption, transFromProps, false);
  62140. prepareStyleTransitionFrom(toIndividual, fromIndividual, toElOption, toElOption.style, transFromProps, false);
  62141. applyTransitionFrom(toIndividual, dataIndex, toElOption, this._seriesModel, transFromProps, false);
  62142. }
  62143. };
  62144. MorphPreparation.prototype._getOrCreateMorphConfig = function (dataIndex) {
  62145. var morphConfigList = this._morphConfigList;
  62146. var config = morphConfigList[dataIndex];
  62147. if (config) {
  62148. return config;
  62149. }
  62150. var duration;
  62151. var easing;
  62152. var delay;
  62153. var seriesModel = this._seriesModel;
  62154. var transOpt = this._transOpt;
  62155. if (seriesModel.isAnimationEnabled()) {
  62156. // PENDING: refactor? this is the same logic as `src/util/graphic.ts#animateOrSetProps`.
  62157. var animationPayload = void 0;
  62158. if (seriesModel && seriesModel.ecModel) {
  62159. var updatePayload = seriesModel.ecModel.getUpdatePayload();
  62160. animationPayload = updatePayload && updatePayload.animation;
  62161. }
  62162. if (animationPayload) {
  62163. duration = animationPayload.duration || 0;
  62164. easing = animationPayload.easing || 'cubicOut';
  62165. delay = animationPayload.delay || 0;
  62166. } else {
  62167. easing = seriesModel.get('animationEasingUpdate');
  62168. var delayOption = seriesModel.get('animationDelayUpdate');
  62169. delay = isFunction(delayOption) ? delayOption(dataIndex) : delayOption;
  62170. var durationOption = seriesModel.get('animationDurationUpdate');
  62171. duration = isFunction(durationOption) ? durationOption(dataIndex) : durationOption;
  62172. }
  62173. }
  62174. config = {
  62175. duration: duration || 0,
  62176. delay: delay,
  62177. easing: easing,
  62178. dividingMethod: transOpt ? transOpt.dividingMethod : null
  62179. };
  62180. morphConfigList[dataIndex] = config;
  62181. return config;
  62182. };
  62183. MorphPreparation.prototype.reset = function (type) {
  62184. // `this._morphConfigList` can be kept. It only related to `dataIndex`.
  62185. this._type = type;
  62186. this._fromList.length = this._toList.length = this._toElOptionList.length = this._allPropsFinalList.length = this._toDataIndices.length = 0;
  62187. };
  62188. return MorphPreparation;
  62189. }();
  62190. function copyPropsWhenDivided(srcPath, tarPath, willClone) {
  62191. // Do not copy transform props.
  62192. // Sub paths are transfrom based on their host path.
  62193. // tarPath.x = srcPath.x;
  62194. // tarPath.y = srcPath.y;
  62195. // tarPath.scaleX = srcPath.scaleX;
  62196. // tarPath.scaleY = srcPath.scaleY;
  62197. // tarPath.originX = srcPath.originX;
  62198. // tarPath.originY = srcPath.originY;
  62199. // If just carry the style, will not be modifed, so do not copy.
  62200. tarPath.style = willClone ? clone(srcPath.style) : srcPath.style;
  62201. tarPath.zlevel = srcPath.zlevel;
  62202. tarPath.z = srcPath.z;
  62203. tarPath.z2 = srcPath.z2;
  62204. }
  62205. function install$r(registers) {
  62206. registers.registerChartView(CustomSeriesView);
  62207. registers.registerSeriesModel(CustomSeriesModel);
  62208. }
  62209. var inner$c = makeInner();
  62210. var clone$3 = clone;
  62211. var bind$1 = bind;
  62212. /**
  62213. * Base axis pointer class in 2D.
  62214. */
  62215. var BaseAxisPointer =
  62216. /** @class */
  62217. function () {
  62218. function BaseAxisPointer() {
  62219. this._dragging = false;
  62220. /**
  62221. * In px, arbitrary value. Do not set too small,
  62222. * no animation is ok for most cases.
  62223. */
  62224. this.animationThreshold = 15;
  62225. }
  62226. /**
  62227. * @implement
  62228. */
  62229. BaseAxisPointer.prototype.render = function (axisModel, axisPointerModel, api, forceRender) {
  62230. var value = axisPointerModel.get('value');
  62231. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  62232. // be replaced when user calling setOption in not merge mode.
  62233. this._axisModel = axisModel;
  62234. this._axisPointerModel = axisPointerModel;
  62235. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  62236. // So it is power consuming if performing `render` each time,
  62237. // especially on mobile device.
  62238. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  62239. return;
  62240. }
  62241. this._lastValue = value;
  62242. this._lastStatus = status;
  62243. var group = this._group;
  62244. var handle = this._handle;
  62245. if (!status || status === 'hide') {
  62246. // Do not clear here, for animation better.
  62247. group && group.hide();
  62248. handle && handle.hide();
  62249. return;
  62250. }
  62251. group && group.show();
  62252. handle && handle.show(); // Otherwise status is 'show'
  62253. var elOption = {};
  62254. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  62255. var graphicKey = elOption.graphicKey;
  62256. if (graphicKey !== this._lastGraphicKey) {
  62257. this.clear(api);
  62258. }
  62259. this._lastGraphicKey = graphicKey;
  62260. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  62261. if (!group) {
  62262. group = this._group = new Group();
  62263. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  62264. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  62265. api.getZr().add(group);
  62266. } else {
  62267. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  62268. this.updatePointerEl(group, elOption, doUpdateProps);
  62269. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  62270. }
  62271. updateMandatoryProps(group, axisPointerModel, true);
  62272. this._renderHandle(value);
  62273. };
  62274. /**
  62275. * @implement
  62276. */
  62277. BaseAxisPointer.prototype.remove = function (api) {
  62278. this.clear(api);
  62279. };
  62280. /**
  62281. * @implement
  62282. */
  62283. BaseAxisPointer.prototype.dispose = function (api) {
  62284. this.clear(api);
  62285. };
  62286. /**
  62287. * @protected
  62288. */
  62289. BaseAxisPointer.prototype.determineAnimation = function (axisModel, axisPointerModel) {
  62290. var animation = axisPointerModel.get('animation');
  62291. var axis = axisModel.axis;
  62292. var isCategoryAxis = axis.type === 'category';
  62293. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  62294. if (!useSnap && !isCategoryAxis) {
  62295. return false;
  62296. }
  62297. if (animation === 'auto' || animation == null) {
  62298. var animationThreshold = this.animationThreshold;
  62299. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  62300. return true;
  62301. } // It is important to auto animation when snap used. Consider if there is
  62302. // a dataZoom, animation will be disabled when too many points exist, while
  62303. // it will be enabled for better visual effect when little points exist.
  62304. if (useSnap) {
  62305. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  62306. var axisExtent = axis.getExtent(); // Approximate band width
  62307. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  62308. }
  62309. return false;
  62310. }
  62311. return animation === true;
  62312. };
  62313. /**
  62314. * add {pointer, label, graphicKey} to elOption
  62315. * @protected
  62316. */
  62317. BaseAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  62318. };
  62319. /**
  62320. * @protected
  62321. */
  62322. BaseAxisPointer.prototype.createPointerEl = function (group, elOption, axisModel, axisPointerModel) {
  62323. var pointerOption = elOption.pointer;
  62324. if (pointerOption) {
  62325. var pointerEl = inner$c(group).pointerEl = new graphic[pointerOption.type](clone$3(elOption.pointer));
  62326. group.add(pointerEl);
  62327. }
  62328. };
  62329. /**
  62330. * @protected
  62331. */
  62332. BaseAxisPointer.prototype.createLabelEl = function (group, elOption, axisModel, axisPointerModel) {
  62333. if (elOption.label) {
  62334. var labelEl = inner$c(group).labelEl = new ZRText(clone$3(elOption.label));
  62335. group.add(labelEl);
  62336. updateLabelShowHide(labelEl, axisPointerModel);
  62337. }
  62338. };
  62339. /**
  62340. * @protected
  62341. */
  62342. BaseAxisPointer.prototype.updatePointerEl = function (group, elOption, updateProps) {
  62343. var pointerEl = inner$c(group).pointerEl;
  62344. if (pointerEl && elOption.pointer) {
  62345. pointerEl.setStyle(elOption.pointer.style);
  62346. updateProps(pointerEl, {
  62347. shape: elOption.pointer.shape
  62348. });
  62349. }
  62350. };
  62351. /**
  62352. * @protected
  62353. */
  62354. BaseAxisPointer.prototype.updateLabelEl = function (group, elOption, updateProps, axisPointerModel) {
  62355. var labelEl = inner$c(group).labelEl;
  62356. if (labelEl) {
  62357. labelEl.setStyle(elOption.label.style);
  62358. updateProps(labelEl, {
  62359. // Consider text length change in vertical axis, animation should
  62360. // be used on shape, otherwise the effect will be weird.
  62361. // TODOTODO
  62362. // shape: elOption.label.shape,
  62363. x: elOption.label.x,
  62364. y: elOption.label.y
  62365. });
  62366. updateLabelShowHide(labelEl, axisPointerModel);
  62367. }
  62368. };
  62369. /**
  62370. * @private
  62371. */
  62372. BaseAxisPointer.prototype._renderHandle = function (value) {
  62373. if (this._dragging || !this.updateHandleTransform) {
  62374. return;
  62375. }
  62376. var axisPointerModel = this._axisPointerModel;
  62377. var zr = this._api.getZr();
  62378. var handle = this._handle;
  62379. var handleModel = axisPointerModel.getModel('handle');
  62380. var status = axisPointerModel.get('status');
  62381. if (!handleModel.get('show') || !status || status === 'hide') {
  62382. handle && zr.remove(handle);
  62383. this._handle = null;
  62384. return;
  62385. }
  62386. var isInit;
  62387. if (!this._handle) {
  62388. isInit = true;
  62389. handle = this._handle = createIcon(handleModel.get('icon'), {
  62390. cursor: 'move',
  62391. draggable: true,
  62392. onmousemove: function (e) {
  62393. // Fot mobile devicem, prevent screen slider on the button.
  62394. stop(e.event);
  62395. },
  62396. onmousedown: bind$1(this._onHandleDragMove, this, 0, 0),
  62397. drift: bind$1(this._onHandleDragMove, this),
  62398. ondragend: bind$1(this._onHandleDragEnd, this)
  62399. });
  62400. zr.add(handle);
  62401. }
  62402. updateMandatoryProps(handle, axisPointerModel, false); // update style
  62403. handle.setStyle(handleModel.getItemStyle(null, ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'])); // update position
  62404. var handleSize = handleModel.get('size');
  62405. if (!isArray(handleSize)) {
  62406. handleSize = [handleSize, handleSize];
  62407. }
  62408. handle.scaleX = handleSize[0] / 2;
  62409. handle.scaleY = handleSize[1] / 2;
  62410. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  62411. this._moveHandleToValue(value, isInit);
  62412. };
  62413. BaseAxisPointer.prototype._moveHandleToValue = function (value, isInit) {
  62414. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  62415. };
  62416. BaseAxisPointer.prototype._onHandleDragMove = function (dx, dy) {
  62417. var handle = this._handle;
  62418. if (!handle) {
  62419. return;
  62420. }
  62421. this._dragging = true; // Persistent for throttle.
  62422. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  62423. this._payloadInfo = trans;
  62424. handle.stopAnimation();
  62425. handle.attr(getHandleTransProps(trans));
  62426. inner$c(handle).lastProp = null;
  62427. this._doDispatchAxisPointer();
  62428. };
  62429. /**
  62430. * Throttled method.
  62431. */
  62432. BaseAxisPointer.prototype._doDispatchAxisPointer = function () {
  62433. var handle = this._handle;
  62434. if (!handle) {
  62435. return;
  62436. }
  62437. var payloadInfo = this._payloadInfo;
  62438. var axisModel = this._axisModel;
  62439. this._api.dispatchAction({
  62440. type: 'updateAxisPointer',
  62441. x: payloadInfo.cursorPoint[0],
  62442. y: payloadInfo.cursorPoint[1],
  62443. tooltipOption: payloadInfo.tooltipOption,
  62444. axesInfo: [{
  62445. axisDim: axisModel.axis.dim,
  62446. axisIndex: axisModel.componentIndex
  62447. }]
  62448. });
  62449. };
  62450. BaseAxisPointer.prototype._onHandleDragEnd = function () {
  62451. this._dragging = false;
  62452. var handle = this._handle;
  62453. if (!handle) {
  62454. return;
  62455. }
  62456. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  62457. // axisPointer. So move handle to align the exact value position when
  62458. // drag ended.
  62459. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  62460. // button, and will be hidden after finger left handle button.
  62461. this._api.dispatchAction({
  62462. type: 'hideTip'
  62463. });
  62464. };
  62465. /**
  62466. * @private
  62467. */
  62468. BaseAxisPointer.prototype.clear = function (api) {
  62469. this._lastValue = null;
  62470. this._lastStatus = null;
  62471. var zr = api.getZr();
  62472. var group = this._group;
  62473. var handle = this._handle;
  62474. if (zr && group) {
  62475. this._lastGraphicKey = null;
  62476. group && zr.remove(group);
  62477. handle && zr.remove(handle);
  62478. this._group = null;
  62479. this._handle = null;
  62480. this._payloadInfo = null;
  62481. }
  62482. };
  62483. /**
  62484. * @protected
  62485. */
  62486. BaseAxisPointer.prototype.doClear = function () {// Implemented by sub-class if necessary.
  62487. };
  62488. BaseAxisPointer.prototype.buildLabel = function (xy, wh, xDimIndex) {
  62489. xDimIndex = xDimIndex || 0;
  62490. return {
  62491. x: xy[xDimIndex],
  62492. y: xy[1 - xDimIndex],
  62493. width: wh[xDimIndex],
  62494. height: wh[1 - xDimIndex]
  62495. };
  62496. };
  62497. return BaseAxisPointer;
  62498. }();
  62499. function updateProps$1(animationModel, moveAnimation, el, props) {
  62500. // Animation optimize.
  62501. if (!propsEqual(inner$c(el).lastProp, props)) {
  62502. inner$c(el).lastProp = props;
  62503. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  62504. }
  62505. }
  62506. function propsEqual(lastProps, newProps) {
  62507. if (isObject(lastProps) && isObject(newProps)) {
  62508. var equals_1 = true;
  62509. each(newProps, function (item, key) {
  62510. equals_1 = equals_1 && propsEqual(lastProps[key], item);
  62511. });
  62512. return !!equals_1;
  62513. } else {
  62514. return lastProps === newProps;
  62515. }
  62516. }
  62517. function updateLabelShowHide(labelEl, axisPointerModel) {
  62518. labelEl[axisPointerModel.get(['label', 'show']) ? 'show' : 'hide']();
  62519. }
  62520. function getHandleTransProps(trans) {
  62521. return {
  62522. x: trans.x || 0,
  62523. y: trans.y || 0,
  62524. rotation: trans.rotation || 0
  62525. };
  62526. }
  62527. function updateMandatoryProps(group, axisPointerModel, silent) {
  62528. var z = axisPointerModel.get('z');
  62529. var zlevel = axisPointerModel.get('zlevel');
  62530. group && group.traverse(function (el) {
  62531. if (el.type !== 'group') {
  62532. z != null && (el.z = z);
  62533. zlevel != null && (el.zlevel = zlevel);
  62534. el.silent = silent;
  62535. }
  62536. });
  62537. }
  62538. function buildElStyle(axisPointerModel) {
  62539. var axisPointerType = axisPointerModel.get('type');
  62540. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  62541. var style;
  62542. if (axisPointerType === 'line') {
  62543. style = styleModel.getLineStyle();
  62544. style.fill = null;
  62545. } else if (axisPointerType === 'shadow') {
  62546. style = styleModel.getAreaStyle();
  62547. style.stroke = null;
  62548. }
  62549. return style;
  62550. }
  62551. /**
  62552. * @param {Function} labelPos {align, verticalAlign, position}
  62553. */
  62554. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  62555. var value = axisPointerModel.get('value');
  62556. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  62557. precision: axisPointerModel.get(['label', 'precision']),
  62558. formatter: axisPointerModel.get(['label', 'formatter'])
  62559. });
  62560. var labelModel = axisPointerModel.getModel('label');
  62561. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  62562. var font = labelModel.getFont();
  62563. var textRect = getBoundingRect(text, font);
  62564. var position = labelPos.position;
  62565. var width = textRect.width + paddings[1] + paddings[3];
  62566. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  62567. var align = labelPos.align;
  62568. align === 'right' && (position[0] -= width);
  62569. align === 'center' && (position[0] -= width / 2);
  62570. var verticalAlign = labelPos.verticalAlign;
  62571. verticalAlign === 'bottom' && (position[1] -= height);
  62572. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  62573. confineInContainer(position, width, height, api);
  62574. var bgColor = labelModel.get('backgroundColor');
  62575. if (!bgColor || bgColor === 'auto') {
  62576. bgColor = axisModel.get(['axisLine', 'lineStyle', 'color']);
  62577. }
  62578. elOption.label = {
  62579. // shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  62580. x: position[0],
  62581. y: position[1],
  62582. style: createTextStyle(labelModel, {
  62583. text: text,
  62584. font: font,
  62585. fill: labelModel.getTextColor(),
  62586. padding: paddings,
  62587. backgroundColor: bgColor
  62588. }),
  62589. // Lable should be over axisPointer.
  62590. z2: 10
  62591. };
  62592. } // Do not overflow ec container
  62593. function confineInContainer(position, width, height, api) {
  62594. var viewWidth = api.getWidth();
  62595. var viewHeight = api.getHeight();
  62596. position[0] = Math.min(position[0] + width, viewWidth) - width;
  62597. position[1] = Math.min(position[1] + height, viewHeight) - height;
  62598. position[0] = Math.max(position[0], 0);
  62599. position[1] = Math.max(position[1], 0);
  62600. }
  62601. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  62602. value = axis.scale.parse(value);
  62603. var text = axis.scale.getLabel({
  62604. value: value
  62605. }, {
  62606. // If `precision` is set, width can be fixed (like '12.00500'), which
  62607. // helps to debounce when when moving label.
  62608. precision: opt.precision
  62609. });
  62610. var formatter = opt.formatter;
  62611. if (formatter) {
  62612. var params_1 = {
  62613. value: getAxisRawValue(axis, {
  62614. value: value
  62615. }),
  62616. axisDimension: axis.dim,
  62617. axisIndex: axis.index,
  62618. seriesData: []
  62619. };
  62620. each(seriesDataIndices, function (idxItem) {
  62621. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  62622. var dataIndex = idxItem.dataIndexInside;
  62623. var dataParams = series && series.getDataParams(dataIndex);
  62624. dataParams && params_1.seriesData.push(dataParams);
  62625. });
  62626. if (isString(formatter)) {
  62627. text = formatter.replace('{value}', text);
  62628. } else if (isFunction(formatter)) {
  62629. text = formatter(params_1);
  62630. }
  62631. }
  62632. return text;
  62633. }
  62634. function getTransformedPosition(axis, value, layoutInfo) {
  62635. var transform = create$1();
  62636. rotate(transform, transform, layoutInfo.rotation);
  62637. translate(transform, transform, layoutInfo.position);
  62638. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  62639. }
  62640. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  62641. // @ts-ignore
  62642. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  62643. layoutInfo.labelMargin = axisPointerModel.get(['label', 'margin']);
  62644. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  62645. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  62646. align: textLayout.textAlign,
  62647. verticalAlign: textLayout.textVerticalAlign
  62648. });
  62649. }
  62650. function makeLineShape(p1, p2, xDimIndex) {
  62651. xDimIndex = xDimIndex || 0;
  62652. return {
  62653. x1: p1[xDimIndex],
  62654. y1: p1[1 - xDimIndex],
  62655. x2: p2[xDimIndex],
  62656. y2: p2[1 - xDimIndex]
  62657. };
  62658. }
  62659. function makeRectShape(xy, wh, xDimIndex) {
  62660. xDimIndex = xDimIndex || 0;
  62661. return {
  62662. x: xy[xDimIndex],
  62663. y: xy[1 - xDimIndex],
  62664. width: wh[xDimIndex],
  62665. height: wh[1 - xDimIndex]
  62666. };
  62667. }
  62668. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  62669. return {
  62670. cx: cx,
  62671. cy: cy,
  62672. r0: r0,
  62673. r: r,
  62674. startAngle: startAngle,
  62675. endAngle: endAngle,
  62676. clockwise: true
  62677. };
  62678. }
  62679. var CartesianAxisPointer =
  62680. /** @class */
  62681. function (_super) {
  62682. __extends(CartesianAxisPointer, _super);
  62683. function CartesianAxisPointer() {
  62684. return _super !== null && _super.apply(this, arguments) || this;
  62685. }
  62686. /**
  62687. * @override
  62688. */
  62689. CartesianAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  62690. var axis = axisModel.axis;
  62691. var grid = axis.grid;
  62692. var axisPointerType = axisPointerModel.get('type');
  62693. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  62694. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  62695. if (axisPointerType && axisPointerType !== 'none') {
  62696. var elStyle = buildElStyle(axisPointerModel);
  62697. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  62698. pointerOption.style = elStyle;
  62699. elOption.graphicKey = pointerOption.type;
  62700. elOption.pointer = pointerOption;
  62701. }
  62702. var layoutInfo = layout$1(grid.model, axisModel);
  62703. buildCartesianSingleLabelElOption( // @ts-ignore
  62704. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  62705. };
  62706. /**
  62707. * @override
  62708. */
  62709. CartesianAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  62710. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  62711. labelInside: false
  62712. }); // @ts-ignore
  62713. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  62714. var pos = getTransformedPosition(axisModel.axis, value, layoutInfo);
  62715. return {
  62716. x: pos[0],
  62717. y: pos[1],
  62718. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  62719. };
  62720. };
  62721. /**
  62722. * @override
  62723. */
  62724. CartesianAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  62725. var axis = axisModel.axis;
  62726. var grid = axis.grid;
  62727. var axisExtent = axis.getGlobalExtent(true);
  62728. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  62729. var dimIndex = axis.dim === 'x' ? 0 : 1;
  62730. var currPosition = [transform.x, transform.y];
  62731. currPosition[dimIndex] += delta[dimIndex];
  62732. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  62733. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  62734. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  62735. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  62736. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  62737. var tooltipOptions = [{
  62738. verticalAlign: 'middle'
  62739. }, {
  62740. align: 'center'
  62741. }];
  62742. return {
  62743. x: currPosition[0],
  62744. y: currPosition[1],
  62745. rotation: transform.rotation,
  62746. cursorPoint: cursorPoint,
  62747. tooltipOption: tooltipOptions[dimIndex]
  62748. };
  62749. };
  62750. return CartesianAxisPointer;
  62751. }(BaseAxisPointer);
  62752. function getCartesian(grid, axis) {
  62753. var opt = {};
  62754. opt[axis.dim + 'AxisIndex'] = axis.index;
  62755. return grid.getCartesian(opt);
  62756. }
  62757. var pointerShapeBuilder = {
  62758. line: function (axis, pixelValue, otherExtent) {
  62759. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  62760. return {
  62761. type: 'Line',
  62762. subPixelOptimize: true,
  62763. shape: targetShape
  62764. };
  62765. },
  62766. shadow: function (axis, pixelValue, otherExtent) {
  62767. var bandWidth = Math.max(1, axis.getBandWidth());
  62768. var span = otherExtent[1] - otherExtent[0];
  62769. return {
  62770. type: 'Rect',
  62771. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  62772. };
  62773. }
  62774. };
  62775. function getAxisDimIndex(axis) {
  62776. return axis.dim === 'x' ? 0 : 1;
  62777. }
  62778. var AxisPointerModel =
  62779. /** @class */
  62780. function (_super) {
  62781. __extends(AxisPointerModel, _super);
  62782. function AxisPointerModel() {
  62783. var _this = _super !== null && _super.apply(this, arguments) || this;
  62784. _this.type = AxisPointerModel.type;
  62785. return _this;
  62786. }
  62787. AxisPointerModel.type = 'axisPointer';
  62788. AxisPointerModel.defaultOption = {
  62789. // 'auto' means that show when triggered by tooltip or handle.
  62790. show: 'auto',
  62791. zlevel: 0,
  62792. z: 50,
  62793. type: 'line',
  62794. // axispointer triggered by tootip determine snap automatically,
  62795. // see `modelHelper`.
  62796. snap: false,
  62797. triggerTooltip: true,
  62798. value: null,
  62799. status: null,
  62800. link: [],
  62801. // Do not set 'auto' here, otherwise global animation: false
  62802. // will not effect at this axispointer.
  62803. animation: null,
  62804. animationDurationUpdate: 200,
  62805. lineStyle: {
  62806. color: '#B9BEC9',
  62807. width: 1,
  62808. type: 'dashed'
  62809. },
  62810. shadowStyle: {
  62811. color: 'rgba(210,219,238,0.2)'
  62812. },
  62813. label: {
  62814. show: true,
  62815. formatter: null,
  62816. precision: 'auto',
  62817. margin: 3,
  62818. color: '#fff',
  62819. padding: [5, 7, 5, 7],
  62820. backgroundColor: 'auto',
  62821. borderColor: null,
  62822. borderWidth: 0,
  62823. borderRadius: 3
  62824. },
  62825. handle: {
  62826. show: false,
  62827. // eslint-disable-next-line
  62828. 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',
  62829. size: 45,
  62830. // handle margin is from symbol center to axis, which is stable when circular move.
  62831. margin: 50,
  62832. // color: '#1b8bbd'
  62833. // color: '#2f4554'
  62834. color: '#333',
  62835. shadowBlur: 3,
  62836. shadowColor: '#aaa',
  62837. shadowOffsetX: 0,
  62838. shadowOffsetY: 2,
  62839. // For mobile performance
  62840. throttle: 40
  62841. }
  62842. };
  62843. return AxisPointerModel;
  62844. }(ComponentModel);
  62845. var inner$d = makeInner();
  62846. var each$8 = each;
  62847. /**
  62848. * @param {string} key
  62849. * @param {module:echarts/ExtensionAPI} api
  62850. * @param {Function} handler
  62851. * param: {string} currTrigger
  62852. * param: {Array.<number>} point
  62853. */
  62854. function register(key, api, handler) {
  62855. if (env.node) {
  62856. return;
  62857. }
  62858. var zr = api.getZr();
  62859. inner$d(zr).records || (inner$d(zr).records = {});
  62860. initGlobalListeners(zr, api);
  62861. var record = inner$d(zr).records[key] || (inner$d(zr).records[key] = {});
  62862. record.handler = handler;
  62863. }
  62864. function initGlobalListeners(zr, api) {
  62865. if (inner$d(zr).initialized) {
  62866. return;
  62867. }
  62868. inner$d(zr).initialized = true;
  62869. useHandler('click', curry(doEnter, 'click'));
  62870. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  62871. useHandler('globalout', onLeave);
  62872. function useHandler(eventType, cb) {
  62873. zr.on(eventType, function (e) {
  62874. var dis = makeDispatchAction(api);
  62875. each$8(inner$d(zr).records, function (record) {
  62876. record && cb(record, e, dis.dispatchAction);
  62877. });
  62878. dispatchTooltipFinally(dis.pendings, api);
  62879. });
  62880. }
  62881. }
  62882. function dispatchTooltipFinally(pendings, api) {
  62883. var showLen = pendings.showTip.length;
  62884. var hideLen = pendings.hideTip.length;
  62885. var actuallyPayload;
  62886. if (showLen) {
  62887. actuallyPayload = pendings.showTip[showLen - 1];
  62888. } else if (hideLen) {
  62889. actuallyPayload = pendings.hideTip[hideLen - 1];
  62890. }
  62891. if (actuallyPayload) {
  62892. actuallyPayload.dispatchAction = null;
  62893. api.dispatchAction(actuallyPayload);
  62894. }
  62895. }
  62896. function onLeave(record, e, dispatchAction) {
  62897. record.handler('leave', null, dispatchAction);
  62898. }
  62899. function doEnter(currTrigger, record, e, dispatchAction) {
  62900. record.handler(currTrigger, e, dispatchAction);
  62901. }
  62902. function makeDispatchAction(api) {
  62903. var pendings = {
  62904. showTip: [],
  62905. hideTip: []
  62906. }; // FIXME
  62907. // better approach?
  62908. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  62909. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  62910. // So we have to add "final stage" to merge those dispatched actions.
  62911. var dispatchAction = function (payload) {
  62912. var pendingList = pendings[payload.type];
  62913. if (pendingList) {
  62914. pendingList.push(payload);
  62915. } else {
  62916. payload.dispatchAction = dispatchAction;
  62917. api.dispatchAction(payload);
  62918. }
  62919. };
  62920. return {
  62921. dispatchAction: dispatchAction,
  62922. pendings: pendings
  62923. };
  62924. }
  62925. function unregister(key, api) {
  62926. if (env.node) {
  62927. return;
  62928. }
  62929. var zr = api.getZr();
  62930. var record = (inner$d(zr).records || {})[key];
  62931. if (record) {
  62932. inner$d(zr).records[key] = null;
  62933. }
  62934. }
  62935. var AxisPointerView =
  62936. /** @class */
  62937. function (_super) {
  62938. __extends(AxisPointerView, _super);
  62939. function AxisPointerView() {
  62940. var _this = _super !== null && _super.apply(this, arguments) || this;
  62941. _this.type = AxisPointerView.type;
  62942. return _this;
  62943. }
  62944. AxisPointerView.prototype.render = function (globalAxisPointerModel, ecModel, api) {
  62945. var globalTooltipModel = ecModel.getComponent('tooltip');
  62946. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  62947. // AxisPointerView to be independent to Tooltip.
  62948. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  62949. // If 'none', it is not controlled by mouse totally.
  62950. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  62951. dispatchAction({
  62952. type: 'updateAxisPointer',
  62953. currTrigger: currTrigger,
  62954. x: e && e.offsetX,
  62955. y: e && e.offsetY
  62956. });
  62957. }
  62958. });
  62959. };
  62960. AxisPointerView.prototype.remove = function (ecModel, api) {
  62961. unregister('axisPointer', api);
  62962. };
  62963. AxisPointerView.prototype.dispose = function (ecModel, api) {
  62964. unregister('axisPointer', api);
  62965. };
  62966. AxisPointerView.type = 'axisPointer';
  62967. return AxisPointerView;
  62968. }(ComponentView);
  62969. /**
  62970. * @param finder contains {seriesIndex, dataIndex, dataIndexInside}
  62971. * @param ecModel
  62972. * @return {point: [x, y], el: ...} point Will not be null.
  62973. */
  62974. function findPointFromSeries(finder, ecModel) {
  62975. var point = [];
  62976. var seriesIndex = finder.seriesIndex;
  62977. var seriesModel;
  62978. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  62979. return {
  62980. point: []
  62981. };
  62982. }
  62983. var data = seriesModel.getData();
  62984. var dataIndex = queryDataIndex(data, finder);
  62985. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  62986. return {
  62987. point: []
  62988. };
  62989. }
  62990. var el = data.getItemGraphicEl(dataIndex);
  62991. var coordSys = seriesModel.coordinateSystem;
  62992. if (seriesModel.getTooltipPosition) {
  62993. point = seriesModel.getTooltipPosition(dataIndex) || [];
  62994. } else if (coordSys && coordSys.dataToPoint) {
  62995. if (finder.isStacked) {
  62996. var baseAxis = coordSys.getBaseAxis();
  62997. var valueAxis = coordSys.getOtherAxis(baseAxis);
  62998. var valueAxisDim = valueAxis.dim;
  62999. var baseAxisDim = baseAxis.dim;
  63000. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  63001. var baseDim = data.mapDimension(baseAxisDim);
  63002. var stackedData = [];
  63003. stackedData[baseDataOffset] = data.get(baseDim, dataIndex);
  63004. stackedData[1 - baseDataOffset] = data.get(data.getCalculationInfo('stackResultDimension'), dataIndex);
  63005. point = coordSys.dataToPoint(stackedData) || [];
  63006. } else {
  63007. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  63008. return data.mapDimension(dim);
  63009. }), dataIndex)) || [];
  63010. }
  63011. } else if (el) {
  63012. // Use graphic bounding rect
  63013. var rect = el.getBoundingRect().clone();
  63014. rect.applyTransform(el.transform);
  63015. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  63016. }
  63017. return {
  63018. point: point,
  63019. el: el
  63020. };
  63021. }
  63022. var inner$e = makeInner();
  63023. /**
  63024. * Basic logic: check all axis, if they do not demand show/highlight,
  63025. * then hide/downplay them.
  63026. *
  63027. * @return content of event obj for echarts.connect.
  63028. */
  63029. function axisTrigger(payload, ecModel, api) {
  63030. var currTrigger = payload.currTrigger;
  63031. var point = [payload.x, payload.y];
  63032. var finder = payload;
  63033. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  63034. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  63035. // See #6121. But we are not able to reproduce it yet.
  63036. if (!coordSysAxesInfo) {
  63037. return;
  63038. }
  63039. if (illegalPoint(point)) {
  63040. // Used in the default behavior of `connection`: use the sample seriesIndex
  63041. // and dataIndex. And also used in the tooltipView trigger.
  63042. point = findPointFromSeries({
  63043. seriesIndex: finder.seriesIndex,
  63044. // Do not use dataIndexInside from other ec instance.
  63045. // FIXME: auto detect it?
  63046. dataIndex: finder.dataIndex
  63047. }, ecModel).point;
  63048. }
  63049. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  63050. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  63051. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  63052. // and dataIndex.
  63053. var inputAxesInfo = finder.axesInfo;
  63054. var axesInfo = coordSysAxesInfo.axesInfo;
  63055. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  63056. var outputPayload = {};
  63057. var showValueMap = {};
  63058. var dataByCoordSys = {
  63059. list: [],
  63060. map: {}
  63061. };
  63062. var updaters = {
  63063. showPointer: curry(showPointer, showValueMap),
  63064. showTooltip: curry(showTooltip, dataByCoordSys)
  63065. }; // Process for triggered axes.
  63066. each(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  63067. // If a point given, it must be contained by the coordinate system.
  63068. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  63069. each(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  63070. var axis = axisInfo.axis;
  63071. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  63072. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  63073. var val = inputAxisInfo && inputAxisInfo.value;
  63074. if (val == null && !isIllegalPoint) {
  63075. val = axis.pointToData(point);
  63076. }
  63077. val != null && processOnAxis(axisInfo, val, updaters, false, outputPayload);
  63078. }
  63079. });
  63080. }); // Process for linked axes.
  63081. var linkTriggers = {};
  63082. each(axesInfo, function (tarAxisInfo, tarKey) {
  63083. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  63084. if (linkGroup && !showValueMap[tarKey]) {
  63085. each(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  63086. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  63087. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  63088. var val = srcValItem.value;
  63089. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  63090. linkTriggers[tarAxisInfo.key] = val;
  63091. }
  63092. });
  63093. }
  63094. });
  63095. each(linkTriggers, function (val, tarKey) {
  63096. processOnAxis(axesInfo[tarKey], val, updaters, true, outputPayload);
  63097. });
  63098. updateModelActually(showValueMap, axesInfo, outputPayload);
  63099. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  63100. dispatchHighDownActually(axesInfo, dispatchAction, api);
  63101. return outputPayload;
  63102. }
  63103. function processOnAxis(axisInfo, newValue, updaters, noSnap, outputFinder) {
  63104. var axis = axisInfo.axis;
  63105. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  63106. return;
  63107. }
  63108. if (!axisInfo.involveSeries) {
  63109. updaters.showPointer(axisInfo, newValue);
  63110. return;
  63111. } // Heavy calculation. So put it after axis.containData checking.
  63112. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  63113. var payloadBatch = payloadInfo.payloadBatch;
  63114. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  63115. // By default use the first involved series data as a sample to connect.
  63116. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  63117. extend(outputFinder, payloadBatch[0]);
  63118. } // If no linkSource input, this process is for collecting link
  63119. // target, where snap should not be accepted.
  63120. if (!noSnap && axisInfo.snap) {
  63121. if (axis.containData(snapToValue) && snapToValue != null) {
  63122. newValue = snapToValue;
  63123. }
  63124. }
  63125. updaters.showPointer(axisInfo, newValue, payloadBatch); // Tooltip should always be snapToValue, otherwise there will be
  63126. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  63127. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  63128. }
  63129. function buildPayloadsBySeries(value, axisInfo) {
  63130. var axis = axisInfo.axis;
  63131. var dim = axis.dim;
  63132. var snapToValue = value;
  63133. var payloadBatch = [];
  63134. var minDist = Number.MAX_VALUE;
  63135. var minDiff = -1;
  63136. each(axisInfo.seriesModels, function (series, idx) {
  63137. var dataDim = series.getData().mapDimensionsAll(dim);
  63138. var seriesNestestValue;
  63139. var dataIndices;
  63140. if (series.getAxisTooltipData) {
  63141. var result = series.getAxisTooltipData(dataDim, value, axis);
  63142. dataIndices = result.dataIndices;
  63143. seriesNestestValue = result.nestestValue;
  63144. } else {
  63145. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  63146. // when data length is not same.
  63147. // false,
  63148. axis.type === 'category' ? 0.5 : null);
  63149. if (!dataIndices.length) {
  63150. return;
  63151. }
  63152. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  63153. }
  63154. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  63155. return;
  63156. }
  63157. var diff = value - seriesNestestValue;
  63158. var dist = Math.abs(diff); // Consider category case
  63159. if (dist <= minDist) {
  63160. if (dist < minDist || diff >= 0 && minDiff < 0) {
  63161. minDist = dist;
  63162. minDiff = diff;
  63163. snapToValue = seriesNestestValue;
  63164. payloadBatch.length = 0;
  63165. }
  63166. each(dataIndices, function (dataIndex) {
  63167. payloadBatch.push({
  63168. seriesIndex: series.seriesIndex,
  63169. dataIndexInside: dataIndex,
  63170. dataIndex: series.getData().getRawIndex(dataIndex)
  63171. });
  63172. });
  63173. }
  63174. });
  63175. return {
  63176. payloadBatch: payloadBatch,
  63177. snapToValue: snapToValue
  63178. };
  63179. }
  63180. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  63181. showValueMap[axisInfo.key] = {
  63182. value: value,
  63183. payloadBatch: payloadBatch
  63184. };
  63185. }
  63186. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  63187. var payloadBatch = payloadInfo.payloadBatch;
  63188. var axis = axisInfo.axis;
  63189. var axisModel = axis.model;
  63190. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  63191. // whose length will be used to judge whether dispatch action.
  63192. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  63193. return;
  63194. }
  63195. var coordSysModel = axisInfo.coordSys.model;
  63196. var coordSysKey = makeKey(coordSysModel);
  63197. var coordSysItem = dataByCoordSys.map[coordSysKey];
  63198. if (!coordSysItem) {
  63199. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  63200. coordSysId: coordSysModel.id,
  63201. coordSysIndex: coordSysModel.componentIndex,
  63202. coordSysType: coordSysModel.type,
  63203. coordSysMainType: coordSysModel.mainType,
  63204. dataByAxis: []
  63205. };
  63206. dataByCoordSys.list.push(coordSysItem);
  63207. }
  63208. coordSysItem.dataByAxis.push({
  63209. axisDim: axis.dim,
  63210. axisIndex: axisModel.componentIndex,
  63211. axisType: axisModel.type,
  63212. axisId: axisModel.id,
  63213. value: value,
  63214. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  63215. // depends that all models have been updated. So it should not be performed
  63216. // here. Considering axisPointerModel used here is volatile, which is hard
  63217. // to be retrieve in TooltipView, we prepare parameters here.
  63218. valueLabelOpt: {
  63219. precision: axisPointerModel.get(['label', 'precision']),
  63220. formatter: axisPointerModel.get(['label', 'formatter'])
  63221. },
  63222. seriesDataIndices: payloadBatch.slice()
  63223. });
  63224. }
  63225. function updateModelActually(showValueMap, axesInfo, outputPayload) {
  63226. var outputAxesInfo = outputPayload.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  63227. each(axesInfo, function (axisInfo, key) {
  63228. var option = axisInfo.axisPointerModel.option;
  63229. var valItem = showValueMap[key];
  63230. if (valItem) {
  63231. !axisInfo.useHandle && (option.status = 'show');
  63232. option.value = valItem.value; // For label formatter param and highlight.
  63233. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  63234. } // When always show (e.g., handle used), remain
  63235. // original value and status.
  63236. else {
  63237. // If hide, value still need to be set, consider
  63238. // click legend to toggle axis blank.
  63239. !axisInfo.useHandle && (option.status = 'hide');
  63240. } // If status is 'hide', should be no info in payload.
  63241. option.status === 'show' && outputAxesInfo.push({
  63242. axisDim: axisInfo.axis.dim,
  63243. axisIndex: axisInfo.axis.model.componentIndex,
  63244. value: option.value
  63245. });
  63246. });
  63247. }
  63248. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  63249. // Basic logic: If no showTip required, hideTip will be dispatched.
  63250. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  63251. dispatchAction({
  63252. type: 'hideTip'
  63253. });
  63254. return;
  63255. } // In most case only one axis (or event one series is used). It is
  63256. // convinient to fetch payload.seriesIndex and payload.dataIndex
  63257. // dirtectly. So put the first seriesIndex and dataIndex of the first
  63258. // axis on the payload.
  63259. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  63260. dispatchAction({
  63261. type: 'showTip',
  63262. escapeConnect: true,
  63263. x: point[0],
  63264. y: point[1],
  63265. tooltipOption: payload.tooltipOption,
  63266. position: payload.position,
  63267. dataIndexInside: sampleItem.dataIndexInside,
  63268. dataIndex: sampleItem.dataIndex,
  63269. seriesIndex: sampleItem.seriesIndex,
  63270. dataByCoordSys: dataByCoordSys.list
  63271. });
  63272. }
  63273. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  63274. // FIXME
  63275. // highlight status modification shoule be a stage of main process?
  63276. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  63277. var zr = api.getZr();
  63278. var highDownKey = 'axisPointerLastHighlights';
  63279. var lastHighlights = inner$e(zr)[highDownKey] || {};
  63280. var newHighlights = inner$e(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  63281. // Build hash map and remove duplicate incidentally.
  63282. each(axesInfo, function (axisInfo, key) {
  63283. var option = axisInfo.axisPointerModel.option;
  63284. option.status === 'show' && each(option.seriesDataIndices, function (batchItem) {
  63285. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  63286. newHighlights[key] = batchItem;
  63287. });
  63288. }); // Diff.
  63289. var toHighlight = [];
  63290. var toDownplay = [];
  63291. each(lastHighlights, function (batchItem, key) {
  63292. !newHighlights[key] && toDownplay.push(batchItem);
  63293. });
  63294. each(newHighlights, function (batchItem, key) {
  63295. !lastHighlights[key] && toHighlight.push(batchItem);
  63296. });
  63297. toDownplay.length && api.dispatchAction({
  63298. type: 'downplay',
  63299. escapeConnect: true,
  63300. // Not blur others when highlight in axisPointer.
  63301. notBlur: true,
  63302. batch: toDownplay
  63303. });
  63304. toHighlight.length && api.dispatchAction({
  63305. type: 'highlight',
  63306. escapeConnect: true,
  63307. // Not blur others when highlight in axisPointer.
  63308. notBlur: true,
  63309. batch: toHighlight
  63310. });
  63311. }
  63312. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  63313. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  63314. var inputAxisInfo = inputAxesInfo[i];
  63315. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  63316. return inputAxisInfo;
  63317. }
  63318. }
  63319. }
  63320. function makeMapperParam(axisInfo) {
  63321. var axisModel = axisInfo.axis.model;
  63322. var item = {};
  63323. var dim = item.axisDim = axisInfo.axis.dim;
  63324. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  63325. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  63326. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  63327. return item;
  63328. }
  63329. function illegalPoint(point) {
  63330. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  63331. }
  63332. function install$s(registers) {
  63333. // CartesianAxisPointer is not supposed to be required here. But consider
  63334. // echarts.simple.js and online build tooltip, which only require gridSimple,
  63335. // CartesianAxisPointer should be able to required somewhere.
  63336. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  63337. registers.registerComponentModel(AxisPointerModel);
  63338. registers.registerComponentView(AxisPointerView);
  63339. registers.registerPreprocessor(function (option) {
  63340. // Always has a global axisPointerModel for default setting.
  63341. if (option) {
  63342. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  63343. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  63344. // is not set, remain null/undefined, otherwise it will
  63345. // override existent link setting.
  63346. if (link && !isArray(link)) {
  63347. option.axisPointer.link = [link];
  63348. }
  63349. }
  63350. }); // This process should proformed after coordinate systems created
  63351. // and series data processed. So put it on statistic processing stage.
  63352. registers.registerProcessor(registers.PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  63353. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  63354. // allAxesInfo should be updated when setOption performed.
  63355. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  63356. }); // Broadcast to all views.
  63357. registers.registerAction({
  63358. type: 'updateAxisPointer',
  63359. event: 'updateAxisPointer',
  63360. update: ':updateAxisPointer'
  63361. }, axisTrigger);
  63362. }
  63363. function install$t(registers) {
  63364. use(install$5);
  63365. use(install$s);
  63366. }
  63367. var PolarAxisPointer =
  63368. /** @class */
  63369. function (_super) {
  63370. __extends(PolarAxisPointer, _super);
  63371. function PolarAxisPointer() {
  63372. return _super !== null && _super.apply(this, arguments) || this;
  63373. }
  63374. /**
  63375. * @override
  63376. */
  63377. PolarAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  63378. var axis = axisModel.axis;
  63379. if (axis.dim === 'angle') {
  63380. this.animationThreshold = Math.PI / 18;
  63381. }
  63382. var polar = axis.polar;
  63383. var otherAxis = polar.getOtherAxis(axis);
  63384. var otherExtent = otherAxis.getExtent();
  63385. var coordValue = axis.dataToCoord(value);
  63386. var axisPointerType = axisPointerModel.get('type');
  63387. if (axisPointerType && axisPointerType !== 'none') {
  63388. var elStyle = buildElStyle(axisPointerModel);
  63389. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, polar, coordValue, otherExtent);
  63390. pointerOption.style = elStyle;
  63391. elOption.graphicKey = pointerOption.type;
  63392. elOption.pointer = pointerOption;
  63393. }
  63394. var labelMargin = axisPointerModel.get(['label', 'margin']);
  63395. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  63396. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  63397. };
  63398. return PolarAxisPointer;
  63399. }(BaseAxisPointer);
  63400. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  63401. var axis = axisModel.axis;
  63402. var coord = axis.dataToCoord(value);
  63403. var axisAngle = polar.getAngleAxis().getExtent()[0];
  63404. axisAngle = axisAngle / 180 * Math.PI;
  63405. var radiusExtent = polar.getRadiusAxis().getExtent();
  63406. var position;
  63407. var align;
  63408. var verticalAlign;
  63409. if (axis.dim === 'radius') {
  63410. var transform = create$1();
  63411. rotate(transform, transform, axisAngle);
  63412. translate(transform, transform, [polar.cx, polar.cy]);
  63413. position = applyTransform$1([coord, -labelMargin], transform);
  63414. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0; // @ts-ignore
  63415. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  63416. align = labelLayout.textAlign;
  63417. verticalAlign = labelLayout.textVerticalAlign;
  63418. } else {
  63419. // angle axis
  63420. var r = radiusExtent[1];
  63421. position = polar.coordToPoint([r + labelMargin, coord]);
  63422. var cx = polar.cx;
  63423. var cy = polar.cy;
  63424. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  63425. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  63426. }
  63427. return {
  63428. position: position,
  63429. align: align,
  63430. verticalAlign: verticalAlign
  63431. };
  63432. }
  63433. var pointerShapeBuilder$1 = {
  63434. line: function (axis, polar, coordValue, otherExtent) {
  63435. return axis.dim === 'angle' ? {
  63436. type: 'Line',
  63437. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  63438. } : {
  63439. type: 'Circle',
  63440. shape: {
  63441. cx: polar.cx,
  63442. cy: polar.cy,
  63443. r: coordValue
  63444. }
  63445. };
  63446. },
  63447. shadow: function (axis, polar, coordValue, otherExtent) {
  63448. var bandWidth = Math.max(1, axis.getBandWidth());
  63449. var radian = Math.PI / 180;
  63450. return axis.dim === 'angle' ? {
  63451. type: 'Sector',
  63452. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  63453. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  63454. } : {
  63455. type: 'Sector',
  63456. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  63457. };
  63458. }
  63459. };
  63460. var PolarModel =
  63461. /** @class */
  63462. function (_super) {
  63463. __extends(PolarModel, _super);
  63464. function PolarModel() {
  63465. var _this = _super !== null && _super.apply(this, arguments) || this;
  63466. _this.type = PolarModel.type;
  63467. return _this;
  63468. }
  63469. PolarModel.prototype.findAxisModel = function (axisType) {
  63470. var foundAxisModel;
  63471. var ecModel = this.ecModel;
  63472. ecModel.eachComponent(axisType, function (axisModel) {
  63473. if (axisModel.getCoordSysModel() === this) {
  63474. foundAxisModel = axisModel;
  63475. }
  63476. }, this);
  63477. return foundAxisModel;
  63478. };
  63479. PolarModel.type = 'polar';
  63480. PolarModel.dependencies = ['radiusAxis', 'angleAxis'];
  63481. PolarModel.defaultOption = {
  63482. zlevel: 0,
  63483. z: 0,
  63484. center: ['50%', '50%'],
  63485. radius: '80%'
  63486. };
  63487. return PolarModel;
  63488. }(ComponentModel);
  63489. var PolarAxisModel =
  63490. /** @class */
  63491. function (_super) {
  63492. __extends(PolarAxisModel, _super);
  63493. function PolarAxisModel() {
  63494. return _super !== null && _super.apply(this, arguments) || this;
  63495. }
  63496. PolarAxisModel.prototype.getCoordSysModel = function () {
  63497. return this.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  63498. };
  63499. PolarAxisModel.type = 'polarAxis';
  63500. return PolarAxisModel;
  63501. }(ComponentModel);
  63502. mixin(PolarAxisModel, AxisModelCommonMixin);
  63503. var AngleAxisModel =
  63504. /** @class */
  63505. function (_super) {
  63506. __extends(AngleAxisModel, _super);
  63507. function AngleAxisModel() {
  63508. var _this = _super !== null && _super.apply(this, arguments) || this;
  63509. _this.type = AngleAxisModel.type;
  63510. return _this;
  63511. }
  63512. AngleAxisModel.type = 'angleAxis';
  63513. return AngleAxisModel;
  63514. }(PolarAxisModel);
  63515. var RadiusAxisModel =
  63516. /** @class */
  63517. function (_super) {
  63518. __extends(RadiusAxisModel, _super);
  63519. function RadiusAxisModel() {
  63520. var _this = _super !== null && _super.apply(this, arguments) || this;
  63521. _this.type = RadiusAxisModel.type;
  63522. return _this;
  63523. }
  63524. RadiusAxisModel.type = 'radiusAxis';
  63525. return RadiusAxisModel;
  63526. }(PolarAxisModel);
  63527. var RadiusAxis =
  63528. /** @class */
  63529. function (_super) {
  63530. __extends(RadiusAxis, _super);
  63531. function RadiusAxis(scale, radiusExtent) {
  63532. return _super.call(this, 'radius', scale, radiusExtent) || this;
  63533. }
  63534. RadiusAxis.prototype.pointToData = function (point, clamp) {
  63535. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  63536. };
  63537. return RadiusAxis;
  63538. }(Axis);
  63539. RadiusAxis.prototype.dataToRadius = Axis.prototype.dataToCoord;
  63540. RadiusAxis.prototype.radiusToData = Axis.prototype.coordToData;
  63541. var inner$f = makeInner();
  63542. var AngleAxis =
  63543. /** @class */
  63544. function (_super) {
  63545. __extends(AngleAxis, _super);
  63546. function AngleAxis(scale, angleExtent) {
  63547. return _super.call(this, 'angle', scale, angleExtent || [0, 360]) || this;
  63548. }
  63549. AngleAxis.prototype.pointToData = function (point, clamp) {
  63550. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  63551. };
  63552. /**
  63553. * Only be called in category axis.
  63554. * Angle axis uses text height to decide interval
  63555. *
  63556. * @override
  63557. * @return {number} Auto interval for cateogry axis tick and label
  63558. */
  63559. AngleAxis.prototype.calculateCategoryInterval = function () {
  63560. var axis = this;
  63561. var labelModel = axis.getLabelModel();
  63562. var ordinalScale = axis.scale;
  63563. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  63564. // avoid generating a long array by `getTicks`
  63565. // in large category data case.
  63566. var tickCount = ordinalScale.count();
  63567. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  63568. return 0;
  63569. }
  63570. var tickValue = ordinalExtent[0];
  63571. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  63572. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  63573. // and each distance from axis line yet.
  63574. var rect = getBoundingRect(tickValue == null ? '' : tickValue + '', labelModel.getFont(), 'center', 'top');
  63575. var maxH = Math.max(rect.height, 7);
  63576. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  63577. isNaN(dh) && (dh = Infinity);
  63578. var interval = Math.max(0, Math.floor(dh));
  63579. var cache = inner$f(axis.model);
  63580. var lastAutoInterval = cache.lastAutoInterval;
  63581. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  63582. // otherwise the calculated interval might jitter when the zoom
  63583. // window size is close to the interval-changing size.
  63584. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  63585. // point is not the same when zooming in or zooming out.
  63586. && lastAutoInterval > interval) {
  63587. interval = lastAutoInterval;
  63588. } // Only update cache if cache not used, otherwise the
  63589. // changing of interval is too insensitive.
  63590. else {
  63591. cache.lastTickCount = tickCount;
  63592. cache.lastAutoInterval = interval;
  63593. }
  63594. return interval;
  63595. };
  63596. return AngleAxis;
  63597. }(Axis);
  63598. AngleAxis.prototype.dataToAngle = Axis.prototype.dataToCoord;
  63599. AngleAxis.prototype.angleToData = Axis.prototype.coordToData;
  63600. var Polar =
  63601. /** @class */
  63602. function () {
  63603. function Polar(name) {
  63604. this.dimensions = ['radius', 'angle'];
  63605. this.type = 'polar';
  63606. /**
  63607. * x of polar center
  63608. */
  63609. this.cx = 0;
  63610. /**
  63611. * y of polar center
  63612. */
  63613. this.cy = 0;
  63614. this._radiusAxis = new RadiusAxis();
  63615. this._angleAxis = new AngleAxis();
  63616. this.axisPointerEnabled = true;
  63617. this.name = name || '';
  63618. this._radiusAxis.polar = this._angleAxis.polar = this;
  63619. }
  63620. /**
  63621. * If contain coord
  63622. */
  63623. Polar.prototype.containPoint = function (point) {
  63624. var coord = this.pointToCoord(point);
  63625. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  63626. };
  63627. /**
  63628. * If contain data
  63629. */
  63630. Polar.prototype.containData = function (data) {
  63631. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  63632. };
  63633. Polar.prototype.getAxis = function (dim) {
  63634. var key = '_' + dim + 'Axis';
  63635. return this[key];
  63636. };
  63637. Polar.prototype.getAxes = function () {
  63638. return [this._radiusAxis, this._angleAxis];
  63639. };
  63640. /**
  63641. * Get axes by type of scale
  63642. */
  63643. Polar.prototype.getAxesByScale = function (scaleType) {
  63644. var axes = [];
  63645. var angleAxis = this._angleAxis;
  63646. var radiusAxis = this._radiusAxis;
  63647. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  63648. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  63649. return axes;
  63650. };
  63651. Polar.prototype.getAngleAxis = function () {
  63652. return this._angleAxis;
  63653. };
  63654. Polar.prototype.getRadiusAxis = function () {
  63655. return this._radiusAxis;
  63656. };
  63657. Polar.prototype.getOtherAxis = function (axis) {
  63658. var angleAxis = this._angleAxis;
  63659. return axis === angleAxis ? this._radiusAxis : angleAxis;
  63660. };
  63661. /**
  63662. * Base axis will be used on stacking.
  63663. *
  63664. */
  63665. Polar.prototype.getBaseAxis = function () {
  63666. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  63667. };
  63668. Polar.prototype.getTooltipAxes = function (dim) {
  63669. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  63670. return {
  63671. baseAxes: [baseAxis],
  63672. otherAxes: [this.getOtherAxis(baseAxis)]
  63673. };
  63674. };
  63675. /**
  63676. * Convert a single data item to (x, y) point.
  63677. * Parameter data is an array which the first element is radius and the second is angle
  63678. */
  63679. Polar.prototype.dataToPoint = function (data, clamp) {
  63680. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  63681. };
  63682. /**
  63683. * Convert a (x, y) point to data
  63684. */
  63685. Polar.prototype.pointToData = function (point, clamp) {
  63686. var coord = this.pointToCoord(point);
  63687. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  63688. };
  63689. /**
  63690. * Convert a (x, y) point to (radius, angle) coord
  63691. */
  63692. Polar.prototype.pointToCoord = function (point) {
  63693. var dx = point[0] - this.cx;
  63694. var dy = point[1] - this.cy;
  63695. var angleAxis = this.getAngleAxis();
  63696. var extent = angleAxis.getExtent();
  63697. var minAngle = Math.min(extent[0], extent[1]);
  63698. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  63699. // FIXME
  63700. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  63701. var radius = Math.sqrt(dx * dx + dy * dy);
  63702. dx /= radius;
  63703. dy /= radius;
  63704. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  63705. var dir = radian < minAngle ? 1 : -1;
  63706. while (radian < minAngle || radian > maxAngle) {
  63707. radian += dir * 360;
  63708. }
  63709. return [radius, radian];
  63710. };
  63711. /**
  63712. * Convert a (radius, angle) coord to (x, y) point
  63713. */
  63714. Polar.prototype.coordToPoint = function (coord) {
  63715. var radius = coord[0];
  63716. var radian = coord[1] / 180 * Math.PI;
  63717. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  63718. var y = -Math.sin(radian) * radius + this.cy;
  63719. return [x, y];
  63720. };
  63721. /**
  63722. * Get ring area of cartesian.
  63723. * Area will have a contain function to determine if a point is in the coordinate system.
  63724. */
  63725. Polar.prototype.getArea = function () {
  63726. var angleAxis = this.getAngleAxis();
  63727. var radiusAxis = this.getRadiusAxis();
  63728. var radiusExtent = radiusAxis.getExtent().slice();
  63729. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  63730. var angleExtent = angleAxis.getExtent();
  63731. var RADIAN = Math.PI / 180;
  63732. return {
  63733. cx: this.cx,
  63734. cy: this.cy,
  63735. r0: radiusExtent[0],
  63736. r: radiusExtent[1],
  63737. startAngle: -angleExtent[0] * RADIAN,
  63738. endAngle: -angleExtent[1] * RADIAN,
  63739. clockwise: angleAxis.inverse,
  63740. contain: function (x, y) {
  63741. // It's a ring shape.
  63742. // Start angle and end angle don't matter
  63743. var dx = x - this.cx;
  63744. var dy = y - this.cy;
  63745. var d2 = dx * dx + dy * dy;
  63746. var r = this.r;
  63747. var r0 = this.r0;
  63748. return d2 <= r * r && d2 >= r0 * r0;
  63749. }
  63750. };
  63751. };
  63752. Polar.prototype.convertToPixel = function (ecModel, finder, value) {
  63753. var coordSys = getCoordSys$2(finder);
  63754. return coordSys === this ? this.dataToPoint(value) : null;
  63755. };
  63756. Polar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  63757. var coordSys = getCoordSys$2(finder);
  63758. return coordSys === this ? this.pointToData(pixel) : null;
  63759. };
  63760. return Polar;
  63761. }();
  63762. function getCoordSys$2(finder) {
  63763. var seriesModel = finder.seriesModel;
  63764. var polarModel = finder.polarModel;
  63765. return polarModel && polarModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  63766. }
  63767. /**
  63768. * Resize method bound to the polar
  63769. */
  63770. function resizePolar(polar, polarModel, api) {
  63771. var center = polarModel.get('center');
  63772. var width = api.getWidth();
  63773. var height = api.getHeight();
  63774. polar.cx = parsePercent$1(center[0], width);
  63775. polar.cy = parsePercent$1(center[1], height);
  63776. var radiusAxis = polar.getRadiusAxis();
  63777. var size = Math.min(width, height) / 2;
  63778. var radius = polarModel.get('radius');
  63779. if (radius == null) {
  63780. radius = [0, '100%'];
  63781. } else if (!isArray(radius)) {
  63782. // r0 = 0
  63783. radius = [0, radius];
  63784. }
  63785. var parsedRadius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  63786. radiusAxis.inverse ? radiusAxis.setExtent(parsedRadius[1], parsedRadius[0]) : radiusAxis.setExtent(parsedRadius[0], parsedRadius[1]);
  63787. }
  63788. /**
  63789. * Update polar
  63790. */
  63791. function updatePolarScale(ecModel, api) {
  63792. var polar = this;
  63793. var angleAxis = polar.getAngleAxis();
  63794. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  63795. angleAxis.scale.setExtent(Infinity, -Infinity);
  63796. radiusAxis.scale.setExtent(Infinity, -Infinity);
  63797. ecModel.eachSeries(function (seriesModel) {
  63798. if (seriesModel.coordinateSystem === polar) {
  63799. var data_1 = seriesModel.getData();
  63800. each(getDataDimensionsOnAxis(data_1, 'radius'), function (dim) {
  63801. radiusAxis.scale.unionExtentFromData(data_1, dim);
  63802. });
  63803. each(getDataDimensionsOnAxis(data_1, 'angle'), function (dim) {
  63804. angleAxis.scale.unionExtentFromData(data_1, dim);
  63805. });
  63806. }
  63807. });
  63808. niceScaleExtent(angleAxis.scale, angleAxis.model);
  63809. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  63810. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  63811. var extent = angleAxis.getExtent();
  63812. var diff = 360 / angleAxis.scale.count();
  63813. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  63814. angleAxis.setExtent(extent[0], extent[1]);
  63815. }
  63816. }
  63817. function isAngleAxisModel(axisModel) {
  63818. return axisModel.mainType === 'angleAxis';
  63819. }
  63820. /**
  63821. * Set common axis properties
  63822. */
  63823. function setAxis(axis, axisModel) {
  63824. axis.type = axisModel.get('type');
  63825. axis.scale = createScaleByModel(axisModel);
  63826. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  63827. axis.inverse = axisModel.get('inverse');
  63828. if (isAngleAxisModel(axisModel)) {
  63829. axis.inverse = axis.inverse !== axisModel.get('clockwise');
  63830. var startAngle = axisModel.get('startAngle');
  63831. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  63832. } // Inject axis instance
  63833. axisModel.axis = axis;
  63834. axis.model = axisModel;
  63835. }
  63836. var polarCreator = {
  63837. dimensions: Polar.prototype.dimensions,
  63838. create: function (ecModel, api) {
  63839. var polarList = [];
  63840. ecModel.eachComponent('polar', function (polarModel, idx) {
  63841. var polar = new Polar(idx + ''); // Inject resize and update method
  63842. polar.update = updatePolarScale;
  63843. var radiusAxis = polar.getRadiusAxis();
  63844. var angleAxis = polar.getAngleAxis();
  63845. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  63846. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  63847. setAxis(radiusAxis, radiusAxisModel);
  63848. setAxis(angleAxis, angleAxisModel);
  63849. resizePolar(polar, polarModel, api);
  63850. polarList.push(polar);
  63851. polarModel.coordinateSystem = polar;
  63852. polar.model = polarModel;
  63853. }); // Inject coordinateSystem to series
  63854. ecModel.eachSeries(function (seriesModel) {
  63855. if (seriesModel.get('coordinateSystem') === 'polar') {
  63856. var polarModel = seriesModel.getReferringComponents('polar', SINGLE_REFERRING).models[0];
  63857. if ("development" !== 'production') {
  63858. if (!polarModel) {
  63859. throw new Error('Polar "' + retrieve(seriesModel.get('polarIndex'), seriesModel.get('polarId'), 0) + '" not found');
  63860. }
  63861. }
  63862. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  63863. }
  63864. });
  63865. return polarList;
  63866. }
  63867. };
  63868. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  63869. function getAxisLineShape(polar, rExtent, angle) {
  63870. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  63871. var start = polar.coordToPoint([rExtent[0], angle]);
  63872. var end = polar.coordToPoint([rExtent[1], angle]);
  63873. return {
  63874. x1: start[0],
  63875. y1: start[1],
  63876. x2: end[0],
  63877. y2: end[1]
  63878. };
  63879. }
  63880. function getRadiusIdx(polar) {
  63881. var radiusAxis = polar.getRadiusAxis();
  63882. return radiusAxis.inverse ? 0 : 1;
  63883. } // Remove the last tick which will overlap the first tick
  63884. function fixAngleOverlap(list) {
  63885. var firstItem = list[0];
  63886. var lastItem = list[list.length - 1];
  63887. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  63888. list.pop();
  63889. }
  63890. }
  63891. var AngleAxisView =
  63892. /** @class */
  63893. function (_super) {
  63894. __extends(AngleAxisView, _super);
  63895. function AngleAxisView() {
  63896. var _this = _super !== null && _super.apply(this, arguments) || this;
  63897. _this.type = AngleAxisView.type;
  63898. _this.axisPointerClass = 'PolarAxisPointer';
  63899. return _this;
  63900. }
  63901. AngleAxisView.prototype.render = function (angleAxisModel, ecModel) {
  63902. this.group.removeAll();
  63903. if (!angleAxisModel.get('show')) {
  63904. return;
  63905. }
  63906. var angleAxis = angleAxisModel.axis;
  63907. var polar = angleAxis.polar;
  63908. var radiusExtent = polar.getRadiusAxis().getExtent();
  63909. var ticksAngles = angleAxis.getTicksCoords();
  63910. var minorTickAngles = angleAxis.getMinorTicksCoords();
  63911. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  63912. labelItem = clone(labelItem);
  63913. var scale = angleAxis.scale;
  63914. var tickValue = scale.type === 'ordinal' ? scale.getRawOrdinalNumber(labelItem.tickValue) : labelItem.tickValue;
  63915. labelItem.coord = angleAxis.dataToCoord(tickValue);
  63916. return labelItem;
  63917. });
  63918. fixAngleOverlap(labels);
  63919. fixAngleOverlap(ticksAngles);
  63920. each(elementList$1, function (name) {
  63921. if (angleAxisModel.get([name, 'show']) && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  63922. angelAxisElementsBuilders[name](this.group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  63923. }
  63924. }, this);
  63925. };
  63926. AngleAxisView.type = 'angleAxis';
  63927. return AngleAxisView;
  63928. }(AxisView);
  63929. var angelAxisElementsBuilders = {
  63930. axisLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  63931. var lineStyleModel = angleAxisModel.getModel(['axisLine', 'lineStyle']); // extent id of the axis radius (r0 and r)
  63932. var rId = getRadiusIdx(polar);
  63933. var r0Id = rId ? 0 : 1;
  63934. var shape;
  63935. if (radiusExtent[r0Id] === 0) {
  63936. shape = new Circle({
  63937. shape: {
  63938. cx: polar.cx,
  63939. cy: polar.cy,
  63940. r: radiusExtent[rId]
  63941. },
  63942. style: lineStyleModel.getLineStyle(),
  63943. z2: 1,
  63944. silent: true
  63945. });
  63946. } else {
  63947. shape = new Ring({
  63948. shape: {
  63949. cx: polar.cx,
  63950. cy: polar.cy,
  63951. r: radiusExtent[rId],
  63952. r0: radiusExtent[r0Id]
  63953. },
  63954. style: lineStyleModel.getLineStyle(),
  63955. z2: 1,
  63956. silent: true
  63957. });
  63958. }
  63959. shape.style.fill = null;
  63960. group.add(shape);
  63961. },
  63962. axisTick: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  63963. var tickModel = angleAxisModel.getModel('axisTick');
  63964. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  63965. var radius = radiusExtent[getRadiusIdx(polar)];
  63966. var lines = map(ticksAngles, function (tickAngleItem) {
  63967. return new Line({
  63968. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  63969. });
  63970. });
  63971. group.add(mergePath$1(lines, {
  63972. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  63973. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  63974. })
  63975. }));
  63976. },
  63977. minorTick: function (group, angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  63978. if (!minorTickAngles.length) {
  63979. return;
  63980. }
  63981. var tickModel = angleAxisModel.getModel('axisTick');
  63982. var minorTickModel = angleAxisModel.getModel('minorTick');
  63983. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  63984. var radius = radiusExtent[getRadiusIdx(polar)];
  63985. var lines = [];
  63986. for (var i = 0; i < minorTickAngles.length; i++) {
  63987. for (var k = 0; k < minorTickAngles[i].length; k++) {
  63988. lines.push(new Line({
  63989. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  63990. }));
  63991. }
  63992. }
  63993. group.add(mergePath$1(lines, {
  63994. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  63995. stroke: angleAxisModel.get(['axisLine', 'lineStyle', 'color'])
  63996. }))
  63997. }));
  63998. },
  63999. axisLabel: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  64000. var rawCategoryData = angleAxisModel.getCategories(true);
  64001. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  64002. var labelMargin = commonLabelModel.get('margin');
  64003. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  64004. each(labels, function (labelItem, idx) {
  64005. var labelModel = commonLabelModel;
  64006. var tickValue = labelItem.tickValue;
  64007. var r = radiusExtent[getRadiusIdx(polar)];
  64008. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  64009. var cx = polar.cx;
  64010. var cy = polar.cy;
  64011. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  64012. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  64013. if (rawCategoryData && rawCategoryData[tickValue]) {
  64014. var rawCategoryItem = rawCategoryData[tickValue];
  64015. if (isObject(rawCategoryItem) && rawCategoryItem.textStyle) {
  64016. labelModel = new Model(rawCategoryItem.textStyle, commonLabelModel, commonLabelModel.ecModel);
  64017. }
  64018. }
  64019. var textEl = new ZRText({
  64020. silent: AxisBuilder.isLabelSilent(angleAxisModel),
  64021. style: createTextStyle(labelModel, {
  64022. x: p[0],
  64023. y: p[1],
  64024. fill: labelModel.getTextColor() || angleAxisModel.get(['axisLine', 'lineStyle', 'color']),
  64025. text: labelItem.formattedLabel,
  64026. align: labelTextAlign,
  64027. verticalAlign: labelTextVerticalAlign
  64028. })
  64029. });
  64030. group.add(textEl); // Pack data for mouse event
  64031. if (triggerEvent) {
  64032. var eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  64033. eventData.targetType = 'axisLabel';
  64034. eventData.value = labelItem.rawLabel;
  64035. getECData(textEl).eventData = eventData;
  64036. }
  64037. }, this);
  64038. },
  64039. splitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  64040. var splitLineModel = angleAxisModel.getModel('splitLine');
  64041. var lineStyleModel = splitLineModel.getModel('lineStyle');
  64042. var lineColors = lineStyleModel.get('color');
  64043. var lineCount = 0;
  64044. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  64045. var splitLines = [];
  64046. for (var i = 0; i < ticksAngles.length; i++) {
  64047. var colorIndex = lineCount++ % lineColors.length;
  64048. splitLines[colorIndex] = splitLines[colorIndex] || [];
  64049. splitLines[colorIndex].push(new Line({
  64050. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  64051. }));
  64052. } // Simple optimization
  64053. // Batching the lines if color are the same
  64054. for (var i = 0; i < splitLines.length; i++) {
  64055. group.add(mergePath$1(splitLines[i], {
  64056. style: defaults({
  64057. stroke: lineColors[i % lineColors.length]
  64058. }, lineStyleModel.getLineStyle()),
  64059. silent: true,
  64060. z: angleAxisModel.get('z')
  64061. }));
  64062. }
  64063. },
  64064. minorSplitLine: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  64065. if (!minorTickAngles.length) {
  64066. return;
  64067. }
  64068. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  64069. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  64070. var lines = [];
  64071. for (var i = 0; i < minorTickAngles.length; i++) {
  64072. for (var k = 0; k < minorTickAngles[i].length; k++) {
  64073. lines.push(new Line({
  64074. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  64075. }));
  64076. }
  64077. }
  64078. group.add(mergePath$1(lines, {
  64079. style: lineStyleModel.getLineStyle(),
  64080. silent: true,
  64081. z: angleAxisModel.get('z')
  64082. }));
  64083. },
  64084. splitArea: function (group, angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  64085. if (!ticksAngles.length) {
  64086. return;
  64087. }
  64088. var splitAreaModel = angleAxisModel.getModel('splitArea');
  64089. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  64090. var areaColors = areaStyleModel.get('color');
  64091. var lineCount = 0;
  64092. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  64093. var splitAreas = [];
  64094. var RADIAN = Math.PI / 180;
  64095. var prevAngle = -ticksAngles[0].coord * RADIAN;
  64096. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  64097. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  64098. var clockwise = angleAxisModel.get('clockwise');
  64099. for (var i = 1, len = ticksAngles.length; i <= len; i++) {
  64100. var coord = i === len ? ticksAngles[0].coord : ticksAngles[i].coord;
  64101. var colorIndex = lineCount++ % areaColors.length;
  64102. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  64103. splitAreas[colorIndex].push(new Sector({
  64104. shape: {
  64105. cx: polar.cx,
  64106. cy: polar.cy,
  64107. r0: r0,
  64108. r: r1,
  64109. startAngle: prevAngle,
  64110. endAngle: -coord * RADIAN,
  64111. clockwise: clockwise
  64112. },
  64113. silent: true
  64114. }));
  64115. prevAngle = -coord * RADIAN;
  64116. } // Simple optimization
  64117. // Batching the lines if color are the same
  64118. for (var i = 0; i < splitAreas.length; i++) {
  64119. group.add(mergePath$1(splitAreas[i], {
  64120. style: defaults({
  64121. fill: areaColors[i % areaColors.length]
  64122. }, areaStyleModel.getAreaStyle()),
  64123. silent: true
  64124. }));
  64125. }
  64126. }
  64127. };
  64128. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  64129. var selfBuilderAttrs$1 = ['splitLine', 'splitArea', 'minorSplitLine'];
  64130. var RadiusAxisView =
  64131. /** @class */
  64132. function (_super) {
  64133. __extends(RadiusAxisView, _super);
  64134. function RadiusAxisView() {
  64135. var _this = _super !== null && _super.apply(this, arguments) || this;
  64136. _this.type = RadiusAxisView.type;
  64137. _this.axisPointerClass = 'PolarAxisPointer';
  64138. return _this;
  64139. }
  64140. RadiusAxisView.prototype.render = function (radiusAxisModel, ecModel) {
  64141. this.group.removeAll();
  64142. if (!radiusAxisModel.get('show')) {
  64143. return;
  64144. }
  64145. var oldAxisGroup = this._axisGroup;
  64146. var newAxisGroup = this._axisGroup = new Group();
  64147. this.group.add(newAxisGroup);
  64148. var radiusAxis = radiusAxisModel.axis;
  64149. var polar = radiusAxis.polar;
  64150. var angleAxis = polar.getAngleAxis();
  64151. var ticksCoords = radiusAxis.getTicksCoords();
  64152. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  64153. var axisAngle = angleAxis.getExtent()[0];
  64154. var radiusExtent = radiusAxis.getExtent();
  64155. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  64156. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  64157. each(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  64158. newAxisGroup.add(axisBuilder.getGroup());
  64159. groupTransition(oldAxisGroup, newAxisGroup, radiusAxisModel);
  64160. each(selfBuilderAttrs$1, function (name) {
  64161. if (radiusAxisModel.get([name, 'show']) && !radiusAxis.scale.isBlank()) {
  64162. axisElementBuilders$1[name](this.group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  64163. }
  64164. }, this);
  64165. };
  64166. RadiusAxisView.type = 'radiusAxis';
  64167. return RadiusAxisView;
  64168. }(AxisView);
  64169. var axisElementBuilders$1 = {
  64170. splitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  64171. var splitLineModel = radiusAxisModel.getModel('splitLine');
  64172. var lineStyleModel = splitLineModel.getModel('lineStyle');
  64173. var lineColors = lineStyleModel.get('color');
  64174. var lineCount = 0;
  64175. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  64176. var splitLines = [];
  64177. for (var i = 0; i < ticksCoords.length; i++) {
  64178. var colorIndex = lineCount++ % lineColors.length;
  64179. splitLines[colorIndex] = splitLines[colorIndex] || [];
  64180. splitLines[colorIndex].push(new Circle({
  64181. shape: {
  64182. cx: polar.cx,
  64183. cy: polar.cy,
  64184. r: ticksCoords[i].coord
  64185. }
  64186. }));
  64187. } // Simple optimization
  64188. // Batching the lines if color are the same
  64189. for (var i = 0; i < splitLines.length; i++) {
  64190. group.add(mergePath$1(splitLines[i], {
  64191. style: defaults({
  64192. stroke: lineColors[i % lineColors.length],
  64193. fill: null
  64194. }, lineStyleModel.getLineStyle()),
  64195. silent: true
  64196. }));
  64197. }
  64198. },
  64199. minorSplitLine: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  64200. if (!minorTicksCoords.length) {
  64201. return;
  64202. }
  64203. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  64204. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  64205. var lines = [];
  64206. for (var i = 0; i < minorTicksCoords.length; i++) {
  64207. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  64208. lines.push(new Circle({
  64209. shape: {
  64210. cx: polar.cx,
  64211. cy: polar.cy,
  64212. r: minorTicksCoords[i][k].coord
  64213. }
  64214. }));
  64215. }
  64216. }
  64217. group.add(mergePath$1(lines, {
  64218. style: defaults({
  64219. fill: null
  64220. }, lineStyleModel.getLineStyle()),
  64221. silent: true
  64222. }));
  64223. },
  64224. splitArea: function (group, radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  64225. if (!ticksCoords.length) {
  64226. return;
  64227. }
  64228. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  64229. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  64230. var areaColors = areaStyleModel.get('color');
  64231. var lineCount = 0;
  64232. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  64233. var splitAreas = [];
  64234. var prevRadius = ticksCoords[0].coord;
  64235. for (var i = 1; i < ticksCoords.length; i++) {
  64236. var colorIndex = lineCount++ % areaColors.length;
  64237. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  64238. splitAreas[colorIndex].push(new Sector({
  64239. shape: {
  64240. cx: polar.cx,
  64241. cy: polar.cy,
  64242. r0: prevRadius,
  64243. r: ticksCoords[i].coord,
  64244. startAngle: 0,
  64245. endAngle: Math.PI * 2
  64246. },
  64247. silent: true
  64248. }));
  64249. prevRadius = ticksCoords[i].coord;
  64250. } // Simple optimization
  64251. // Batching the lines if color are the same
  64252. for (var i = 0; i < splitAreas.length; i++) {
  64253. group.add(mergePath$1(splitAreas[i], {
  64254. style: defaults({
  64255. fill: areaColors[i % areaColors.length]
  64256. }, areaStyleModel.getAreaStyle()),
  64257. silent: true
  64258. }));
  64259. }
  64260. }
  64261. };
  64262. /**
  64263. * @inner
  64264. */
  64265. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  64266. return {
  64267. position: [polar.cx, polar.cy],
  64268. rotation: axisAngle / 180 * Math.PI,
  64269. labelDirection: -1,
  64270. tickDirection: -1,
  64271. nameDirection: 1,
  64272. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  64273. // Over splitLine and splitArea
  64274. z2: 1
  64275. };
  64276. }
  64277. function getSeriesStackId$1(seriesModel) {
  64278. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  64279. }
  64280. function getAxisKey$1(polar, axis) {
  64281. return axis.dim + polar.model.componentIndex;
  64282. }
  64283. function barLayoutPolar(seriesType, ecModel, api) {
  64284. var lastStackCoords = {};
  64285. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  64286. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  64287. }));
  64288. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  64289. // Check series coordinate, do layout for polar only
  64290. if (seriesModel.coordinateSystem.type !== 'polar') {
  64291. return;
  64292. }
  64293. var data = seriesModel.getData();
  64294. var polar = seriesModel.coordinateSystem;
  64295. var baseAxis = polar.getBaseAxis();
  64296. var axisKey = getAxisKey$1(polar, baseAxis);
  64297. var stackId = getSeriesStackId$1(seriesModel);
  64298. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  64299. var columnOffset = columnLayoutInfo.offset;
  64300. var columnWidth = columnLayoutInfo.width;
  64301. var valueAxis = polar.getOtherAxis(baseAxis);
  64302. var cx = seriesModel.coordinateSystem.cx;
  64303. var cy = seriesModel.coordinateSystem.cy;
  64304. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  64305. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  64306. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  64307. var valueDim = data.mapDimension(valueAxis.dim);
  64308. var baseDim = data.mapDimension(baseAxis.dim);
  64309. var stacked = isDimensionStacked(data, valueDim
  64310. /*, baseDim*/
  64311. );
  64312. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  64313. var valueAxisStart = valueAxis.dataToCoord(0);
  64314. for (var idx = 0, len = data.count(); idx < len; idx++) {
  64315. var value = data.get(valueDim, idx);
  64316. var baseValue = data.get(baseDim, idx);
  64317. var sign = value >= 0 ? 'p' : 'n';
  64318. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  64319. // stackResultDimension directly.
  64320. // Only ordinal axis can be stacked.
  64321. if (stacked) {
  64322. if (!lastStackCoords[stackId][baseValue]) {
  64323. lastStackCoords[stackId][baseValue] = {
  64324. p: valueAxisStart,
  64325. n: valueAxisStart // Negative stack
  64326. };
  64327. } // Should also consider #4243
  64328. baseCoord = lastStackCoords[stackId][baseValue][sign];
  64329. }
  64330. var r0 = void 0;
  64331. var r = void 0;
  64332. var startAngle = void 0;
  64333. var endAngle = void 0; // radial sector
  64334. if (valueAxis.dim === 'radius') {
  64335. var radiusSpan = valueAxis.dataToCoord(value) - valueAxisStart;
  64336. var angle = baseAxis.dataToCoord(baseValue);
  64337. if (Math.abs(radiusSpan) < barMinHeight) {
  64338. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  64339. }
  64340. r0 = baseCoord;
  64341. r = baseCoord + radiusSpan;
  64342. startAngle = angle - columnOffset;
  64343. endAngle = startAngle - columnWidth;
  64344. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  64345. } // tangential sector
  64346. else {
  64347. var angleSpan = valueAxis.dataToCoord(value, clampLayout) - valueAxisStart;
  64348. var radius = baseAxis.dataToCoord(baseValue);
  64349. if (Math.abs(angleSpan) < barMinAngle) {
  64350. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  64351. }
  64352. r0 = radius + columnOffset;
  64353. r = r0 + columnWidth;
  64354. startAngle = baseCoord;
  64355. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  64356. // add a round to differentiate it from origin
  64357. // let extent = angleAxis.getExtent();
  64358. // let stackCoord = angle;
  64359. // if (stackCoord === extent[0] && value > 0) {
  64360. // stackCoord = extent[1];
  64361. // }
  64362. // else if (stackCoord === extent[1] && value < 0) {
  64363. // stackCoord = extent[0];
  64364. // }
  64365. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  64366. }
  64367. data.setItemLayout(idx, {
  64368. cx: cx,
  64369. cy: cy,
  64370. r0: r0,
  64371. r: r,
  64372. // Consider that positive angle is anti-clockwise,
  64373. // while positive radian of sector is clockwise
  64374. startAngle: -startAngle * Math.PI / 180,
  64375. endAngle: -endAngle * Math.PI / 180
  64376. });
  64377. }
  64378. });
  64379. }
  64380. /**
  64381. * Calculate bar width and offset for radial bar charts
  64382. */
  64383. function calRadialBar(barSeries) {
  64384. // Columns info on each category axis. Key is polar name
  64385. var columnsMap = {};
  64386. each(barSeries, function (seriesModel, idx) {
  64387. var data = seriesModel.getData();
  64388. var polar = seriesModel.coordinateSystem;
  64389. var baseAxis = polar.getBaseAxis();
  64390. var axisKey = getAxisKey$1(polar, baseAxis);
  64391. var axisExtent = baseAxis.getExtent();
  64392. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  64393. var columnsOnAxis = columnsMap[axisKey] || {
  64394. bandWidth: bandWidth,
  64395. remainedWidth: bandWidth,
  64396. autoWidthCount: 0,
  64397. categoryGap: '20%',
  64398. gap: '30%',
  64399. stacks: {}
  64400. };
  64401. var stacks = columnsOnAxis.stacks;
  64402. columnsMap[axisKey] = columnsOnAxis;
  64403. var stackId = getSeriesStackId$1(seriesModel);
  64404. if (!stacks[stackId]) {
  64405. columnsOnAxis.autoWidthCount++;
  64406. }
  64407. stacks[stackId] = stacks[stackId] || {
  64408. width: 0,
  64409. maxWidth: 0
  64410. };
  64411. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  64412. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  64413. var barGap = seriesModel.get('barGap');
  64414. var barCategoryGap = seriesModel.get('barCategoryGap');
  64415. if (barWidth && !stacks[stackId].width) {
  64416. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  64417. stacks[stackId].width = barWidth;
  64418. columnsOnAxis.remainedWidth -= barWidth;
  64419. }
  64420. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  64421. barGap != null && (columnsOnAxis.gap = barGap);
  64422. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  64423. });
  64424. var result = {};
  64425. each(columnsMap, function (columnsOnAxis, coordSysName) {
  64426. result[coordSysName] = {};
  64427. var stacks = columnsOnAxis.stacks;
  64428. var bandWidth = columnsOnAxis.bandWidth;
  64429. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  64430. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  64431. var remainedWidth = columnsOnAxis.remainedWidth;
  64432. var autoWidthCount = columnsOnAxis.autoWidthCount;
  64433. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64434. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  64435. each(stacks, function (column, stack) {
  64436. var maxWidth = column.maxWidth;
  64437. if (maxWidth && maxWidth < autoWidth) {
  64438. maxWidth = Math.min(maxWidth, remainedWidth);
  64439. if (column.width) {
  64440. maxWidth = Math.min(maxWidth, column.width);
  64441. }
  64442. remainedWidth -= maxWidth;
  64443. column.width = maxWidth;
  64444. autoWidthCount--;
  64445. }
  64446. }); // Recalculate width again
  64447. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  64448. autoWidth = Math.max(autoWidth, 0);
  64449. var widthSum = 0;
  64450. var lastColumn;
  64451. each(stacks, function (column, idx) {
  64452. if (!column.width) {
  64453. column.width = autoWidth;
  64454. }
  64455. lastColumn = column;
  64456. widthSum += column.width * (1 + barGapPercent);
  64457. });
  64458. if (lastColumn) {
  64459. widthSum -= lastColumn.width * barGapPercent;
  64460. }
  64461. var offset = -widthSum / 2;
  64462. each(stacks, function (column, stackId) {
  64463. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  64464. offset: offset,
  64465. width: column.width
  64466. };
  64467. offset += column.width * (1 + barGapPercent);
  64468. });
  64469. });
  64470. return result;
  64471. }
  64472. var angleAxisExtraOption = {
  64473. startAngle: 90,
  64474. clockwise: true,
  64475. splitNumber: 12,
  64476. axisLabel: {
  64477. rotate: 0
  64478. }
  64479. };
  64480. var radiusAxisExtraOption = {
  64481. splitNumber: 5
  64482. };
  64483. var PolarView =
  64484. /** @class */
  64485. function (_super) {
  64486. __extends(PolarView, _super);
  64487. function PolarView() {
  64488. var _this = _super !== null && _super.apply(this, arguments) || this;
  64489. _this.type = PolarView.type;
  64490. return _this;
  64491. }
  64492. PolarView.type = 'polar';
  64493. return PolarView;
  64494. }(ComponentView);
  64495. function install$u(registers) {
  64496. use(install$s);
  64497. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  64498. registers.registerCoordinateSystem('polar', polarCreator);
  64499. registers.registerComponentModel(PolarModel);
  64500. registers.registerComponentView(PolarView); // Model and view for angleAxis and radiusAxis
  64501. axisModelCreator(registers, 'angle', AngleAxisModel, angleAxisExtraOption);
  64502. axisModelCreator(registers, 'radius', RadiusAxisModel, radiusAxisExtraOption);
  64503. registers.registerComponentView(AngleAxisView);
  64504. registers.registerComponentView(RadiusAxisView);
  64505. registers.registerLayout(curry(barLayoutPolar, 'bar'));
  64506. }
  64507. function layout$2(axisModel, opt) {
  64508. opt = opt || {};
  64509. var single = axisModel.coordinateSystem;
  64510. var axis = axisModel.axis;
  64511. var layout = {};
  64512. var axisPosition = axis.position;
  64513. var orient = axis.orient;
  64514. var rect = single.getRect();
  64515. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  64516. var positionMap = {
  64517. horizontal: {
  64518. top: rectBound[2],
  64519. bottom: rectBound[3]
  64520. },
  64521. vertical: {
  64522. left: rectBound[0],
  64523. right: rectBound[1]
  64524. }
  64525. };
  64526. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  64527. var r = {
  64528. horizontal: 0,
  64529. vertical: 1
  64530. };
  64531. layout.rotation = Math.PI / 2 * r[orient];
  64532. var directionMap = {
  64533. top: -1,
  64534. bottom: 1,
  64535. right: 1,
  64536. left: -1
  64537. };
  64538. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  64539. if (axisModel.get(['axisTick', 'inside'])) {
  64540. layout.tickDirection = -layout.tickDirection;
  64541. }
  64542. if (retrieve(opt.labelInside, axisModel.get(['axisLabel', 'inside']))) {
  64543. layout.labelDirection = -layout.labelDirection;
  64544. }
  64545. var labelRotation = opt.rotate;
  64546. labelRotation == null && (labelRotation = axisModel.get(['axisLabel', 'rotate']));
  64547. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  64548. layout.z2 = 1;
  64549. return layout;
  64550. }
  64551. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  64552. var selfBuilderAttrs$2 = ['splitArea', 'splitLine'];
  64553. var SingleAxisView =
  64554. /** @class */
  64555. function (_super) {
  64556. __extends(SingleAxisView, _super);
  64557. function SingleAxisView() {
  64558. var _this = _super !== null && _super.apply(this, arguments) || this;
  64559. _this.type = SingleAxisView.type;
  64560. _this.axisPointerClass = 'SingleAxisPointer';
  64561. return _this;
  64562. }
  64563. SingleAxisView.prototype.render = function (axisModel, ecModel, api, payload) {
  64564. var group = this.group;
  64565. group.removeAll();
  64566. var oldAxisGroup = this._axisGroup;
  64567. this._axisGroup = new Group();
  64568. var layout = layout$2(axisModel);
  64569. var axisBuilder = new AxisBuilder(axisModel, layout);
  64570. each(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  64571. group.add(this._axisGroup);
  64572. group.add(axisBuilder.getGroup());
  64573. each(selfBuilderAttrs$2, function (name) {
  64574. if (axisModel.get([name, 'show'])) {
  64575. axisElementBuilders$2[name](this, this.group, this._axisGroup, axisModel);
  64576. }
  64577. }, this);
  64578. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  64579. _super.prototype.render.call(this, axisModel, ecModel, api, payload);
  64580. };
  64581. SingleAxisView.prototype.remove = function () {
  64582. rectCoordAxisHandleRemove(this);
  64583. };
  64584. SingleAxisView.type = 'singleAxis';
  64585. return SingleAxisView;
  64586. }(AxisView);
  64587. var axisElementBuilders$2 = {
  64588. splitLine: function (axisView, group, axisGroup, axisModel) {
  64589. var axis = axisModel.axis;
  64590. if (axis.scale.isBlank()) {
  64591. return;
  64592. }
  64593. var splitLineModel = axisModel.getModel('splitLine');
  64594. var lineStyleModel = splitLineModel.getModel('lineStyle');
  64595. var lineColors = lineStyleModel.get('color');
  64596. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  64597. var gridRect = axisModel.coordinateSystem.getRect();
  64598. var isHorizontal = axis.isHorizontal();
  64599. var splitLines = [];
  64600. var lineCount = 0;
  64601. var ticksCoords = axis.getTicksCoords({
  64602. tickModel: splitLineModel
  64603. });
  64604. var p1 = [];
  64605. var p2 = [];
  64606. for (var i = 0; i < ticksCoords.length; ++i) {
  64607. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  64608. if (isHorizontal) {
  64609. p1[0] = tickCoord;
  64610. p1[1] = gridRect.y;
  64611. p2[0] = tickCoord;
  64612. p2[1] = gridRect.y + gridRect.height;
  64613. } else {
  64614. p1[0] = gridRect.x;
  64615. p1[1] = tickCoord;
  64616. p2[0] = gridRect.x + gridRect.width;
  64617. p2[1] = tickCoord;
  64618. }
  64619. var colorIndex = lineCount++ % lineColors.length;
  64620. splitLines[colorIndex] = splitLines[colorIndex] || [];
  64621. splitLines[colorIndex].push(new Line({
  64622. subPixelOptimize: true,
  64623. shape: {
  64624. x1: p1[0],
  64625. y1: p1[1],
  64626. x2: p2[0],
  64627. y2: p2[1]
  64628. },
  64629. silent: true
  64630. }));
  64631. }
  64632. var lineStyle = lineStyleModel.getLineStyle(['color']);
  64633. for (var i = 0; i < splitLines.length; ++i) {
  64634. group.add(mergePath$1(splitLines[i], {
  64635. style: defaults({
  64636. stroke: lineColors[i % lineColors.length]
  64637. }, lineStyle),
  64638. silent: true
  64639. }));
  64640. }
  64641. },
  64642. splitArea: function (axisView, group, axisGroup, axisModel) {
  64643. rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, axisModel);
  64644. }
  64645. };
  64646. var SingleAxisModel =
  64647. /** @class */
  64648. function (_super) {
  64649. __extends(SingleAxisModel, _super);
  64650. function SingleAxisModel() {
  64651. var _this = _super !== null && _super.apply(this, arguments) || this;
  64652. _this.type = SingleAxisModel.type;
  64653. return _this;
  64654. }
  64655. SingleAxisModel.prototype.getCoordSysModel = function () {
  64656. return this;
  64657. };
  64658. SingleAxisModel.type = 'singleAxis';
  64659. SingleAxisModel.layoutMode = 'box';
  64660. SingleAxisModel.defaultOption = {
  64661. left: '5%',
  64662. top: '5%',
  64663. right: '5%',
  64664. bottom: '5%',
  64665. type: 'value',
  64666. position: 'bottom',
  64667. orient: 'horizontal',
  64668. axisLine: {
  64669. show: true,
  64670. lineStyle: {
  64671. width: 1,
  64672. type: 'solid'
  64673. }
  64674. },
  64675. // Single coordinate system and single axis is the,
  64676. // which is used as the parent tooltip model.
  64677. // same model, so we set default tooltip show as true.
  64678. tooltip: {
  64679. show: true
  64680. },
  64681. axisTick: {
  64682. show: true,
  64683. length: 6,
  64684. lineStyle: {
  64685. width: 1
  64686. }
  64687. },
  64688. axisLabel: {
  64689. show: true,
  64690. interval: 'auto'
  64691. },
  64692. splitLine: {
  64693. show: true,
  64694. lineStyle: {
  64695. type: 'dashed',
  64696. opacity: 0.2
  64697. }
  64698. }
  64699. };
  64700. return SingleAxisModel;
  64701. }(ComponentModel);
  64702. mixin(SingleAxisModel, AxisModelCommonMixin.prototype);
  64703. var SingleAxis =
  64704. /** @class */
  64705. function (_super) {
  64706. __extends(SingleAxis, _super);
  64707. function SingleAxis(dim, scale, coordExtent, axisType, position) {
  64708. var _this = _super.call(this, dim, scale, coordExtent) || this;
  64709. _this.type = axisType || 'value';
  64710. _this.position = position || 'bottom';
  64711. return _this;
  64712. }
  64713. /**
  64714. * Judge the orient of the axis.
  64715. */
  64716. SingleAxis.prototype.isHorizontal = function () {
  64717. var position = this.position;
  64718. return position === 'top' || position === 'bottom';
  64719. };
  64720. SingleAxis.prototype.pointToData = function (point, clamp) {
  64721. return this.coordinateSystem.pointToData(point)[0];
  64722. };
  64723. return SingleAxis;
  64724. }(Axis);
  64725. /**
  64726. * Create a single coordinates system.
  64727. */
  64728. var Single =
  64729. /** @class */
  64730. function () {
  64731. function Single(axisModel, ecModel, api) {
  64732. this.type = 'single';
  64733. this.dimension = 'single';
  64734. /**
  64735. * Add it just for draw tooltip.
  64736. */
  64737. this.dimensions = ['single'];
  64738. this.axisPointerEnabled = true;
  64739. this.model = axisModel;
  64740. this._init(axisModel, ecModel, api);
  64741. }
  64742. /**
  64743. * Initialize single coordinate system.
  64744. */
  64745. Single.prototype._init = function (axisModel, ecModel, api) {
  64746. var dim = this.dimension;
  64747. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  64748. var isCategory = axis.type === 'category';
  64749. axis.onBand = isCategory && axisModel.get('boundaryGap');
  64750. axis.inverse = axisModel.get('inverse');
  64751. axis.orient = axisModel.get('orient');
  64752. axisModel.axis = axis;
  64753. axis.model = axisModel;
  64754. axis.coordinateSystem = this;
  64755. this._axis = axis;
  64756. };
  64757. /**
  64758. * Update axis scale after data processed
  64759. */
  64760. Single.prototype.update = function (ecModel, api) {
  64761. ecModel.eachSeries(function (seriesModel) {
  64762. if (seriesModel.coordinateSystem === this) {
  64763. var data_1 = seriesModel.getData();
  64764. each(data_1.mapDimensionsAll(this.dimension), function (dim) {
  64765. this._axis.scale.unionExtentFromData(data_1, dim);
  64766. }, this);
  64767. niceScaleExtent(this._axis.scale, this._axis.model);
  64768. }
  64769. }, this);
  64770. };
  64771. /**
  64772. * Resize the single coordinate system.
  64773. */
  64774. Single.prototype.resize = function (axisModel, api) {
  64775. this._rect = getLayoutRect({
  64776. left: axisModel.get('left'),
  64777. top: axisModel.get('top'),
  64778. right: axisModel.get('right'),
  64779. bottom: axisModel.get('bottom'),
  64780. width: axisModel.get('width'),
  64781. height: axisModel.get('height')
  64782. }, {
  64783. width: api.getWidth(),
  64784. height: api.getHeight()
  64785. });
  64786. this._adjustAxis();
  64787. };
  64788. Single.prototype.getRect = function () {
  64789. return this._rect;
  64790. };
  64791. Single.prototype._adjustAxis = function () {
  64792. var rect = this._rect;
  64793. var axis = this._axis;
  64794. var isHorizontal = axis.isHorizontal();
  64795. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  64796. var idx = axis.reverse ? 1 : 0;
  64797. axis.setExtent(extent[idx], extent[1 - idx]);
  64798. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  64799. };
  64800. Single.prototype._updateAxisTransform = function (axis, coordBase) {
  64801. var axisExtent = axis.getExtent();
  64802. var extentSum = axisExtent[0] + axisExtent[1];
  64803. var isHorizontal = axis.isHorizontal();
  64804. axis.toGlobalCoord = isHorizontal ? function (coord) {
  64805. return coord + coordBase;
  64806. } : function (coord) {
  64807. return extentSum - coord + coordBase;
  64808. };
  64809. axis.toLocalCoord = isHorizontal ? function (coord) {
  64810. return coord - coordBase;
  64811. } : function (coord) {
  64812. return extentSum - coord + coordBase;
  64813. };
  64814. };
  64815. /**
  64816. * Get axis.
  64817. */
  64818. Single.prototype.getAxis = function () {
  64819. return this._axis;
  64820. };
  64821. /**
  64822. * Get axis, add it just for draw tooltip.
  64823. */
  64824. Single.prototype.getBaseAxis = function () {
  64825. return this._axis;
  64826. };
  64827. Single.prototype.getAxes = function () {
  64828. return [this._axis];
  64829. };
  64830. Single.prototype.getTooltipAxes = function () {
  64831. return {
  64832. baseAxes: [this.getAxis()],
  64833. // Empty otherAxes
  64834. otherAxes: []
  64835. };
  64836. };
  64837. /**
  64838. * If contain point.
  64839. */
  64840. Single.prototype.containPoint = function (point) {
  64841. var rect = this.getRect();
  64842. var axis = this.getAxis();
  64843. var orient = axis.orient;
  64844. if (orient === 'horizontal') {
  64845. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  64846. } else {
  64847. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  64848. }
  64849. };
  64850. Single.prototype.pointToData = function (point) {
  64851. var axis = this.getAxis();
  64852. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  64853. };
  64854. /**
  64855. * Convert the series data to concrete point.
  64856. * Can be [val] | val
  64857. */
  64858. Single.prototype.dataToPoint = function (val) {
  64859. var axis = this.getAxis();
  64860. var rect = this.getRect();
  64861. var pt = [];
  64862. var idx = axis.orient === 'horizontal' ? 0 : 1;
  64863. if (val instanceof Array) {
  64864. val = val[0];
  64865. }
  64866. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  64867. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  64868. return pt;
  64869. };
  64870. Single.prototype.convertToPixel = function (ecModel, finder, value) {
  64871. var coordSys = getCoordSys$3(finder);
  64872. return coordSys === this ? this.dataToPoint(value) : null;
  64873. };
  64874. Single.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  64875. var coordSys = getCoordSys$3(finder);
  64876. return coordSys === this ? this.pointToData(pixel) : null;
  64877. };
  64878. return Single;
  64879. }();
  64880. function getCoordSys$3(finder) {
  64881. var seriesModel = finder.seriesModel;
  64882. var singleModel = finder.singleAxisModel;
  64883. return singleModel && singleModel.coordinateSystem || seriesModel && seriesModel.coordinateSystem;
  64884. }
  64885. /**
  64886. * Create single coordinate system and inject it into seriesModel.
  64887. */
  64888. function create$2(ecModel, api) {
  64889. var singles = [];
  64890. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  64891. var single = new Single(axisModel, ecModel, api);
  64892. single.name = 'single_' + idx;
  64893. single.resize(axisModel, api);
  64894. axisModel.coordinateSystem = single;
  64895. singles.push(single);
  64896. });
  64897. ecModel.eachSeries(function (seriesModel) {
  64898. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  64899. var singleAxisModel = seriesModel.getReferringComponents('singleAxis', SINGLE_REFERRING).models[0];
  64900. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  64901. }
  64902. });
  64903. return singles;
  64904. }
  64905. var singleCreator = {
  64906. create: create$2,
  64907. dimensions: Single.prototype.dimensions
  64908. };
  64909. var XY = ['x', 'y'];
  64910. var WH = ['width', 'height'];
  64911. var SingleAxisPointer =
  64912. /** @class */
  64913. function (_super) {
  64914. __extends(SingleAxisPointer, _super);
  64915. function SingleAxisPointer() {
  64916. return _super !== null && _super.apply(this, arguments) || this;
  64917. }
  64918. /**
  64919. * @override
  64920. */
  64921. SingleAxisPointer.prototype.makeElOption = function (elOption, value, axisModel, axisPointerModel, api) {
  64922. var axis = axisModel.axis;
  64923. var coordSys = axis.coordinateSystem;
  64924. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  64925. var pixelValue = coordSys.dataToPoint(value)[0];
  64926. var axisPointerType = axisPointerModel.get('type');
  64927. if (axisPointerType && axisPointerType !== 'none') {
  64928. var elStyle = buildElStyle(axisPointerModel);
  64929. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, pixelValue, otherExtent);
  64930. pointerOption.style = elStyle;
  64931. elOption.graphicKey = pointerOption.type;
  64932. elOption.pointer = pointerOption;
  64933. }
  64934. var layoutInfo = layout$2(axisModel);
  64935. buildCartesianSingleLabelElOption( // @ts-ignore
  64936. value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  64937. };
  64938. /**
  64939. * @override
  64940. */
  64941. SingleAxisPointer.prototype.getHandleTransform = function (value, axisModel, axisPointerModel) {
  64942. var layoutInfo = layout$2(axisModel, {
  64943. labelInside: false
  64944. }); // @ts-ignore
  64945. layoutInfo.labelMargin = axisPointerModel.get(['handle', 'margin']);
  64946. var position = getTransformedPosition(axisModel.axis, value, layoutInfo);
  64947. return {
  64948. x: position[0],
  64949. y: position[1],
  64950. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  64951. };
  64952. };
  64953. /**
  64954. * @override
  64955. */
  64956. SingleAxisPointer.prototype.updateHandleTransform = function (transform, delta, axisModel, axisPointerModel) {
  64957. var axis = axisModel.axis;
  64958. var coordSys = axis.coordinateSystem;
  64959. var dimIndex = getPointDimIndex(axis);
  64960. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  64961. var currPosition = [transform.x, transform.y];
  64962. currPosition[dimIndex] += delta[dimIndex];
  64963. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  64964. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  64965. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  64966. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  64967. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  64968. cursorPoint[dimIndex] = currPosition[dimIndex];
  64969. return {
  64970. x: currPosition[0],
  64971. y: currPosition[1],
  64972. rotation: transform.rotation,
  64973. cursorPoint: cursorPoint,
  64974. tooltipOption: {
  64975. verticalAlign: 'middle'
  64976. }
  64977. };
  64978. };
  64979. return SingleAxisPointer;
  64980. }(BaseAxisPointer);
  64981. var pointerShapeBuilder$2 = {
  64982. line: function (axis, pixelValue, otherExtent) {
  64983. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  64984. return {
  64985. type: 'Line',
  64986. subPixelOptimize: true,
  64987. shape: targetShape
  64988. };
  64989. },
  64990. shadow: function (axis, pixelValue, otherExtent) {
  64991. var bandWidth = axis.getBandWidth();
  64992. var span = otherExtent[1] - otherExtent[0];
  64993. return {
  64994. type: 'Rect',
  64995. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  64996. };
  64997. }
  64998. };
  64999. function getPointDimIndex(axis) {
  65000. return axis.isHorizontal() ? 0 : 1;
  65001. }
  65002. function getGlobalExtent(coordSys, dimIndex) {
  65003. var rect = coordSys.getRect();
  65004. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  65005. }
  65006. var SingleView =
  65007. /** @class */
  65008. function (_super) {
  65009. __extends(SingleView, _super);
  65010. function SingleView() {
  65011. var _this = _super !== null && _super.apply(this, arguments) || this;
  65012. _this.type = SingleView.type;
  65013. return _this;
  65014. }
  65015. SingleView.type = 'single';
  65016. return SingleView;
  65017. }(ComponentView);
  65018. function install$v(registers) {
  65019. use(install$s);
  65020. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  65021. registers.registerComponentView(SingleView); // Axis
  65022. registers.registerComponentView(SingleAxisView);
  65023. registers.registerComponentModel(SingleAxisModel);
  65024. axisModelCreator(registers, 'single', SingleAxisModel, SingleAxisModel.defaultOption);
  65025. registers.registerCoordinateSystem('single', singleCreator);
  65026. }
  65027. var CalendarModel =
  65028. /** @class */
  65029. function (_super) {
  65030. __extends(CalendarModel, _super);
  65031. function CalendarModel() {
  65032. var _this = _super !== null && _super.apply(this, arguments) || this;
  65033. _this.type = CalendarModel.type;
  65034. return _this;
  65035. }
  65036. /**
  65037. * @override
  65038. */
  65039. CalendarModel.prototype.init = function (option, parentModel, ecModel) {
  65040. var inputPositionParams = getLayoutParams(option);
  65041. _super.prototype.init.apply(this, arguments);
  65042. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  65043. };
  65044. /**
  65045. * @override
  65046. */
  65047. CalendarModel.prototype.mergeOption = function (option) {
  65048. _super.prototype.mergeOption.apply(this, arguments);
  65049. mergeAndNormalizeLayoutParams(this.option, option);
  65050. };
  65051. CalendarModel.prototype.getCellSize = function () {
  65052. // Has been normalized
  65053. return this.option.cellSize;
  65054. };
  65055. CalendarModel.type = 'calendar';
  65056. CalendarModel.defaultOption = {
  65057. zlevel: 0,
  65058. z: 2,
  65059. left: 80,
  65060. top: 60,
  65061. cellSize: 20,
  65062. // horizontal vertical
  65063. orient: 'horizontal',
  65064. // month separate line style
  65065. splitLine: {
  65066. show: true,
  65067. lineStyle: {
  65068. color: '#000',
  65069. width: 1,
  65070. type: 'solid'
  65071. }
  65072. },
  65073. // rect style temporarily unused emphasis
  65074. itemStyle: {
  65075. color: '#fff',
  65076. borderWidth: 1,
  65077. borderColor: '#ccc'
  65078. },
  65079. // week text style
  65080. dayLabel: {
  65081. show: true,
  65082. firstDay: 0,
  65083. // start end
  65084. position: 'start',
  65085. margin: '50%',
  65086. nameMap: 'en',
  65087. color: '#000'
  65088. },
  65089. // month text style
  65090. monthLabel: {
  65091. show: true,
  65092. // start end
  65093. position: 'start',
  65094. margin: 5,
  65095. // center or left
  65096. align: 'center',
  65097. // cn en []
  65098. nameMap: 'en',
  65099. formatter: null,
  65100. color: '#000'
  65101. },
  65102. // year text style
  65103. yearLabel: {
  65104. show: true,
  65105. // top bottom left right
  65106. position: null,
  65107. margin: 30,
  65108. formatter: null,
  65109. color: '#ccc',
  65110. fontFamily: 'sans-serif',
  65111. fontWeight: 'bolder',
  65112. fontSize: 20
  65113. }
  65114. };
  65115. return CalendarModel;
  65116. }(ComponentModel);
  65117. function mergeAndNormalizeLayoutParams(target, raw) {
  65118. // Normalize cellSize
  65119. var cellSize = target.cellSize;
  65120. var cellSizeArr;
  65121. if (!isArray(cellSize)) {
  65122. cellSizeArr = target.cellSize = [cellSize, cellSize];
  65123. } else {
  65124. cellSizeArr = cellSize;
  65125. }
  65126. if (cellSizeArr.length === 1) {
  65127. cellSizeArr[1] = cellSizeArr[0];
  65128. }
  65129. var ignoreSize = map([0, 1], function (hvIdx) {
  65130. // If user have set `width` or both `left` and `right`, cellSizeArr
  65131. // will be automatically set to 'auto', otherwise the default
  65132. // setting of cellSizeArr will make `width` setting not work.
  65133. if (sizeCalculable(raw, hvIdx)) {
  65134. cellSizeArr[hvIdx] = 'auto';
  65135. }
  65136. return cellSizeArr[hvIdx] != null && cellSizeArr[hvIdx] !== 'auto';
  65137. });
  65138. mergeLayoutParam(target, raw, {
  65139. type: 'box',
  65140. ignoreSize: ignoreSize
  65141. });
  65142. }
  65143. var MONTH_TEXT = {
  65144. EN: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  65145. CN: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  65146. };
  65147. var WEEK_TEXT = {
  65148. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  65149. CN: ['日', '一', '二', '三', '四', '五', '六']
  65150. };
  65151. var CalendarView =
  65152. /** @class */
  65153. function (_super) {
  65154. __extends(CalendarView, _super);
  65155. function CalendarView() {
  65156. var _this = _super !== null && _super.apply(this, arguments) || this;
  65157. _this.type = CalendarView.type;
  65158. return _this;
  65159. }
  65160. CalendarView.prototype.render = function (calendarModel, ecModel, api) {
  65161. var group = this.group;
  65162. group.removeAll();
  65163. var coordSys = calendarModel.coordinateSystem; // range info
  65164. var rangeData = coordSys.getRangeInfo();
  65165. var orient = coordSys.getOrient();
  65166. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  65167. this._renderLines(calendarModel, rangeData, orient, group);
  65168. this._renderYearText(calendarModel, rangeData, orient, group);
  65169. this._renderMonthText(calendarModel, orient, group);
  65170. this._renderWeekText(calendarModel, rangeData, orient, group);
  65171. }; // render day rect
  65172. CalendarView.prototype._renderDayRect = function (calendarModel, rangeData, group) {
  65173. var coordSys = calendarModel.coordinateSystem;
  65174. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  65175. var sw = coordSys.getCellWidth();
  65176. var sh = coordSys.getCellHeight();
  65177. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  65178. var point = coordSys.dataToRect([i], false).tl; // every rect
  65179. var rect = new Rect({
  65180. shape: {
  65181. x: point[0],
  65182. y: point[1],
  65183. width: sw,
  65184. height: sh
  65185. },
  65186. cursor: 'default',
  65187. style: itemRectStyleModel
  65188. });
  65189. group.add(rect);
  65190. }
  65191. }; // render separate line
  65192. CalendarView.prototype._renderLines = function (calendarModel, rangeData, orient, group) {
  65193. var self = this;
  65194. var coordSys = calendarModel.coordinateSystem;
  65195. var lineStyleModel = calendarModel.getModel(['splitLine', 'lineStyle']).getLineStyle();
  65196. var show = calendarModel.get(['splitLine', 'show']);
  65197. var lineWidth = lineStyleModel.lineWidth;
  65198. this._tlpoints = [];
  65199. this._blpoints = [];
  65200. this._firstDayOfMonth = [];
  65201. this._firstDayPoints = [];
  65202. var firstDay = rangeData.start;
  65203. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  65204. addPoints(firstDay.formatedDate);
  65205. if (i === 0) {
  65206. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  65207. }
  65208. var date = firstDay.date;
  65209. date.setMonth(date.getMonth() + 1);
  65210. firstDay = coordSys.getDateInfo(date);
  65211. }
  65212. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  65213. function addPoints(date) {
  65214. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  65215. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  65216. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  65217. self._tlpoints.push(points[0]);
  65218. self._blpoints.push(points[points.length - 1]);
  65219. show && self._drawSplitline(points, lineStyleModel, group);
  65220. } // render top/left line
  65221. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  65222. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  65223. }; // get points at both ends
  65224. CalendarView.prototype._getEdgesPoints = function (points, lineWidth, orient) {
  65225. var rs = [points[0].slice(), points[points.length - 1].slice()];
  65226. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  65227. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  65228. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  65229. return rs;
  65230. }; // render split line
  65231. CalendarView.prototype._drawSplitline = function (points, lineStyle, group) {
  65232. var poyline = new Polyline({
  65233. z2: 20,
  65234. shape: {
  65235. points: points
  65236. },
  65237. style: lineStyle
  65238. });
  65239. group.add(poyline);
  65240. }; // render month line of one week points
  65241. CalendarView.prototype._getLinePointsOfOneWeek = function (calendarModel, date, orient) {
  65242. var coordSys = calendarModel.coordinateSystem;
  65243. var parsedDate = coordSys.getDateInfo(date);
  65244. var points = [];
  65245. for (var i = 0; i < 7; i++) {
  65246. var tmpD = coordSys.getNextNDay(parsedDate.time, i);
  65247. var point = coordSys.dataToRect([tmpD.time], false);
  65248. points[2 * tmpD.day] = point.tl;
  65249. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  65250. }
  65251. return points;
  65252. };
  65253. CalendarView.prototype._formatterLabel = function (formatter, params) {
  65254. if (typeof formatter === 'string' && formatter) {
  65255. return formatTplSimple(formatter, params);
  65256. }
  65257. if (typeof formatter === 'function') {
  65258. return formatter(params);
  65259. }
  65260. return params.nameMap;
  65261. };
  65262. CalendarView.prototype._yearTextPositionControl = function (textEl, point, orient, position, margin) {
  65263. var x = point[0];
  65264. var y = point[1];
  65265. var aligns = ['center', 'bottom'];
  65266. if (position === 'bottom') {
  65267. y += margin;
  65268. aligns = ['center', 'top'];
  65269. } else if (position === 'left') {
  65270. x -= margin;
  65271. } else if (position === 'right') {
  65272. x += margin;
  65273. aligns = ['center', 'top'];
  65274. } else {
  65275. // top
  65276. y -= margin;
  65277. }
  65278. var rotate = 0;
  65279. if (position === 'left' || position === 'right') {
  65280. rotate = Math.PI / 2;
  65281. }
  65282. return {
  65283. rotation: rotate,
  65284. x: x,
  65285. y: y,
  65286. style: {
  65287. align: aligns[0],
  65288. verticalAlign: aligns[1]
  65289. }
  65290. };
  65291. }; // render year
  65292. CalendarView.prototype._renderYearText = function (calendarModel, rangeData, orient, group) {
  65293. var yearLabel = calendarModel.getModel('yearLabel');
  65294. if (!yearLabel.get('show')) {
  65295. return;
  65296. }
  65297. var margin = yearLabel.get('margin');
  65298. var pos = yearLabel.get('position');
  65299. if (!pos) {
  65300. pos = orient !== 'horizontal' ? 'top' : 'left';
  65301. }
  65302. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  65303. var xc = (points[0][0] + points[1][0]) / 2;
  65304. var yc = (points[0][1] + points[1][1]) / 2;
  65305. var idx = orient === 'horizontal' ? 0 : 1;
  65306. var posPoints = {
  65307. top: [xc, points[idx][1]],
  65308. bottom: [xc, points[1 - idx][1]],
  65309. left: [points[1 - idx][0], yc],
  65310. right: [points[idx][0], yc]
  65311. };
  65312. var name = rangeData.start.y;
  65313. if (+rangeData.end.y > +rangeData.start.y) {
  65314. name = name + '-' + rangeData.end.y;
  65315. }
  65316. var formatter = yearLabel.get('formatter');
  65317. var params = {
  65318. start: rangeData.start.y,
  65319. end: rangeData.end.y,
  65320. nameMap: name
  65321. };
  65322. var content = this._formatterLabel(formatter, params);
  65323. var yearText = new ZRText({
  65324. z2: 30,
  65325. style: createTextStyle(yearLabel, {
  65326. text: content
  65327. })
  65328. });
  65329. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  65330. group.add(yearText);
  65331. };
  65332. CalendarView.prototype._monthTextPositionControl = function (point, isCenter, orient, position, margin) {
  65333. var align = 'left';
  65334. var vAlign = 'top';
  65335. var x = point[0];
  65336. var y = point[1];
  65337. if (orient === 'horizontal') {
  65338. y = y + margin;
  65339. if (isCenter) {
  65340. align = 'center';
  65341. }
  65342. if (position === 'start') {
  65343. vAlign = 'bottom';
  65344. }
  65345. } else {
  65346. x = x + margin;
  65347. if (isCenter) {
  65348. vAlign = 'middle';
  65349. }
  65350. if (position === 'start') {
  65351. align = 'right';
  65352. }
  65353. }
  65354. return {
  65355. x: x,
  65356. y: y,
  65357. align: align,
  65358. verticalAlign: vAlign
  65359. };
  65360. }; // render month and year text
  65361. CalendarView.prototype._renderMonthText = function (calendarModel, orient, group) {
  65362. var monthLabel = calendarModel.getModel('monthLabel');
  65363. if (!monthLabel.get('show')) {
  65364. return;
  65365. }
  65366. var nameMap = monthLabel.get('nameMap');
  65367. var margin = monthLabel.get('margin');
  65368. var pos = monthLabel.get('position');
  65369. var align = monthLabel.get('align');
  65370. var termPoints = [this._tlpoints, this._blpoints];
  65371. if (isString(nameMap)) {
  65372. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  65373. }
  65374. var idx = pos === 'start' ? 0 : 1;
  65375. var axis = orient === 'horizontal' ? 0 : 1;
  65376. margin = pos === 'start' ? -margin : margin;
  65377. var isCenter = align === 'center';
  65378. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  65379. var tmp = termPoints[idx][i].slice();
  65380. var firstDay = this._firstDayOfMonth[i];
  65381. if (isCenter) {
  65382. var firstDayPoints = this._firstDayPoints[i];
  65383. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  65384. }
  65385. var formatter = monthLabel.get('formatter');
  65386. var name_1 = nameMap[+firstDay.m - 1];
  65387. var params = {
  65388. yyyy: firstDay.y,
  65389. yy: (firstDay.y + '').slice(2),
  65390. MM: firstDay.m,
  65391. M: +firstDay.m,
  65392. nameMap: name_1
  65393. };
  65394. var content = this._formatterLabel(formatter, params);
  65395. var monthText = new ZRText({
  65396. z2: 30,
  65397. style: extend(createTextStyle(monthLabel, {
  65398. text: content
  65399. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin))
  65400. });
  65401. group.add(monthText);
  65402. }
  65403. };
  65404. CalendarView.prototype._weekTextPositionControl = function (point, orient, position, margin, cellSize) {
  65405. var align = 'center';
  65406. var vAlign = 'middle';
  65407. var x = point[0];
  65408. var y = point[1];
  65409. var isStart = position === 'start';
  65410. if (orient === 'horizontal') {
  65411. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  65412. align = isStart ? 'right' : 'left';
  65413. } else {
  65414. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  65415. vAlign = isStart ? 'bottom' : 'top';
  65416. }
  65417. return {
  65418. x: x,
  65419. y: y,
  65420. align: align,
  65421. verticalAlign: vAlign
  65422. };
  65423. }; // render weeks
  65424. CalendarView.prototype._renderWeekText = function (calendarModel, rangeData, orient, group) {
  65425. var dayLabel = calendarModel.getModel('dayLabel');
  65426. if (!dayLabel.get('show')) {
  65427. return;
  65428. }
  65429. var coordSys = calendarModel.coordinateSystem;
  65430. var pos = dayLabel.get('position');
  65431. var nameMap = dayLabel.get('nameMap');
  65432. var margin = dayLabel.get('margin');
  65433. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  65434. if (isString(nameMap)) {
  65435. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  65436. }
  65437. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  65438. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  65439. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  65440. if (pos === 'start') {
  65441. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  65442. margin = -margin;
  65443. }
  65444. for (var i = 0; i < 7; i++) {
  65445. var tmpD = coordSys.getNextNDay(start, i);
  65446. var point = coordSys.dataToRect([tmpD.time], false).center;
  65447. var day = i;
  65448. day = Math.abs((i + firstDayOfWeek) % 7);
  65449. var weekText = new ZRText({
  65450. z2: 30,
  65451. style: extend(createTextStyle(dayLabel, {
  65452. text: nameMap[day]
  65453. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize))
  65454. });
  65455. group.add(weekText);
  65456. }
  65457. };
  65458. CalendarView.type = 'calendar';
  65459. return CalendarView;
  65460. }(ComponentView);
  65461. var PROXIMATE_ONE_DAY = 86400000;
  65462. var Calendar =
  65463. /** @class */
  65464. function () {
  65465. function Calendar(calendarModel, ecModel, api) {
  65466. this.type = 'calendar';
  65467. this.dimensions = Calendar.dimensions; // Required in createListFromData
  65468. this.getDimensionsInfo = Calendar.getDimensionsInfo;
  65469. this._model = calendarModel;
  65470. }
  65471. Calendar.getDimensionsInfo = function () {
  65472. return [{
  65473. name: 'time',
  65474. type: 'time'
  65475. }, 'value'];
  65476. };
  65477. Calendar.prototype.getRangeInfo = function () {
  65478. return this._rangeInfo;
  65479. };
  65480. Calendar.prototype.getModel = function () {
  65481. return this._model;
  65482. };
  65483. Calendar.prototype.getRect = function () {
  65484. return this._rect;
  65485. };
  65486. Calendar.prototype.getCellWidth = function () {
  65487. return this._sw;
  65488. };
  65489. Calendar.prototype.getCellHeight = function () {
  65490. return this._sh;
  65491. };
  65492. Calendar.prototype.getOrient = function () {
  65493. return this._orient;
  65494. };
  65495. /**
  65496. * getFirstDayOfWeek
  65497. *
  65498. * @example
  65499. * 0 : start at Sunday
  65500. * 1 : start at Monday
  65501. *
  65502. * @return {number}
  65503. */
  65504. Calendar.prototype.getFirstDayOfWeek = function () {
  65505. return this._firstDayOfWeek;
  65506. };
  65507. /**
  65508. * get date info
  65509. * }
  65510. */
  65511. Calendar.prototype.getDateInfo = function (date) {
  65512. date = parseDate(date);
  65513. var y = date.getFullYear();
  65514. var m = date.getMonth() + 1;
  65515. var mStr = m < 10 ? '0' + m : '' + m;
  65516. var d = date.getDate();
  65517. var dStr = d < 10 ? '0' + d : '' + d;
  65518. var day = date.getDay();
  65519. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  65520. return {
  65521. y: y + '',
  65522. m: mStr,
  65523. d: dStr,
  65524. day: day,
  65525. time: date.getTime(),
  65526. formatedDate: y + '-' + mStr + '-' + dStr,
  65527. date: date
  65528. };
  65529. };
  65530. Calendar.prototype.getNextNDay = function (date, n) {
  65531. n = n || 0;
  65532. if (n === 0) {
  65533. return this.getDateInfo(date);
  65534. }
  65535. date = new Date(this.getDateInfo(date).time);
  65536. date.setDate(date.getDate() + n);
  65537. return this.getDateInfo(date);
  65538. };
  65539. Calendar.prototype.update = function (ecModel, api) {
  65540. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  65541. this._orient = this._model.get('orient');
  65542. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  65543. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  65544. var weeks = this._rangeInfo.weeks || 1;
  65545. var whNames = ['width', 'height'];
  65546. var cellSize = this._model.getCellSize().slice();
  65547. var layoutParams = this._model.getBoxLayoutParams();
  65548. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  65549. each([0, 1], function (idx) {
  65550. if (cellSizeSpecified(cellSize, idx)) {
  65551. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  65552. }
  65553. });
  65554. var whGlobal = {
  65555. width: api.getWidth(),
  65556. height: api.getHeight()
  65557. };
  65558. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  65559. each([0, 1], function (idx) {
  65560. if (!cellSizeSpecified(cellSize, idx)) {
  65561. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  65562. }
  65563. });
  65564. function cellSizeSpecified(cellSize, idx) {
  65565. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  65566. } // Has been calculated out number.
  65567. this._sw = cellSize[0];
  65568. this._sh = cellSize[1];
  65569. };
  65570. /**
  65571. * Convert a time data(time, value) item to (x, y) point.
  65572. */
  65573. // TODO Clamp of calendar is not same with cartesian coordinate systems.
  65574. // It will return NaN if data exceeds.
  65575. Calendar.prototype.dataToPoint = function (data, clamp) {
  65576. isArray(data) && (data = data[0]);
  65577. clamp == null && (clamp = true);
  65578. var dayInfo = this.getDateInfo(data);
  65579. var range = this._rangeInfo;
  65580. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  65581. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  65582. return [NaN, NaN];
  65583. }
  65584. var week = dayInfo.day;
  65585. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  65586. if (this._orient === 'vertical') {
  65587. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  65588. }
  65589. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  65590. };
  65591. /**
  65592. * Convert a (x, y) point to time data
  65593. */
  65594. Calendar.prototype.pointToData = function (point) {
  65595. var date = this.pointToDate(point);
  65596. return date && date.time;
  65597. };
  65598. /**
  65599. * Convert a time date item to (x, y) four point.
  65600. */
  65601. Calendar.prototype.dataToRect = function (data, clamp) {
  65602. var point = this.dataToPoint(data, clamp);
  65603. return {
  65604. contentShape: {
  65605. x: point[0] - (this._sw - this._lineWidth) / 2,
  65606. y: point[1] - (this._sh - this._lineWidth) / 2,
  65607. width: this._sw - this._lineWidth,
  65608. height: this._sh - this._lineWidth
  65609. },
  65610. center: point,
  65611. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  65612. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  65613. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  65614. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  65615. };
  65616. };
  65617. /**
  65618. * Convert a (x, y) point to time date
  65619. *
  65620. * @param {Array} point point
  65621. * @return {Object} date
  65622. */
  65623. Calendar.prototype.pointToDate = function (point) {
  65624. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  65625. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  65626. var range = this._rangeInfo.range;
  65627. if (this._orient === 'vertical') {
  65628. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  65629. }
  65630. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  65631. };
  65632. Calendar.prototype.convertToPixel = function (ecModel, finder, value) {
  65633. var coordSys = getCoordSys$4(finder);
  65634. return coordSys === this ? coordSys.dataToPoint(value) : null;
  65635. };
  65636. Calendar.prototype.convertFromPixel = function (ecModel, finder, pixel) {
  65637. var coordSys = getCoordSys$4(finder);
  65638. return coordSys === this ? coordSys.pointToData(pixel) : null;
  65639. };
  65640. Calendar.prototype.containPoint = function (point) {
  65641. console.warn('Not implemented.');
  65642. return false;
  65643. };
  65644. /**
  65645. * initRange
  65646. * Normalize to an [start, end] array
  65647. */
  65648. Calendar.prototype._initRangeOption = function () {
  65649. var range = this._model.get('range');
  65650. var normalizedRange; // Convert [1990] to 1990
  65651. if (isArray(range) && range.length === 1) {
  65652. range = range[0];
  65653. }
  65654. if (!isArray(range)) {
  65655. var rangeStr = range.toString(); // One year.
  65656. if (/^\d{4}$/.test(rangeStr)) {
  65657. normalizedRange = [rangeStr + '-01-01', rangeStr + '-12-31'];
  65658. } // One month
  65659. if (/^\d{4}[\/|-]\d{1,2}$/.test(rangeStr)) {
  65660. var start = this.getDateInfo(rangeStr);
  65661. var firstDay = start.date;
  65662. firstDay.setMonth(firstDay.getMonth() + 1);
  65663. var end = this.getNextNDay(firstDay, -1);
  65664. normalizedRange = [start.formatedDate, end.formatedDate];
  65665. } // One day
  65666. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rangeStr)) {
  65667. normalizedRange = [rangeStr, rangeStr];
  65668. }
  65669. } else {
  65670. normalizedRange = range;
  65671. }
  65672. if (!normalizedRange) {
  65673. if ("development" !== 'production') {
  65674. logError('Invalid date range.');
  65675. } // Not handling it.
  65676. return range;
  65677. }
  65678. var tmp = this._getRangeInfo(normalizedRange);
  65679. if (tmp.start.time > tmp.end.time) {
  65680. normalizedRange.reverse();
  65681. }
  65682. return normalizedRange;
  65683. };
  65684. /**
  65685. * range info
  65686. *
  65687. * @private
  65688. * @param {Array} range range ['2017-01-01', '2017-07-08']
  65689. * If range[0] > range[1], they will not be reversed.
  65690. * @return {Object} obj
  65691. */
  65692. Calendar.prototype._getRangeInfo = function (range) {
  65693. var parsedRange = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  65694. var reversed;
  65695. if (parsedRange[0].time > parsedRange[1].time) {
  65696. reversed = true;
  65697. parsedRange.reverse();
  65698. }
  65699. var allDay = Math.floor(parsedRange[1].time / PROXIMATE_ONE_DAY) - Math.floor(parsedRange[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  65700. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  65701. // Consider case2:
  65702. // Firstly set system timezone as "Time Zone: America/Toronto",
  65703. // ```
  65704. // let first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  65705. // let second = new Date(1478412000000);
  65706. // let allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  65707. // ```
  65708. // will get wrong result because of DST. So we should fix it.
  65709. var date = new Date(parsedRange[0].time);
  65710. var startDateNum = date.getDate();
  65711. var endDateNum = parsedRange[1].date.getDate();
  65712. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  65713. var dateNum = date.getDate();
  65714. if (dateNum !== endDateNum) {
  65715. var sign = date.getTime() - parsedRange[1].time > 0 ? 1 : -1;
  65716. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - parsedRange[1].time) * sign > 0) {
  65717. allDay -= sign;
  65718. date.setDate(dateNum - sign);
  65719. }
  65720. }
  65721. var weeks = Math.floor((allDay + parsedRange[0].day + 6) / 7);
  65722. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  65723. reversed && parsedRange.reverse();
  65724. return {
  65725. range: [parsedRange[0].formatedDate, parsedRange[1].formatedDate],
  65726. start: parsedRange[0],
  65727. end: parsedRange[1],
  65728. allDay: allDay,
  65729. weeks: weeks,
  65730. // From 0.
  65731. nthWeek: nthWeek,
  65732. fweek: parsedRange[0].day,
  65733. lweek: parsedRange[1].day
  65734. };
  65735. };
  65736. /**
  65737. * get date by nthWeeks and week day in range
  65738. *
  65739. * @private
  65740. * @param {number} nthWeek the week
  65741. * @param {number} day the week day
  65742. * @param {Array} range [d1, d2]
  65743. * @return {Object}
  65744. */
  65745. Calendar.prototype._getDateByWeeksAndDay = function (nthWeek, day, range) {
  65746. var rangeInfo = this._getRangeInfo(range);
  65747. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  65748. return null;
  65749. }
  65750. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  65751. var date = new Date(rangeInfo.start.time);
  65752. date.setDate(+rangeInfo.start.d + nthDay);
  65753. return this.getDateInfo(date);
  65754. };
  65755. Calendar.create = function (ecModel, api) {
  65756. var calendarList = [];
  65757. ecModel.eachComponent('calendar', function (calendarModel) {
  65758. var calendar = new Calendar(calendarModel, ecModel, api);
  65759. calendarList.push(calendar);
  65760. calendarModel.coordinateSystem = calendar;
  65761. });
  65762. ecModel.eachSeries(function (calendarSeries) {
  65763. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  65764. // Inject coordinate system
  65765. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  65766. }
  65767. });
  65768. return calendarList;
  65769. };
  65770. Calendar.dimensions = ['time', 'value'];
  65771. return Calendar;
  65772. }();
  65773. function getCoordSys$4(finder) {
  65774. var calendarModel = finder.calendarModel;
  65775. var seriesModel = finder.seriesModel;
  65776. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  65777. return coordSys;
  65778. }
  65779. function install$w(registers) {
  65780. registers.registerComponentModel(CalendarModel);
  65781. registers.registerComponentView(CalendarView);
  65782. registers.registerCoordinateSystem('calendar', Calendar);
  65783. }
  65784. var inner$g = makeInner();
  65785. var _nonShapeGraphicElements = {
  65786. // Reserved but not supported in graphic component.
  65787. path: null,
  65788. compoundPath: null,
  65789. // Supported in graphic component.
  65790. group: Group,
  65791. image: ZRImage,
  65792. text: ZRText
  65793. }; // ------------------------
  65794. // Preprocessor
  65795. // ------------------------
  65796. var preprocessor = function (option) {
  65797. var graphicOption = option.graphic; // Convert
  65798. // {graphic: [{left: 10, type: 'circle'}, ...]}
  65799. // or
  65800. // {graphic: {left: 10, type: 'circle'}}
  65801. // to
  65802. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  65803. if (isArray(graphicOption)) {
  65804. if (!graphicOption[0] || !graphicOption[0].elements) {
  65805. option.graphic = [{
  65806. elements: graphicOption
  65807. }];
  65808. } else {
  65809. // Only one graphic instance can be instantiated. (We dont
  65810. // want that too many views are created in echarts._viewMap)
  65811. option.graphic = [option.graphic[0]];
  65812. }
  65813. } else if (graphicOption && !graphicOption.elements) {
  65814. option.graphic = [{
  65815. elements: [graphicOption]
  65816. }];
  65817. }
  65818. };
  65819. var GraphicComponentModel =
  65820. /** @class */
  65821. function (_super) {
  65822. __extends(GraphicComponentModel, _super);
  65823. function GraphicComponentModel() {
  65824. var _this = _super !== null && _super.apply(this, arguments) || this;
  65825. _this.type = GraphicComponentModel.type;
  65826. return _this;
  65827. }
  65828. GraphicComponentModel.prototype.mergeOption = function (option, ecModel) {
  65829. // Prevent default merge to elements
  65830. var elements = this.option.elements;
  65831. this.option.elements = null;
  65832. _super.prototype.mergeOption.call(this, option, ecModel);
  65833. this.option.elements = elements;
  65834. };
  65835. GraphicComponentModel.prototype.optionUpdated = function (newOption, isInit) {
  65836. var thisOption = this.option;
  65837. var newList = (isInit ? thisOption : newOption).elements;
  65838. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  65839. var flattenedList = [];
  65840. this._flatten(newList, flattenedList, null);
  65841. var mappingResult = mappingToExists(existList, flattenedList, 'normalMerge'); // Clear elOptionsToUpdate
  65842. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  65843. each(mappingResult, function (resultItem, index) {
  65844. var newElOption = resultItem.newOption;
  65845. if ("development" !== 'production') {
  65846. assert(isObject(newElOption) || resultItem.existing, 'Empty graphic option definition');
  65847. }
  65848. if (!newElOption) {
  65849. return;
  65850. }
  65851. elOptionsToUpdate.push(newElOption);
  65852. setKeyInfoToNewElOption(resultItem, newElOption);
  65853. mergeNewElOptionToExist(existList, index, newElOption);
  65854. setLayoutInfoToExist(existList[index], newElOption);
  65855. }, this); // Clean
  65856. for (var i = existList.length - 1; i >= 0; i--) {
  65857. if (existList[i] == null) {
  65858. existList.splice(i, 1);
  65859. } else {
  65860. // $action should be volatile, otherwise option gotten from
  65861. // `getOption` will contain unexpected $action.
  65862. delete existList[i].$action;
  65863. }
  65864. }
  65865. };
  65866. /**
  65867. * Convert
  65868. * [{
  65869. * type: 'group',
  65870. * id: 'xx',
  65871. * children: [{type: 'circle'}, {type: 'polygon'}]
  65872. * }]
  65873. * to
  65874. * [
  65875. * {type: 'group', id: 'xx'},
  65876. * {type: 'circle', parentId: 'xx'},
  65877. * {type: 'polygon', parentId: 'xx'}
  65878. * ]
  65879. */
  65880. GraphicComponentModel.prototype._flatten = function (optionList, result, parentOption) {
  65881. each(optionList, function (option) {
  65882. if (!option) {
  65883. return;
  65884. }
  65885. if (parentOption) {
  65886. option.parentOption = parentOption;
  65887. }
  65888. result.push(option);
  65889. var children = option.children;
  65890. if (option.type === 'group' && children) {
  65891. this._flatten(children, result, option);
  65892. } // Deleting for JSON output, and for not affecting group creation.
  65893. delete option.children;
  65894. }, this);
  65895. }; // FIXME
  65896. // Pass to view using payload? setOption has a payload?
  65897. GraphicComponentModel.prototype.useElOptionsToUpdate = function () {
  65898. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  65899. this._elOptionsToUpdate = null;
  65900. return els;
  65901. };
  65902. GraphicComponentModel.type = 'graphic';
  65903. GraphicComponentModel.defaultOption = {
  65904. elements: [] // parentId: null
  65905. };
  65906. return GraphicComponentModel;
  65907. }(ComponentModel); // ------------------------
  65908. // View
  65909. // ------------------------
  65910. var GraphicComponentView =
  65911. /** @class */
  65912. function (_super) {
  65913. __extends(GraphicComponentView, _super);
  65914. function GraphicComponentView() {
  65915. var _this = _super !== null && _super.apply(this, arguments) || this;
  65916. _this.type = GraphicComponentView.type;
  65917. return _this;
  65918. }
  65919. GraphicComponentView.prototype.init = function () {
  65920. this._elMap = createHashMap();
  65921. };
  65922. GraphicComponentView.prototype.render = function (graphicModel, ecModel, api) {
  65923. // Having leveraged between use cases and algorithm complexity, a very
  65924. // simple layout mechanism is used:
  65925. // The size(width/height) can be determined by itself or its parent (not
  65926. // implemented yet), but can not by its children. (Top-down travel)
  65927. // The location(x/y) can be determined by the bounding rect of itself
  65928. // (can including its descendants or not) and the size of its parent.
  65929. // (Bottom-up travel)
  65930. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  65931. // view will be reused.
  65932. if (graphicModel !== this._lastGraphicModel) {
  65933. this._clear();
  65934. }
  65935. this._lastGraphicModel = graphicModel;
  65936. this._updateElements(graphicModel);
  65937. this._relocate(graphicModel, api);
  65938. };
  65939. /**
  65940. * Update graphic elements.
  65941. */
  65942. GraphicComponentView.prototype._updateElements = function (graphicModel) {
  65943. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  65944. if (!elOptionsToUpdate) {
  65945. return;
  65946. }
  65947. var elMap = this._elMap;
  65948. var rootGroup = this.group; // Top-down tranverse to assign graphic settings to each elements.
  65949. each(elOptionsToUpdate, function (elOption) {
  65950. var id = convertOptionIdName(elOption.id, null);
  65951. var elExisting = id != null ? elMap.get(id) : null;
  65952. var parentId = convertOptionIdName(elOption.parentId, null);
  65953. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  65954. var elType = elOption.type;
  65955. var elOptionStyle = elOption.style;
  65956. if (elType === 'text' && elOptionStyle) {
  65957. // In top/bottom mode, textVerticalAlign should not be used, which cause
  65958. // inaccurately locating.
  65959. if (elOption.hv && elOption.hv[1]) {
  65960. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = elOptionStyle.verticalAlign = elOptionStyle.align = null;
  65961. }
  65962. }
  65963. var textContentOption = elOption.textContent;
  65964. var textConfig = elOption.textConfig;
  65965. if (elOptionStyle && isEC4CompatibleStyle(elOptionStyle, elType, !!textConfig, !!textContentOption)) {
  65966. var convertResult = convertFromEC4CompatibleStyle(elOptionStyle, elType, true);
  65967. if (!textConfig && convertResult.textConfig) {
  65968. textConfig = elOption.textConfig = convertResult.textConfig;
  65969. }
  65970. if (!textContentOption && convertResult.textContent) {
  65971. textContentOption = convertResult.textContent;
  65972. }
  65973. } // Remove unnecessary props to avoid potential problems.
  65974. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  65975. if ("development" !== 'production') {
  65976. elExisting && assert(targetElParent === elExisting.parent, 'Changing parent is not supported.');
  65977. }
  65978. var $action = elOption.$action || 'merge';
  65979. if ($action === 'merge') {
  65980. elExisting ? elExisting.attr(elOptionCleaned) : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  65981. } else if ($action === 'replace') {
  65982. removeEl(elExisting, elMap);
  65983. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  65984. } else if ($action === 'remove') {
  65985. removeEl(elExisting, elMap);
  65986. }
  65987. var el = elMap.get(id);
  65988. if (el && textContentOption) {
  65989. if ($action === 'merge') {
  65990. var textContentExisting = el.getTextContent();
  65991. textContentExisting ? textContentExisting.attr(textContentOption) : el.setTextContent(new ZRText(textContentOption));
  65992. } else if ($action === 'replace') {
  65993. el.setTextContent(new ZRText(textContentOption));
  65994. }
  65995. }
  65996. if (el) {
  65997. var elInner = inner$g(el);
  65998. elInner.__ecGraphicWidthOption = elOption.width;
  65999. elInner.__ecGraphicHeightOption = elOption.height;
  66000. setEventData(el, graphicModel, elOption);
  66001. }
  66002. });
  66003. };
  66004. /**
  66005. * Locate graphic elements.
  66006. */
  66007. GraphicComponentView.prototype._relocate = function (graphicModel, api) {
  66008. var elOptions = graphicModel.option.elements;
  66009. var rootGroup = this.group;
  66010. var elMap = this._elMap;
  66011. var apiWidth = api.getWidth();
  66012. var apiHeight = api.getHeight(); // Top-down to calculate percentage width/height of group
  66013. for (var i = 0; i < elOptions.length; i++) {
  66014. var elOption = elOptions[i];
  66015. var id = convertOptionIdName(elOption.id, null);
  66016. var el = id != null ? elMap.get(id) : null;
  66017. if (!el || !el.isGroup) {
  66018. continue;
  66019. }
  66020. var parentEl = el.parent;
  66021. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  66022. var elInner = inner$g(el);
  66023. var parentElInner = inner$g(parentEl);
  66024. elInner.__ecGraphicWidth = parsePercent$1(elInner.__ecGraphicWidthOption, isParentRoot ? apiWidth : parentElInner.__ecGraphicWidth) || 0;
  66025. elInner.__ecGraphicHeight = parsePercent$1(elInner.__ecGraphicHeightOption, isParentRoot ? apiHeight : parentElInner.__ecGraphicHeight) || 0;
  66026. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  66027. for (var i = elOptions.length - 1; i >= 0; i--) {
  66028. var elOption = elOptions[i];
  66029. var id = convertOptionIdName(elOption.id, null);
  66030. var el = id != null ? elMap.get(id) : null;
  66031. if (!el) {
  66032. continue;
  66033. }
  66034. var parentEl = el.parent;
  66035. var parentElInner = inner$g(parentEl);
  66036. var containerInfo = parentEl === rootGroup ? {
  66037. width: apiWidth,
  66038. height: apiHeight
  66039. } : {
  66040. width: parentElInner.__ecGraphicWidth,
  66041. height: parentElInner.__ecGraphicHeight
  66042. }; // PENDING
  66043. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  66044. // does not include the rect of [0, 0, group.width, group.height], which
  66045. // is probably weird for users. Should we make a break change for it?
  66046. positionElement(el, elOption, containerInfo, null, {
  66047. hv: elOption.hv,
  66048. boundingMode: elOption.bounding
  66049. });
  66050. }
  66051. };
  66052. /**
  66053. * Clear all elements.
  66054. */
  66055. GraphicComponentView.prototype._clear = function () {
  66056. var elMap = this._elMap;
  66057. elMap.each(function (el) {
  66058. removeEl(el, elMap);
  66059. });
  66060. this._elMap = createHashMap();
  66061. };
  66062. GraphicComponentView.prototype.dispose = function () {
  66063. this._clear();
  66064. };
  66065. GraphicComponentView.type = 'graphic';
  66066. return GraphicComponentView;
  66067. }(ComponentView);
  66068. function createEl$1(id, targetElParent, elOption, elMap) {
  66069. var graphicType = elOption.type;
  66070. if ("development" !== 'production') {
  66071. assert(graphicType, 'graphic type MUST be set');
  66072. }
  66073. var Clz = hasOwn(_nonShapeGraphicElements, graphicType) // Those graphic elements are not shapes. They should not be
  66074. // overwritten by users, so do them first.
  66075. ? _nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  66076. if ("development" !== 'production') {
  66077. assert(Clz, 'graphic type can not be found');
  66078. }
  66079. var el = new Clz(elOption);
  66080. targetElParent.add(el);
  66081. elMap.set(id, el);
  66082. inner$g(el).__ecGraphicId = id;
  66083. }
  66084. function removeEl(elExisting, elMap) {
  66085. var existElParent = elExisting && elExisting.parent;
  66086. if (existElParent) {
  66087. elExisting.type === 'group' && elExisting.traverse(function (el) {
  66088. removeEl(el, elMap);
  66089. });
  66090. elMap.removeKey(inner$g(elExisting).__ecGraphicId);
  66091. existElParent.remove(elExisting);
  66092. }
  66093. } // Remove unnecessary props to avoid potential problems.
  66094. function getCleanedElOption(elOption) {
  66095. elOption = extend({}, elOption);
  66096. each(['id', 'parentId', '$action', 'hv', 'bounding', 'textContent'].concat(LOCATION_PARAMS), function (name) {
  66097. delete elOption[name];
  66098. });
  66099. return elOption;
  66100. }
  66101. function isSetLoc(obj, props) {
  66102. var isSet;
  66103. each(props, function (prop) {
  66104. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  66105. });
  66106. return isSet;
  66107. }
  66108. function setKeyInfoToNewElOption(resultItem, newElOption) {
  66109. var existElOption = resultItem.existing; // Set id and type after id assigned.
  66110. newElOption.id = resultItem.keyInfo.id;
  66111. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  66112. if (newElOption.parentId == null) {
  66113. var newElParentOption = newElOption.parentOption;
  66114. if (newElParentOption) {
  66115. newElOption.parentId = newElParentOption.id;
  66116. } else if (existElOption) {
  66117. newElOption.parentId = existElOption.parentId;
  66118. }
  66119. } // Clear
  66120. newElOption.parentOption = null;
  66121. }
  66122. function mergeNewElOptionToExist(existList, index, newElOption) {
  66123. // Update existing options, for `getOption` feature.
  66124. var newElOptCopy = extend({}, newElOption);
  66125. var existElOption = existList[index];
  66126. var $action = newElOption.$action || 'merge';
  66127. if ($action === 'merge') {
  66128. if (existElOption) {
  66129. if ("development" !== 'production') {
  66130. var newType = newElOption.type;
  66131. assert(!newType || existElOption.type === newType, 'Please set $action: "replace" to change `type`');
  66132. } // We can ensure that newElOptCopy and existElOption are not
  66133. // the same object, so `merge` will not change newElOptCopy.
  66134. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  66135. mergeLayoutParam(existElOption, newElOptCopy, {
  66136. ignoreSize: true
  66137. }); // Will be used in render.
  66138. copyLayoutParams(newElOption, existElOption);
  66139. } else {
  66140. existList[index] = newElOptCopy;
  66141. }
  66142. } else if ($action === 'replace') {
  66143. existList[index] = newElOptCopy;
  66144. } else if ($action === 'remove') {
  66145. // null will be cleaned later.
  66146. existElOption && (existList[index] = null);
  66147. }
  66148. }
  66149. function setLayoutInfoToExist(existItem, newElOption) {
  66150. if (!existItem) {
  66151. return;
  66152. }
  66153. existItem.hv = newElOption.hv = [// Rigid body, dont care `width`.
  66154. isSetLoc(newElOption, ['left', 'right']), // Rigid body, dont care `height`.
  66155. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  66156. if (existItem.type === 'group') {
  66157. var existingGroupOpt = existItem;
  66158. var newGroupOpt = newElOption;
  66159. existingGroupOpt.width == null && (existingGroupOpt.width = newGroupOpt.width = 0);
  66160. existingGroupOpt.height == null && (existingGroupOpt.height = newGroupOpt.height = 0);
  66161. }
  66162. }
  66163. function setEventData(el, graphicModel, elOption) {
  66164. var eventData = getECData(el).eventData; // Simple optimize for large amount of elements that no need event.
  66165. if (!el.silent && !el.ignore && !eventData) {
  66166. eventData = getECData(el).eventData = {
  66167. componentType: 'graphic',
  66168. componentIndex: graphicModel.componentIndex,
  66169. name: el.name
  66170. };
  66171. } // `elOption.info` enables user to mount some info on
  66172. // elements and use them in event handlers.
  66173. if (eventData) {
  66174. eventData.info = elOption.info;
  66175. }
  66176. }
  66177. function install$x(registers) {
  66178. registers.registerComponentModel(GraphicComponentModel);
  66179. registers.registerComponentView(GraphicComponentView);
  66180. registers.registerPreprocessor(preprocessor);
  66181. }
  66182. var DATA_ZOOM_AXIS_DIMENSIONS = ['x', 'y', 'radius', 'angle', 'single']; // Supported coords.
  66183. // FIXME: polar has been broken (but rarely used).
  66184. var SERIES_COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  66185. function isCoordSupported(seriesModel) {
  66186. var coordType = seriesModel.get('coordinateSystem');
  66187. return indexOf(SERIES_COORDS, coordType) >= 0;
  66188. }
  66189. function getAxisMainType(axisDim) {
  66190. if ("development" !== 'production') {
  66191. assert(axisDim);
  66192. }
  66193. return axisDim + 'Axis';
  66194. }
  66195. /**
  66196. * If two dataZoomModels has the same axis controlled, we say that they are 'linked'.
  66197. * This function finds all linked dataZoomModels start from the given payload.
  66198. */
  66199. function findEffectedDataZooms(ecModel, payload) {
  66200. // Key: `DataZoomAxisDimension`
  66201. var axisRecords = createHashMap();
  66202. var effectedModels = []; // Key: uid of dataZoomModel
  66203. var effectedModelMap = createHashMap(); // Find the dataZooms specified by payload.
  66204. ecModel.eachComponent({
  66205. mainType: 'dataZoom',
  66206. query: payload
  66207. }, function (dataZoomModel) {
  66208. if (!effectedModelMap.get(dataZoomModel.uid)) {
  66209. addToEffected(dataZoomModel);
  66210. }
  66211. }); // Start from the given dataZoomModels, travel the graph to find
  66212. // all of the linked dataZoom models.
  66213. var foundNewLink;
  66214. do {
  66215. foundNewLink = false;
  66216. ecModel.eachComponent('dataZoom', processSingle);
  66217. } while (foundNewLink);
  66218. function processSingle(dataZoomModel) {
  66219. if (!effectedModelMap.get(dataZoomModel.uid) && isLinked(dataZoomModel)) {
  66220. addToEffected(dataZoomModel);
  66221. foundNewLink = true;
  66222. }
  66223. }
  66224. function addToEffected(dataZoom) {
  66225. effectedModelMap.set(dataZoom.uid, true);
  66226. effectedModels.push(dataZoom);
  66227. markAxisControlled(dataZoom);
  66228. }
  66229. function isLinked(dataZoomModel) {
  66230. var isLink = false;
  66231. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  66232. var axisIdxArr = axisRecords.get(axisDim);
  66233. if (axisIdxArr && axisIdxArr[axisIndex]) {
  66234. isLink = true;
  66235. }
  66236. });
  66237. return isLink;
  66238. }
  66239. function markAxisControlled(dataZoomModel) {
  66240. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  66241. (axisRecords.get(axisDim) || axisRecords.set(axisDim, []))[axisIndex] = true;
  66242. });
  66243. }
  66244. return effectedModels;
  66245. }
  66246. /**
  66247. * Find the first target coordinate system.
  66248. * Available after model built.
  66249. *
  66250. * @return Like {
  66251. * grid: [
  66252. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  66253. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  66254. * ...
  66255. * ], // cartesians must not be null/undefined.
  66256. * polar: [
  66257. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  66258. * ...
  66259. * ], // polars must not be null/undefined.
  66260. * singleAxis: [
  66261. * {model: coord0, axisModels: [], coordIndex: 0}
  66262. * ]
  66263. * }
  66264. */
  66265. function collectReferCoordSysModelInfo(dataZoomModel) {
  66266. var ecModel = dataZoomModel.ecModel;
  66267. var coordSysInfoWrap = {
  66268. infoList: [],
  66269. infoMap: createHashMap()
  66270. };
  66271. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  66272. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  66273. if (!axisModel) {
  66274. return;
  66275. }
  66276. var coordSysModel = axisModel.getCoordSysModel();
  66277. if (!coordSysModel) {
  66278. return;
  66279. }
  66280. var coordSysUid = coordSysModel.uid;
  66281. var coordSysInfo = coordSysInfoWrap.infoMap.get(coordSysUid);
  66282. if (!coordSysInfo) {
  66283. coordSysInfo = {
  66284. model: coordSysModel,
  66285. axisModels: []
  66286. };
  66287. coordSysInfoWrap.infoList.push(coordSysInfo);
  66288. coordSysInfoWrap.infoMap.set(coordSysUid, coordSysInfo);
  66289. }
  66290. coordSysInfo.axisModels.push(axisModel);
  66291. });
  66292. return coordSysInfoWrap;
  66293. }
  66294. var DataZoomAxisInfo =
  66295. /** @class */
  66296. function () {
  66297. function DataZoomAxisInfo() {
  66298. this.indexList = [];
  66299. this.indexMap = [];
  66300. }
  66301. DataZoomAxisInfo.prototype.add = function (axisCmptIdx) {
  66302. // Remove duplication.
  66303. if (!this.indexMap[axisCmptIdx]) {
  66304. this.indexList.push(axisCmptIdx);
  66305. this.indexMap[axisCmptIdx] = true;
  66306. }
  66307. };
  66308. return DataZoomAxisInfo;
  66309. }();
  66310. var DataZoomModel =
  66311. /** @class */
  66312. function (_super) {
  66313. __extends(DataZoomModel, _super);
  66314. function DataZoomModel() {
  66315. var _this = _super !== null && _super.apply(this, arguments) || this;
  66316. _this.type = DataZoomModel.type;
  66317. _this._autoThrottle = true;
  66318. _this._noTarget = true;
  66319. /**
  66320. * It is `[rangeModeForMin, rangeModeForMax]`.
  66321. * The optional values for `rangeMode`:
  66322. * + `'value'` mode: the axis extent will always be determined by
  66323. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  66324. * how data like and how `axis.min` and `axis.max` are.
  66325. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  66326. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  66327. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  66328. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  66329. *
  66330. * For example, when users are using dynamic data (update data periodically via `setOption`),
  66331. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  66332. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  66333. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  66334. */
  66335. _this._rangePropMode = ['percent', 'percent'];
  66336. return _this;
  66337. }
  66338. DataZoomModel.prototype.init = function (option, parentModel, ecModel) {
  66339. var inputRawOption = retrieveRawOption(option);
  66340. /**
  66341. * Suppose a "main process" start at the point that model prepared (that is,
  66342. * model initialized or merged or method called in `action`).
  66343. * We should keep the `main process` idempotent, that is, given a set of values
  66344. * on `option`, we get the same result.
  66345. *
  66346. * But sometimes, values on `option` will be updated for providing users
  66347. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  66348. * should not be the base/input of the `main process`.
  66349. *
  66350. * So in that case we should save and keep the input of the `main process`
  66351. * separately, called `settledOption`.
  66352. *
  66353. * For example, consider the case:
  66354. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  66355. * where the original input `option.startValue`, `option.endValue` are earsed by
  66356. * calculated value.
  66357. * (Step)2) click the legend to hide and show a series,
  66358. * where the new range is calculated by the earsed `startValue` and `endValue`,
  66359. * which brings incorrect result.
  66360. */
  66361. this.settledOption = inputRawOption;
  66362. this.mergeDefaultAndTheme(option, ecModel);
  66363. this._doInit(inputRawOption);
  66364. };
  66365. DataZoomModel.prototype.mergeOption = function (newOption) {
  66366. var inputRawOption = retrieveRawOption(newOption); //FIX #2591
  66367. merge(this.option, newOption, true);
  66368. merge(this.settledOption, inputRawOption, true);
  66369. this._doInit(inputRawOption);
  66370. };
  66371. DataZoomModel.prototype._doInit = function (inputRawOption) {
  66372. var thisOption = this.option; // if (!env.canvasSupported) {
  66373. // thisOption.realtime = false;
  66374. // }
  66375. this._setDefaultThrottle(inputRawOption);
  66376. this._updateRangeUse(inputRawOption);
  66377. var settledOption = this.settledOption;
  66378. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  66379. // start/end has higher priority over startValue/endValue if they
  66380. // both set, but we should make chart.setOption({endValue: 1000})
  66381. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  66382. if (this._rangePropMode[index] === 'value') {
  66383. thisOption[names[0]] = settledOption[names[0]] = null;
  66384. } // Otherwise do nothing and use the merge result.
  66385. }, this);
  66386. this._resetTarget();
  66387. };
  66388. DataZoomModel.prototype._resetTarget = function () {
  66389. var optionOrient = this.get('orient', true);
  66390. var targetAxisIndexMap = this._targetAxisInfoMap = createHashMap();
  66391. var hasAxisSpecified = this._fillSpecifiedTargetAxis(targetAxisIndexMap);
  66392. if (hasAxisSpecified) {
  66393. this._orient = optionOrient || this._makeAutoOrientByTargetAxis();
  66394. } else {
  66395. this._orient = optionOrient || 'horizontal';
  66396. this._fillAutoTargetAxisByOrient(targetAxisIndexMap, this._orient);
  66397. }
  66398. this._noTarget = true;
  66399. targetAxisIndexMap.each(function (axisInfo) {
  66400. if (axisInfo.indexList.length) {
  66401. this._noTarget = false;
  66402. }
  66403. }, this);
  66404. };
  66405. DataZoomModel.prototype._fillSpecifiedTargetAxis = function (targetAxisIndexMap) {
  66406. var hasAxisSpecified = false;
  66407. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  66408. var refering = this.getReferringComponents(getAxisMainType(axisDim), MULTIPLE_REFERRING); // When user set axisIndex as a empty array, we think that user specify axisIndex
  66409. // but do not want use auto mode. Because empty array may be encountered when
  66410. // some error occured.
  66411. if (!refering.specified) {
  66412. return;
  66413. }
  66414. hasAxisSpecified = true;
  66415. var axisInfo = new DataZoomAxisInfo();
  66416. each(refering.models, function (axisModel) {
  66417. axisInfo.add(axisModel.componentIndex);
  66418. });
  66419. targetAxisIndexMap.set(axisDim, axisInfo);
  66420. }, this);
  66421. return hasAxisSpecified;
  66422. };
  66423. DataZoomModel.prototype._fillAutoTargetAxisByOrient = function (targetAxisIndexMap, orient) {
  66424. var ecModel = this.ecModel;
  66425. var needAuto = true; // Find axis that parallel to dataZoom as default.
  66426. if (needAuto) {
  66427. var axisDim = orient === 'vertical' ? 'y' : 'x';
  66428. var axisModels = ecModel.findComponents({
  66429. mainType: axisDim + 'Axis'
  66430. });
  66431. setParallelAxis(axisModels, axisDim);
  66432. } // Find axis that parallel to dataZoom as default.
  66433. if (needAuto) {
  66434. var axisModels = ecModel.findComponents({
  66435. mainType: 'singleAxis',
  66436. filter: function (axisModel) {
  66437. return axisModel.get('orient', true) === orient;
  66438. }
  66439. });
  66440. setParallelAxis(axisModels, 'single');
  66441. }
  66442. function setParallelAxis(axisModels, axisDim) {
  66443. // At least use the first parallel axis as the target axis.
  66444. var axisModel = axisModels[0];
  66445. if (!axisModel) {
  66446. return;
  66447. }
  66448. var axisInfo = new DataZoomAxisInfo();
  66449. axisInfo.add(axisModel.componentIndex);
  66450. targetAxisIndexMap.set(axisDim, axisInfo);
  66451. needAuto = false; // Find parallel axes in the same grid.
  66452. if (axisDim === 'x' || axisDim === 'y') {
  66453. var gridModel_1 = axisModel.getReferringComponents('grid', SINGLE_REFERRING).models[0];
  66454. gridModel_1 && each(axisModels, function (axModel) {
  66455. if (axisModel.componentIndex !== axModel.componentIndex && gridModel_1 === axModel.getReferringComponents('grid', SINGLE_REFERRING).models[0]) {
  66456. axisInfo.add(axModel.componentIndex);
  66457. }
  66458. });
  66459. }
  66460. }
  66461. if (needAuto) {
  66462. // If no parallel axis, find the first category axis as default. (Also consider polar).
  66463. each(DATA_ZOOM_AXIS_DIMENSIONS, function (axisDim) {
  66464. if (!needAuto) {
  66465. return;
  66466. }
  66467. var axisModels = ecModel.findComponents({
  66468. mainType: getAxisMainType(axisDim),
  66469. filter: function (axisModel) {
  66470. return axisModel.get('type', true) === 'category';
  66471. }
  66472. });
  66473. if (axisModels[0]) {
  66474. var axisInfo = new DataZoomAxisInfo();
  66475. axisInfo.add(axisModels[0].componentIndex);
  66476. targetAxisIndexMap.set(axisDim, axisInfo);
  66477. needAuto = false;
  66478. }
  66479. }, this);
  66480. }
  66481. };
  66482. DataZoomModel.prototype._makeAutoOrientByTargetAxis = function () {
  66483. var dim; // Find the first axis
  66484. this.eachTargetAxis(function (axisDim) {
  66485. !dim && (dim = axisDim);
  66486. }, this);
  66487. return dim === 'y' ? 'vertical' : 'horizontal';
  66488. };
  66489. DataZoomModel.prototype._setDefaultThrottle = function (inputRawOption) {
  66490. // When first time user set throttle, auto throttle ends.
  66491. if (inputRawOption.hasOwnProperty('throttle')) {
  66492. this._autoThrottle = false;
  66493. }
  66494. if (this._autoThrottle) {
  66495. var globalOption = this.ecModel.option;
  66496. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  66497. }
  66498. };
  66499. DataZoomModel.prototype._updateRangeUse = function (inputRawOption) {
  66500. var rangePropMode = this._rangePropMode;
  66501. var rangeModeInOption = this.get('rangeMode');
  66502. each([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  66503. var percentSpecified = inputRawOption[names[0]] != null;
  66504. var valueSpecified = inputRawOption[names[1]] != null;
  66505. if (percentSpecified && !valueSpecified) {
  66506. rangePropMode[index] = 'percent';
  66507. } else if (!percentSpecified && valueSpecified) {
  66508. rangePropMode[index] = 'value';
  66509. } else if (rangeModeInOption) {
  66510. rangePropMode[index] = rangeModeInOption[index];
  66511. } else if (percentSpecified) {
  66512. // percentSpecified && valueSpecified
  66513. rangePropMode[index] = 'percent';
  66514. } // else remain its original setting.
  66515. });
  66516. };
  66517. DataZoomModel.prototype.noTarget = function () {
  66518. return this._noTarget;
  66519. };
  66520. DataZoomModel.prototype.getFirstTargetAxisModel = function () {
  66521. var firstAxisModel;
  66522. this.eachTargetAxis(function (axisDim, axisIndex) {
  66523. if (firstAxisModel == null) {
  66524. firstAxisModel = this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  66525. }
  66526. }, this);
  66527. return firstAxisModel;
  66528. };
  66529. /**
  66530. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  66531. */
  66532. DataZoomModel.prototype.eachTargetAxis = function (callback, context) {
  66533. this._targetAxisInfoMap.each(function (axisInfo, axisDim) {
  66534. each(axisInfo.indexList, function (axisIndex) {
  66535. callback.call(context, axisDim, axisIndex);
  66536. });
  66537. });
  66538. };
  66539. /**
  66540. * @return If not found, return null/undefined.
  66541. */
  66542. DataZoomModel.prototype.getAxisProxy = function (axisDim, axisIndex) {
  66543. var axisModel = this.getAxisModel(axisDim, axisIndex);
  66544. if (axisModel) {
  66545. return axisModel.__dzAxisProxy;
  66546. }
  66547. };
  66548. /**
  66549. * @return If not found, return null/undefined.
  66550. */
  66551. DataZoomModel.prototype.getAxisModel = function (axisDim, axisIndex) {
  66552. if ("development" !== 'production') {
  66553. assert(axisDim && axisIndex != null);
  66554. }
  66555. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  66556. if (axisInfo && axisInfo.indexMap[axisIndex]) {
  66557. return this.ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  66558. }
  66559. };
  66560. /**
  66561. * If not specified, set to undefined.
  66562. */
  66563. DataZoomModel.prototype.setRawRange = function (opt) {
  66564. var thisOption = this.option;
  66565. var settledOption = this.settledOption;
  66566. each([['start', 'startValue'], ['end', 'endValue']], function (names) {
  66567. // Consider the pair <start, startValue>:
  66568. // If one has value and the other one is `null/undefined`, we both set them
  66569. // to `settledOption`. This strategy enables the feature to clear the original
  66570. // value in `settledOption` to `null/undefined`.
  66571. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  66572. // and keep `settledOption` with the original value. This strategy enables users to
  66573. // only set <end or endValue> but not set <start or startValue> when calling
  66574. // `dispatchAction`.
  66575. // The pair <end, endValue> is treated in the same way.
  66576. if (opt[names[0]] != null || opt[names[1]] != null) {
  66577. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  66578. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  66579. }
  66580. }, this);
  66581. this._updateRangeUse(opt);
  66582. };
  66583. DataZoomModel.prototype.setCalculatedRange = function (opt) {
  66584. var option = this.option;
  66585. each(['start', 'startValue', 'end', 'endValue'], function (name) {
  66586. option[name] = opt[name];
  66587. });
  66588. };
  66589. DataZoomModel.prototype.getPercentRange = function () {
  66590. var axisProxy = this.findRepresentativeAxisProxy();
  66591. if (axisProxy) {
  66592. return axisProxy.getDataPercentWindow();
  66593. }
  66594. };
  66595. /**
  66596. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  66597. *
  66598. * @return [startValue, endValue] value can only be '-' or finite number.
  66599. */
  66600. DataZoomModel.prototype.getValueRange = function (axisDim, axisIndex) {
  66601. if (axisDim == null && axisIndex == null) {
  66602. var axisProxy = this.findRepresentativeAxisProxy();
  66603. if (axisProxy) {
  66604. return axisProxy.getDataValueWindow();
  66605. }
  66606. } else {
  66607. return this.getAxisProxy(axisDim, axisIndex).getDataValueWindow();
  66608. }
  66609. };
  66610. /**
  66611. * @param axisModel If axisModel given, find axisProxy
  66612. * corresponding to the axisModel
  66613. */
  66614. DataZoomModel.prototype.findRepresentativeAxisProxy = function (axisModel) {
  66615. if (axisModel) {
  66616. return axisModel.__dzAxisProxy;
  66617. } // Find the first hosted axisProxy
  66618. var firstProxy;
  66619. var axisDimList = this._targetAxisInfoMap.keys();
  66620. for (var i = 0; i < axisDimList.length; i++) {
  66621. var axisDim = axisDimList[i];
  66622. var axisInfo = this._targetAxisInfoMap.get(axisDim);
  66623. for (var j = 0; j < axisInfo.indexList.length; j++) {
  66624. var proxy = this.getAxisProxy(axisDim, axisInfo.indexList[j]);
  66625. if (proxy.hostedBy(this)) {
  66626. return proxy;
  66627. }
  66628. if (!firstProxy) {
  66629. firstProxy = proxy;
  66630. }
  66631. }
  66632. } // If no hosted proxy found, still need to return a proxy.
  66633. // This case always happens in toolbox dataZoom, where axes are all hosted by
  66634. // other dataZooms.
  66635. return firstProxy;
  66636. };
  66637. DataZoomModel.prototype.getRangePropMode = function () {
  66638. return this._rangePropMode.slice();
  66639. };
  66640. DataZoomModel.prototype.getOrient = function () {
  66641. if ("development" !== 'production') {
  66642. // Should not be called before initialized.
  66643. assert(this._orient);
  66644. }
  66645. return this._orient;
  66646. };
  66647. DataZoomModel.type = 'dataZoom';
  66648. DataZoomModel.dependencies = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series', 'toolbox'];
  66649. DataZoomModel.defaultOption = {
  66650. zlevel: 0,
  66651. z: 4,
  66652. filterMode: 'filter',
  66653. start: 0,
  66654. end: 100
  66655. };
  66656. return DataZoomModel;
  66657. }(ComponentModel);
  66658. /**
  66659. * Retrieve the those raw params from option, which will be cached separately.
  66660. * becasue they will be overwritten by normalized/calculated values in the main
  66661. * process.
  66662. */
  66663. function retrieveRawOption(option) {
  66664. var ret = {};
  66665. each(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  66666. option.hasOwnProperty(name) && (ret[name] = option[name]);
  66667. });
  66668. return ret;
  66669. }
  66670. var SelectDataZoomModel =
  66671. /** @class */
  66672. function (_super) {
  66673. __extends(SelectDataZoomModel, _super);
  66674. function SelectDataZoomModel() {
  66675. var _this = _super !== null && _super.apply(this, arguments) || this;
  66676. _this.type = SelectDataZoomModel.type;
  66677. return _this;
  66678. }
  66679. SelectDataZoomModel.type = 'dataZoom.select';
  66680. return SelectDataZoomModel;
  66681. }(DataZoomModel);
  66682. var DataZoomView =
  66683. /** @class */
  66684. function (_super) {
  66685. __extends(DataZoomView, _super);
  66686. function DataZoomView() {
  66687. var _this = _super !== null && _super.apply(this, arguments) || this;
  66688. _this.type = DataZoomView.type;
  66689. return _this;
  66690. }
  66691. DataZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  66692. this.dataZoomModel = dataZoomModel;
  66693. this.ecModel = ecModel;
  66694. this.api = api;
  66695. };
  66696. DataZoomView.type = 'dataZoom';
  66697. return DataZoomView;
  66698. }(ComponentView);
  66699. var SelectDataZoomView =
  66700. /** @class */
  66701. function (_super) {
  66702. __extends(SelectDataZoomView, _super);
  66703. function SelectDataZoomView() {
  66704. var _this = _super !== null && _super.apply(this, arguments) || this;
  66705. _this.type = SelectDataZoomView.type;
  66706. return _this;
  66707. }
  66708. SelectDataZoomView.type = 'dataZoom.select';
  66709. return SelectDataZoomView;
  66710. }(DataZoomView);
  66711. var each$9 = each;
  66712. var asc$1 = asc;
  66713. /**
  66714. * Operate single axis.
  66715. * One axis can only operated by one axis operator.
  66716. * Different dataZoomModels may be defined to operate the same axis.
  66717. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  66718. * So dataZoomModels share one axisProxy in that case.
  66719. */
  66720. var AxisProxy =
  66721. /** @class */
  66722. function () {
  66723. function AxisProxy(dimName, axisIndex, dataZoomModel, ecModel) {
  66724. this._dimName = dimName;
  66725. this._axisIndex = axisIndex;
  66726. this.ecModel = ecModel;
  66727. this._dataZoomModel = dataZoomModel; // /**
  66728. // * @readOnly
  66729. // * @private
  66730. // */
  66731. // this.hasSeriesStacked;
  66732. }
  66733. /**
  66734. * Whether the axisProxy is hosted by dataZoomModel.
  66735. */
  66736. AxisProxy.prototype.hostedBy = function (dataZoomModel) {
  66737. return this._dataZoomModel === dataZoomModel;
  66738. };
  66739. /**
  66740. * @return Value can only be NaN or finite value.
  66741. */
  66742. AxisProxy.prototype.getDataValueWindow = function () {
  66743. return this._valueWindow.slice();
  66744. };
  66745. /**
  66746. * @return {Array.<number>}
  66747. */
  66748. AxisProxy.prototype.getDataPercentWindow = function () {
  66749. return this._percentWindow.slice();
  66750. };
  66751. AxisProxy.prototype.getTargetSeriesModels = function () {
  66752. var seriesModels = [];
  66753. this.ecModel.eachSeries(function (seriesModel) {
  66754. if (isCoordSupported(seriesModel)) {
  66755. var axisMainType = getAxisMainType(this._dimName);
  66756. var axisModel = seriesModel.getReferringComponents(axisMainType, SINGLE_REFERRING).models[0];
  66757. if (axisModel && this._axisIndex === axisModel.componentIndex) {
  66758. seriesModels.push(seriesModel);
  66759. }
  66760. }
  66761. }, this);
  66762. return seriesModels;
  66763. };
  66764. AxisProxy.prototype.getAxisModel = function () {
  66765. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  66766. };
  66767. AxisProxy.prototype.getMinMaxSpan = function () {
  66768. return clone(this._minMaxSpan);
  66769. };
  66770. /**
  66771. * Only calculate by given range and this._dataExtent, do not change anything.
  66772. */
  66773. AxisProxy.prototype.calculateDataWindow = function (opt) {
  66774. var dataExtent = this._dataExtent;
  66775. var axisModel = this.getAxisModel();
  66776. var scale = axisModel.axis.scale;
  66777. var rangePropMode = this._dataZoomModel.getRangePropMode();
  66778. var percentExtent = [0, 100];
  66779. var percentWindow = [];
  66780. var valueWindow = [];
  66781. var hasPropModeValue;
  66782. each$9(['start', 'end'], function (prop, idx) {
  66783. var boundPercent = opt[prop];
  66784. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  66785. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  66786. // but not min/max of axis, which will be calculated by data window then).
  66787. // The former one is suitable for cases that a dataZoom component controls multiple
  66788. // axes with different unit or extent, and the latter one is suitable for accurate
  66789. // zoom by pixel (e.g., in dataZoomSelect).
  66790. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  66791. // only when setOption or dispatchAction, otherwise it remains its original value.
  66792. // (Why not only record `percentProp` and always map to `valueProp`? Because
  66793. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  66794. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  66795. // data extent. All of values that are overflow the `dataExtent` will be calculated
  66796. // to percent '100%').
  66797. if (rangePropMode[idx] === 'percent') {
  66798. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  66799. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  66800. } else {
  66801. hasPropModeValue = true;
  66802. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  66803. // This calculation can not be inversed, because all of values that
  66804. // are overflow the `dataExtent` will be calculated to percent '100%'
  66805. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  66806. } // valueWindow[idx] = round(boundValue);
  66807. // percentWindow[idx] = round(boundPercent);
  66808. valueWindow[idx] = boundValue;
  66809. percentWindow[idx] = boundPercent;
  66810. });
  66811. asc$1(valueWindow);
  66812. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  66813. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  66814. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  66815. // where API is able to initialize/modify the window size even though `zoomLock`
  66816. // specified.
  66817. var spans = this._minMaxSpan;
  66818. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  66819. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  66820. var suffix = toValue ? 'Span' : 'ValueSpan';
  66821. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  66822. for (var i = 0; i < 2; i++) {
  66823. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  66824. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  66825. }
  66826. }
  66827. return {
  66828. valueWindow: valueWindow,
  66829. percentWindow: percentWindow
  66830. };
  66831. };
  66832. /**
  66833. * Notice: reset should not be called before series.restoreData() called,
  66834. * so it is recommanded to be called in "process stage" but not "model init
  66835. * stage".
  66836. */
  66837. AxisProxy.prototype.reset = function (dataZoomModel) {
  66838. if (dataZoomModel !== this._dataZoomModel) {
  66839. return;
  66840. }
  66841. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  66842. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // this.hasSeriesStacked = false;
  66843. // each(targetSeries, function (series) {
  66844. // let data = series.getData();
  66845. // let dataDim = data.mapDimension(this._dimName);
  66846. // let stackedDimension = data.getCalculationInfo('stackedDimension');
  66847. // if (stackedDimension && stackedDimension === dataDim) {
  66848. // this.hasSeriesStacked = true;
  66849. // }
  66850. // }, this);
  66851. // `calculateDataWindow` uses min/maxSpan.
  66852. this._updateMinMaxSpan();
  66853. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  66854. this._valueWindow = dataWindow.valueWindow;
  66855. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  66856. this._setAxisModel();
  66857. };
  66858. AxisProxy.prototype.filterData = function (dataZoomModel, api) {
  66859. if (dataZoomModel !== this._dataZoomModel) {
  66860. return;
  66861. }
  66862. var axisDim = this._dimName;
  66863. var seriesModels = this.getTargetSeriesModels();
  66864. var filterMode = dataZoomModel.get('filterMode');
  66865. var valueWindow = this._valueWindow;
  66866. if (filterMode === 'none') {
  66867. return;
  66868. } // FIXME
  66869. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  66870. // with NaN data, NaN will be filtered and stack will be wrong.
  66871. // So we need to force the mode to be set empty.
  66872. // In fect, it is not a big deal that do not support filterMode-'filter'
  66873. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  66874. // selection" some day, which might need "adapt to data extent on the
  66875. // otherAxis", which is disabled by filterMode-'empty'.
  66876. // But currently, stack has been fixed to based on value but not index,
  66877. // so this is not an issue any more.
  66878. // let otherAxisModel = this.getOtherAxisModel();
  66879. // if (dataZoomModel.get('$fromToolbox')
  66880. // && otherAxisModel
  66881. // && otherAxisModel.hasSeriesStacked
  66882. // ) {
  66883. // filterMode = 'empty';
  66884. // }
  66885. // TODO
  66886. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  66887. each$9(seriesModels, function (seriesModel) {
  66888. var seriesData = seriesModel.getData();
  66889. var dataDims = seriesData.mapDimensionsAll(axisDim);
  66890. if (!dataDims.length) {
  66891. return;
  66892. }
  66893. if (filterMode === 'weakFilter') {
  66894. seriesData.filterSelf(function (dataIndex) {
  66895. var leftOut;
  66896. var rightOut;
  66897. var hasValue;
  66898. for (var i = 0; i < dataDims.length; i++) {
  66899. var value = seriesData.get(dataDims[i], dataIndex);
  66900. var thisHasValue = !isNaN(value);
  66901. var thisLeftOut = value < valueWindow[0];
  66902. var thisRightOut = value > valueWindow[1];
  66903. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  66904. return true;
  66905. }
  66906. thisHasValue && (hasValue = true);
  66907. thisLeftOut && (leftOut = true);
  66908. thisRightOut && (rightOut = true);
  66909. } // If both left out and right out, do not filter.
  66910. return hasValue && leftOut && rightOut;
  66911. });
  66912. } else {
  66913. each$9(dataDims, function (dim) {
  66914. if (filterMode === 'empty') {
  66915. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  66916. return !isInWindow(value) ? NaN : value;
  66917. }));
  66918. } else {
  66919. var range = {};
  66920. range[dim] = valueWindow; // console.time('select');
  66921. seriesData.selectRange(range); // console.timeEnd('select');
  66922. }
  66923. });
  66924. }
  66925. each$9(dataDims, function (dim) {
  66926. seriesData.setApproximateExtent(valueWindow, dim);
  66927. });
  66928. });
  66929. function isInWindow(value) {
  66930. return value >= valueWindow[0] && value <= valueWindow[1];
  66931. }
  66932. };
  66933. AxisProxy.prototype._updateMinMaxSpan = function () {
  66934. var minMaxSpan = this._minMaxSpan = {};
  66935. var dataZoomModel = this._dataZoomModel;
  66936. var dataExtent = this._dataExtent;
  66937. each$9(['min', 'max'], function (minMax) {
  66938. var percentSpan = dataZoomModel.get(minMax + 'Span');
  66939. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  66940. valueSpan != null && (valueSpan = this.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  66941. if (valueSpan != null) {
  66942. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  66943. } else if (percentSpan != null) {
  66944. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  66945. }
  66946. minMaxSpan[minMax + 'Span'] = percentSpan;
  66947. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  66948. }, this);
  66949. };
  66950. AxisProxy.prototype._setAxisModel = function () {
  66951. var axisModel = this.getAxisModel();
  66952. var percentWindow = this._percentWindow;
  66953. var valueWindow = this._valueWindow;
  66954. if (!percentWindow) {
  66955. return;
  66956. } // [0, 500]: arbitrary value, guess axis extent.
  66957. var precision = getPixelPrecision(valueWindow, [0, 500]);
  66958. precision = Math.min(precision, 20); // For value axis, if min/max/scale are not set, we just use the extent obtained
  66959. // by series data, which may be a little different from the extent calculated by
  66960. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  66961. // little when zooming. So it will not be fixed until some users require it strongly.
  66962. var rawExtentInfo = axisModel.axis.scale.rawExtentInfo;
  66963. if (percentWindow[0] !== 0) {
  66964. rawExtentInfo.setDeterminedMinMax('min', +valueWindow[0].toFixed(precision));
  66965. }
  66966. if (percentWindow[1] !== 100) {
  66967. rawExtentInfo.setDeterminedMinMax('max', +valueWindow[1].toFixed(precision));
  66968. }
  66969. rawExtentInfo.freeze();
  66970. };
  66971. return AxisProxy;
  66972. }();
  66973. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  66974. var dataExtent = [Infinity, -Infinity];
  66975. each$9(seriesModels, function (seriesModel) {
  66976. unionAxisExtentFromData(dataExtent, seriesModel.getData(), axisDim);
  66977. }); // It is important to get "consistent" extent when more then one axes is
  66978. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  66979. // when zooming. But it is difficult to know what is "consistent", considering
  66980. // axes have different type or even different meanings (For example, two
  66981. // time axes are used to compare data of the same date in different years).
  66982. // So basically dataZoom just obtains extent by series.data (in category axis
  66983. // extent can be obtained from axis.data).
  66984. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  66985. // consistent.
  66986. var axisModel = axisProxy.getAxisModel();
  66987. var rawExtentResult = ensureScaleRawExtentInfo(axisModel.axis.scale, axisModel, dataExtent).calculate();
  66988. return [rawExtentResult.min, rawExtentResult.max];
  66989. }
  66990. var dataZoomProcessor = {
  66991. // `dataZoomProcessor` will only be performed in needed series. Consider if
  66992. // there is a line series and a pie series, it is better not to update the
  66993. // line series if only pie series is needed to be updated.
  66994. getTargetSeries: function (ecModel) {
  66995. function eachAxisModel(cb) {
  66996. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  66997. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  66998. var axisModel = ecModel.getComponent(getAxisMainType(axisDim), axisIndex);
  66999. cb(axisDim, axisIndex, axisModel, dataZoomModel);
  67000. });
  67001. });
  67002. } // FIXME: it brings side-effect to `getTargetSeries`.
  67003. // Prepare axis proxies.
  67004. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  67005. // dispose all last axis proxy, in case that some axis are deleted.
  67006. axisModel.__dzAxisProxy = null;
  67007. });
  67008. var proxyList = [];
  67009. eachAxisModel(function (axisDim, axisIndex, axisModel, dataZoomModel) {
  67010. // Different dataZooms may constrol the same axis. In that case,
  67011. // an axisProxy serves both of them.
  67012. if (!axisModel.__dzAxisProxy) {
  67013. // Use the first dataZoomModel as the main model of axisProxy.
  67014. axisModel.__dzAxisProxy = new AxisProxy(axisDim, axisIndex, dataZoomModel, ecModel);
  67015. proxyList.push(axisModel.__dzAxisProxy);
  67016. }
  67017. });
  67018. var seriesModelMap = createHashMap();
  67019. each(proxyList, function (axisProxy) {
  67020. each(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  67021. seriesModelMap.set(seriesModel.uid, seriesModel);
  67022. });
  67023. });
  67024. return seriesModelMap;
  67025. },
  67026. // Consider appendData, where filter should be performed. Because data process is
  67027. // in block mode currently, it is not need to worry about that the overallProgress
  67028. // execute every frame.
  67029. overallReset: function (ecModel, api) {
  67030. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  67031. // We calculate window and reset axis here but not in model
  67032. // init stage and not after action dispatch handler, because
  67033. // reset should be called after seriesData.restoreData.
  67034. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  67035. dataZoomModel.getAxisProxy(axisDim, axisIndex).reset(dataZoomModel);
  67036. }); // Caution: data zoom filtering is order sensitive when using
  67037. // percent range and no min/max/scale set on axis.
  67038. // For example, we have dataZoom definition:
  67039. // [
  67040. // {xAxisIndex: 0, start: 30, end: 70},
  67041. // {yAxisIndex: 0, start: 20, end: 80}
  67042. // ]
  67043. // In this case, [20, 80] of y-dataZoom should be based on data
  67044. // that have filtered by x-dataZoom using range of [30, 70],
  67045. // but should not be based on full raw data. Thus sliding
  67046. // x-dataZoom will change both ranges of xAxis and yAxis,
  67047. // while sliding y-dataZoom will only change the range of yAxis.
  67048. // So we should filter x-axis after reset x-axis immediately,
  67049. // and then reset y-axis and filter y-axis.
  67050. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  67051. dataZoomModel.getAxisProxy(axisDim, axisIndex).filterData(dataZoomModel, api);
  67052. });
  67053. });
  67054. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  67055. // Fullfill all of the range props so that user
  67056. // is able to get them from chart.getOption().
  67057. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  67058. if (axisProxy) {
  67059. var percentRange = axisProxy.getDataPercentWindow();
  67060. var valueRange = axisProxy.getDataValueWindow();
  67061. dataZoomModel.setCalculatedRange({
  67062. start: percentRange[0],
  67063. end: percentRange[1],
  67064. startValue: valueRange[0],
  67065. endValue: valueRange[1]
  67066. });
  67067. }
  67068. });
  67069. }
  67070. };
  67071. function installDataZoomAction(registers) {
  67072. registers.registerAction('dataZoom', function (payload, ecModel) {
  67073. var effectedModels = findEffectedDataZooms(ecModel, payload);
  67074. each(effectedModels, function (dataZoomModel) {
  67075. dataZoomModel.setRawRange({
  67076. start: payload.start,
  67077. end: payload.end,
  67078. startValue: payload.startValue,
  67079. endValue: payload.endValue
  67080. });
  67081. });
  67082. });
  67083. }
  67084. var installed = false;
  67085. function installCommon(registers) {
  67086. if (installed) {
  67087. return;
  67088. }
  67089. installed = true;
  67090. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, dataZoomProcessor);
  67091. installDataZoomAction(registers);
  67092. registers.registerSubTypeDefaulter('dataZoom', function () {
  67093. // Default 'slider' when no type specified.
  67094. return 'slider';
  67095. });
  67096. }
  67097. function install$y(registers) {
  67098. registers.registerComponentModel(SelectDataZoomModel);
  67099. registers.registerComponentView(SelectDataZoomView);
  67100. installCommon(registers);
  67101. }
  67102. /*
  67103. * Licensed to the Apache Software Foundation (ASF) under one
  67104. * or more contributor license agreements. See the NOTICE file
  67105. * distributed with this work for additional information
  67106. * regarding copyright ownership. The ASF licenses this file
  67107. * to you under the Apache License, Version 2.0 (the
  67108. * "License"); you may not use this file except in compliance
  67109. * with the License. You may obtain a copy of the License at
  67110. *
  67111. * http://www.apache.org/licenses/LICENSE-2.0
  67112. *
  67113. * Unless required by applicable law or agreed to in writing,
  67114. * software distributed under the License is distributed on an
  67115. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67116. * KIND, either express or implied. See the License for the
  67117. * specific language governing permissions and limitations
  67118. * under the License.
  67119. */
  67120. /**
  67121. * AUTO-GENERATED FILE. DO NOT MODIFY.
  67122. */
  67123. var ToolboxFeature =
  67124. /** @class */
  67125. function () {
  67126. function ToolboxFeature() {}
  67127. return ToolboxFeature;
  67128. }();
  67129. var features = {};
  67130. function registerFeature(name, ctor) {
  67131. features[name] = ctor;
  67132. }
  67133. function getFeature(name) {
  67134. return features[name];
  67135. }
  67136. var ToolboxModel =
  67137. /** @class */
  67138. function (_super) {
  67139. __extends(ToolboxModel, _super);
  67140. function ToolboxModel() {
  67141. var _this = _super !== null && _super.apply(this, arguments) || this;
  67142. _this.type = ToolboxModel.type;
  67143. return _this;
  67144. }
  67145. ToolboxModel.prototype.optionUpdated = function () {
  67146. _super.prototype.optionUpdated.apply(this, arguments);
  67147. var ecModel = this.ecModel;
  67148. each(this.option.feature, function (featureOpt, featureName) {
  67149. var Feature = getFeature(featureName);
  67150. if (Feature) {
  67151. if (Feature.getDefaultOption) {
  67152. Feature.defaultOption = Feature.getDefaultOption(ecModel);
  67153. }
  67154. merge(featureOpt, Feature.defaultOption);
  67155. }
  67156. });
  67157. };
  67158. ToolboxModel.type = 'toolbox';
  67159. ToolboxModel.layoutMode = {
  67160. type: 'box',
  67161. ignoreSize: true
  67162. };
  67163. ToolboxModel.defaultOption = {
  67164. show: true,
  67165. z: 6,
  67166. zlevel: 0,
  67167. orient: 'horizontal',
  67168. left: 'right',
  67169. top: 'top',
  67170. // right
  67171. // bottom
  67172. backgroundColor: 'transparent',
  67173. borderColor: '#ccc',
  67174. borderRadius: 0,
  67175. borderWidth: 0,
  67176. padding: 5,
  67177. itemSize: 15,
  67178. itemGap: 8,
  67179. showTitle: true,
  67180. iconStyle: {
  67181. borderColor: '#666',
  67182. color: 'none'
  67183. },
  67184. emphasis: {
  67185. iconStyle: {
  67186. borderColor: '#3E98C5'
  67187. }
  67188. },
  67189. // textStyle: {},
  67190. // feature
  67191. tooltip: {
  67192. show: false
  67193. }
  67194. };
  67195. return ToolboxModel;
  67196. }(ComponentModel);
  67197. /**
  67198. * Layout list like component.
  67199. * It will box layout each items in group of component and then position the whole group in the viewport
  67200. * @param {module:zrender/group/Group} group
  67201. * @param {module:echarts/model/Component} componentModel
  67202. * @param {module:echarts/ExtensionAPI}
  67203. */
  67204. function layout$3(group, componentModel, api) {
  67205. var boxLayoutParams = componentModel.getBoxLayoutParams();
  67206. var padding = componentModel.get('padding');
  67207. var viewportSize = {
  67208. width: api.getWidth(),
  67209. height: api.getHeight()
  67210. };
  67211. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  67212. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  67213. positionElement(group, boxLayoutParams, viewportSize, padding);
  67214. }
  67215. function makeBackground(rect, componentModel) {
  67216. var padding = normalizeCssArray$1(componentModel.get('padding'));
  67217. var style = componentModel.getItemStyle(['color', 'opacity']);
  67218. style.fill = componentModel.get('backgroundColor');
  67219. rect = new Rect({
  67220. shape: {
  67221. x: rect.x - padding[3],
  67222. y: rect.y - padding[0],
  67223. width: rect.width + padding[1] + padding[3],
  67224. height: rect.height + padding[0] + padding[2],
  67225. r: componentModel.get('borderRadius')
  67226. },
  67227. style: style,
  67228. silent: true,
  67229. z2: -1
  67230. }); // FIXME
  67231. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  67232. // and background rect when setting like `left: 0`, `top: 0`.
  67233. // graphic.subPixelOptimizeRect(rect);
  67234. return rect;
  67235. }
  67236. var ToolboxView =
  67237. /** @class */
  67238. function (_super) {
  67239. __extends(ToolboxView, _super);
  67240. function ToolboxView() {
  67241. return _super !== null && _super.apply(this, arguments) || this;
  67242. }
  67243. ToolboxView.prototype.render = function (toolboxModel, ecModel, api, payload) {
  67244. var group = this.group;
  67245. group.removeAll();
  67246. if (!toolboxModel.get('show')) {
  67247. return;
  67248. }
  67249. var itemSize = +toolboxModel.get('itemSize');
  67250. var featureOpts = toolboxModel.get('feature') || {};
  67251. var features = this._features || (this._features = {});
  67252. var featureNames = [];
  67253. each(featureOpts, function (opt, name) {
  67254. featureNames.push(name);
  67255. });
  67256. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  67257. this._featureNames = featureNames;
  67258. function processFeature(newIndex, oldIndex) {
  67259. var featureName = featureNames[newIndex];
  67260. var oldName = featureNames[oldIndex];
  67261. var featureOpt = featureOpts[featureName];
  67262. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  67263. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  67264. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  67265. featureOpt.title = payload.newTitle;
  67266. }
  67267. if (featureName && !oldName) {
  67268. // Create
  67269. if (isUserFeatureName(featureName)) {
  67270. feature = {
  67271. onclick: featureModel.option.onclick,
  67272. featureName: featureName
  67273. };
  67274. } else {
  67275. var Feature = getFeature(featureName);
  67276. if (!Feature) {
  67277. return;
  67278. }
  67279. feature = new Feature();
  67280. }
  67281. features[featureName] = feature;
  67282. } else {
  67283. feature = features[oldName]; // If feature does not exsit.
  67284. if (!feature) {
  67285. return;
  67286. }
  67287. }
  67288. feature.uid = getUID('toolbox-feature');
  67289. feature.model = featureModel;
  67290. feature.ecModel = ecModel;
  67291. feature.api = api;
  67292. if (feature instanceof ToolboxFeature) {
  67293. if (!featureName && oldName) {
  67294. feature.dispose && feature.dispose(ecModel, api);
  67295. return;
  67296. }
  67297. if (!featureModel.get('show') || feature.unusable) {
  67298. feature.remove && feature.remove(ecModel, api);
  67299. return;
  67300. }
  67301. }
  67302. createIconPaths(featureModel, feature, featureName);
  67303. featureModel.setIconStatus = function (iconName, status) {
  67304. var option = this.option;
  67305. var iconPaths = this.iconPaths;
  67306. option.iconStatus = option.iconStatus || {};
  67307. option.iconStatus[iconName] = status;
  67308. if (iconPaths[iconName]) {
  67309. (status === 'emphasis' ? enterEmphasis : leaveEmphasis)(iconPaths[iconName]);
  67310. }
  67311. };
  67312. if (feature instanceof ToolboxFeature) {
  67313. if (feature.render) {
  67314. feature.render(featureModel, ecModel, api, payload);
  67315. }
  67316. }
  67317. }
  67318. function createIconPaths(featureModel, feature, featureName) {
  67319. var iconStyleModel = featureModel.getModel('iconStyle');
  67320. var iconStyleEmphasisModel = featureModel.getModel(['emphasis', 'iconStyle']); // If one feature has mutiple icon. they are orginaized as
  67321. // {
  67322. // icon: {
  67323. // foo: '',
  67324. // bar: ''
  67325. // },
  67326. // title: {
  67327. // foo: '',
  67328. // bar: ''
  67329. // }
  67330. // }
  67331. var icons = feature instanceof ToolboxFeature && feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  67332. var titles = featureModel.get('title') || {};
  67333. var iconsMap;
  67334. var titlesMap;
  67335. if (typeof icons === 'string') {
  67336. iconsMap = {};
  67337. iconsMap[featureName] = icons;
  67338. } else {
  67339. iconsMap = icons;
  67340. }
  67341. if (typeof titles === 'string') {
  67342. titlesMap = {};
  67343. titlesMap[featureName] = titles;
  67344. } else {
  67345. titlesMap = titles;
  67346. }
  67347. var iconPaths = featureModel.iconPaths = {};
  67348. each(iconsMap, function (iconStr, iconName) {
  67349. var path = createIcon(iconStr, {}, {
  67350. x: -itemSize / 2,
  67351. y: -itemSize / 2,
  67352. width: itemSize,
  67353. height: itemSize
  67354. }); // TODO handling image
  67355. path.setStyle(iconStyleModel.getItemStyle());
  67356. var pathEmphasisState = path.ensureState('emphasis');
  67357. pathEmphasisState.style = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  67358. var textContent = new ZRText({
  67359. style: {
  67360. text: titlesMap[iconName],
  67361. align: iconStyleEmphasisModel.get('textAlign'),
  67362. borderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  67363. padding: iconStyleEmphasisModel.get('textPadding'),
  67364. fill: null
  67365. },
  67366. ignore: true
  67367. });
  67368. path.setTextContent(textContent);
  67369. var tooltipModel = toolboxModel.getModel('tooltip');
  67370. if (tooltipModel && tooltipModel.get('show')) {
  67371. path.tooltip = extend({
  67372. content: titlesMap[iconName],
  67373. formatter: tooltipModel.get('formatter', true) || function () {
  67374. return titlesMap[iconName];
  67375. },
  67376. formatterParams: {
  67377. componentType: 'toolbox',
  67378. name: iconName,
  67379. title: titlesMap[iconName],
  67380. $vars: ['name', 'title']
  67381. },
  67382. position: tooltipModel.get('position', true) || 'bottom'
  67383. }, tooltipModel.option);
  67384. } // graphic.enableHoverEmphasis(path);
  67385. path.__title = titlesMap[iconName];
  67386. path.on('mouseover', function () {
  67387. // Should not reuse above hoverStyle, which might be modified.
  67388. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  67389. var defaultTextPosition = toolboxModel.get('orient') === 'vertical' ? toolboxModel.get('right') == null ? 'right' : 'left' : toolboxModel.get('bottom') == null ? 'bottom' : 'top';
  67390. textContent.setStyle({
  67391. fill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  67392. backgroundColor: iconStyleEmphasisModel.get('textBackgroundColor')
  67393. });
  67394. path.setTextConfig({
  67395. position: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  67396. });
  67397. textContent.ignore = !toolboxModel.get('showTitle'); // Use enterEmphasis and leaveEmphasis provide by ec.
  67398. // There are flags managed by the echarts.
  67399. enterEmphasis(this);
  67400. }).on('mouseout', function () {
  67401. if (featureModel.get(['iconStatus', iconName]) !== 'emphasis') {
  67402. leaveEmphasis(this);
  67403. }
  67404. textContent.hide();
  67405. });
  67406. (featureModel.get(['iconStatus', iconName]) === 'emphasis' ? enterEmphasis : leaveEmphasis)(path);
  67407. group.add(path);
  67408. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  67409. iconPaths[iconName] = path;
  67410. });
  67411. }
  67412. layout$3(group, toolboxModel, api); // Render background after group is layout
  67413. // FIXME
  67414. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  67415. group.eachChild(function (icon) {
  67416. var titleText = icon.__title; // const hoverStyle = icon.hoverStyle;
  67417. // TODO simplify code?
  67418. var emphasisState = icon.ensureState('emphasis');
  67419. var emphasisTextConfig = emphasisState.textConfig || (emphasisState.textConfig = {});
  67420. var textContent = icon.getTextContent();
  67421. var emphasisTextState = textContent && textContent.states.emphasis; // May be background element
  67422. if (emphasisTextState && !isFunction(emphasisTextState) && titleText) {
  67423. var emphasisTextStyle = emphasisTextState.style || (emphasisTextState.style = {});
  67424. var rect = getBoundingRect(titleText, ZRText.makeFont(emphasisTextStyle));
  67425. var offsetX = icon.x + group.x;
  67426. var offsetY = icon.y + group.y + itemSize;
  67427. var needPutOnTop = false;
  67428. if (offsetY + rect.height > api.getHeight()) {
  67429. emphasisTextConfig.position = 'top';
  67430. needPutOnTop = true;
  67431. }
  67432. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 8;
  67433. if (offsetX + rect.width / 2 > api.getWidth()) {
  67434. emphasisTextConfig.position = ['100%', topOffset];
  67435. emphasisTextStyle.align = 'right';
  67436. } else if (offsetX - rect.width / 2 < 0) {
  67437. emphasisTextConfig.position = [0, topOffset];
  67438. emphasisTextStyle.align = 'left';
  67439. }
  67440. }
  67441. });
  67442. };
  67443. ToolboxView.prototype.updateView = function (toolboxModel, ecModel, api, payload) {
  67444. each(this._features, function (feature) {
  67445. feature instanceof ToolboxFeature && feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  67446. });
  67447. }; // updateLayout(toolboxModel, ecModel, api, payload) {
  67448. // zrUtil.each(this._features, function (feature) {
  67449. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  67450. // });
  67451. // },
  67452. ToolboxView.prototype.remove = function (ecModel, api) {
  67453. each(this._features, function (feature) {
  67454. feature instanceof ToolboxFeature && feature.remove && feature.remove(ecModel, api);
  67455. });
  67456. this.group.removeAll();
  67457. };
  67458. ToolboxView.prototype.dispose = function (ecModel, api) {
  67459. each(this._features, function (feature) {
  67460. feature instanceof ToolboxFeature && feature.dispose && feature.dispose(ecModel, api);
  67461. });
  67462. };
  67463. ToolboxView.type = 'toolbox';
  67464. return ToolboxView;
  67465. }(ComponentView);
  67466. function isUserFeatureName(featureName) {
  67467. return featureName.indexOf('my') === 0;
  67468. }
  67469. var SaveAsImage =
  67470. /** @class */
  67471. function (_super) {
  67472. __extends(SaveAsImage, _super);
  67473. function SaveAsImage() {
  67474. return _super !== null && _super.apply(this, arguments) || this;
  67475. }
  67476. SaveAsImage.prototype.onclick = function (ecModel, api) {
  67477. var model = this.model;
  67478. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  67479. var isSvg = api.getZr().painter.getType() === 'svg';
  67480. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  67481. var url = api.getConnectedDataURL({
  67482. type: type,
  67483. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  67484. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  67485. excludeComponents: model.get('excludeComponents'),
  67486. pixelRatio: model.get('pixelRatio')
  67487. }); // Chrome, Firefox, New Edge
  67488. if (typeof MouseEvent === 'function' && (env.browser.newEdge || !env.browser.ie && !env.browser.edge)) {
  67489. var $a = document.createElement('a');
  67490. $a.download = title + '.' + type;
  67491. $a.target = '_blank';
  67492. $a.href = url;
  67493. var evt = new MouseEvent('click', {
  67494. // some micro front-end framework, window maybe is a Proxy
  67495. view: document.defaultView,
  67496. bubbles: true,
  67497. cancelable: false
  67498. });
  67499. $a.dispatchEvent(evt);
  67500. } // IE or old Edge
  67501. else {
  67502. if (window.navigator.msSaveOrOpenBlob || isSvg) {
  67503. var parts = url.split(','); // data:[<mime type>][;charset=<charset>][;base64],<encoded data>
  67504. var base64Encoded = parts[0].indexOf('base64') > -1;
  67505. var bstr = isSvg // should decode the svg data uri first
  67506. ? decodeURIComponent(parts[1]) : parts[1]; // only `atob` when the data uri is encoded with base64
  67507. // otherwise, like `svg` data uri exported by zrender,
  67508. // there will be an error, for it's not encoded with base64.
  67509. // (just a url-encoded string through `encodeURIComponent`)
  67510. base64Encoded && (bstr = atob(bstr));
  67511. var filename = title + '.' + type;
  67512. if (window.navigator.msSaveOrOpenBlob) {
  67513. var n = bstr.length;
  67514. var u8arr = new Uint8Array(n);
  67515. while (n--) {
  67516. u8arr[n] = bstr.charCodeAt(n);
  67517. }
  67518. var blob = new Blob([u8arr]);
  67519. window.navigator.msSaveOrOpenBlob(blob, filename);
  67520. } else {
  67521. var frame = document.createElement('iframe');
  67522. document.body.appendChild(frame);
  67523. var cw = frame.contentWindow;
  67524. var doc = cw.document;
  67525. doc.open('image/svg+xml', 'replace');
  67526. doc.write(bstr);
  67527. doc.close();
  67528. cw.focus();
  67529. doc.execCommand('SaveAs', true, filename);
  67530. document.body.removeChild(frame);
  67531. }
  67532. } else {
  67533. var lang = model.get('lang');
  67534. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang && lang[0] || '') + '" />' + '</body>';
  67535. var tab = window.open();
  67536. tab.document.write(html);
  67537. tab.document.title = title;
  67538. }
  67539. }
  67540. };
  67541. SaveAsImage.getDefaultOption = function (ecModel) {
  67542. var defaultOption = {
  67543. show: true,
  67544. 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',
  67545. title: ecModel.getLocale(['toolbox', 'saveAsImage', 'title']),
  67546. type: 'png',
  67547. // Default use option.backgroundColor
  67548. // backgroundColor: '#fff',
  67549. connectedBackgroundColor: '#fff',
  67550. name: '',
  67551. excludeComponents: ['toolbox'],
  67552. // use current pixel ratio of device by default
  67553. // pixelRatio: 1,
  67554. lang: ecModel.getLocale(['toolbox', 'saveAsImage', 'lang'])
  67555. };
  67556. return defaultOption;
  67557. };
  67558. return SaveAsImage;
  67559. }(ToolboxFeature);
  67560. SaveAsImage.prototype.unusable = !env.canvasSupported;
  67561. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  67562. var radioTypes = [['line', 'bar'], ['stack']];
  67563. var MagicType =
  67564. /** @class */
  67565. function (_super) {
  67566. __extends(MagicType, _super);
  67567. function MagicType() {
  67568. return _super !== null && _super.apply(this, arguments) || this;
  67569. }
  67570. MagicType.prototype.getIcons = function () {
  67571. var model = this.model;
  67572. var availableIcons = model.get('icon');
  67573. var icons = {};
  67574. each(model.get('type'), function (type) {
  67575. if (availableIcons[type]) {
  67576. icons[type] = availableIcons[type];
  67577. }
  67578. });
  67579. return icons;
  67580. };
  67581. MagicType.getDefaultOption = function (ecModel) {
  67582. var defaultOption = {
  67583. show: true,
  67584. type: [],
  67585. // Icon group
  67586. icon: {
  67587. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  67588. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  67589. // eslint-disable-next-line
  67590. 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
  67591. },
  67592. // `line`, `bar`, `stack`, `tiled`
  67593. title: ecModel.getLocale(['toolbox', 'magicType', 'title']),
  67594. option: {},
  67595. seriesIndex: {}
  67596. };
  67597. return defaultOption;
  67598. };
  67599. MagicType.prototype.onclick = function (ecModel, api, type) {
  67600. var model = this.model;
  67601. var seriesIndex = model.get(['seriesIndex', type]); // Not supported magicType
  67602. if (!seriesOptGenreator[type]) {
  67603. return;
  67604. }
  67605. var newOption = {
  67606. series: []
  67607. };
  67608. var generateNewSeriesTypes = function (seriesModel) {
  67609. var seriesType = seriesModel.subType;
  67610. var seriesId = seriesModel.id;
  67611. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  67612. if (newSeriesOpt) {
  67613. // PENDING If merge original option?
  67614. defaults(newSeriesOpt, seriesModel.option);
  67615. newOption.series.push(newSeriesOpt);
  67616. } // Modify boundaryGap
  67617. var coordSys = seriesModel.coordinateSystem;
  67618. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  67619. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  67620. if (categoryAxis) {
  67621. var axisDim = categoryAxis.dim;
  67622. var axisType = axisDim + 'Axis';
  67623. var axisModel = seriesModel.getReferringComponents(axisType, SINGLE_REFERRING).models[0];
  67624. var axisIndex = axisModel.componentIndex;
  67625. newOption[axisType] = newOption[axisType] || [];
  67626. for (var i = 0; i <= axisIndex; i++) {
  67627. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  67628. }
  67629. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  67630. }
  67631. }
  67632. };
  67633. each(radioTypes, function (radio) {
  67634. if (indexOf(radio, type) >= 0) {
  67635. each(radio, function (item) {
  67636. model.setIconStatus(item, 'normal');
  67637. });
  67638. }
  67639. });
  67640. model.setIconStatus(type, 'emphasis');
  67641. ecModel.eachComponent({
  67642. mainType: 'series',
  67643. query: seriesIndex == null ? null : {
  67644. seriesIndex: seriesIndex
  67645. }
  67646. }, generateNewSeriesTypes);
  67647. var newTitle; // Change title of stack
  67648. if (type === 'stack') {
  67649. // use titles in model instead of ecModel
  67650. // as stack and tiled appears in pair, just flip them
  67651. // no need of checking stack state
  67652. newTitle = merge({
  67653. stack: model.option.title.tiled,
  67654. tiled: model.option.title.stack
  67655. }, model.option.title);
  67656. }
  67657. api.dispatchAction({
  67658. type: 'changeMagicType',
  67659. currentType: type,
  67660. newOption: newOption,
  67661. newTitle: newTitle,
  67662. featureName: 'magicType'
  67663. });
  67664. };
  67665. return MagicType;
  67666. }(ToolboxFeature);
  67667. var seriesOptGenreator = {
  67668. 'line': function (seriesType, seriesId, seriesModel, model) {
  67669. if (seriesType === 'bar') {
  67670. return merge({
  67671. id: seriesId,
  67672. type: 'line',
  67673. // Preserve data related option
  67674. data: seriesModel.get('data'),
  67675. stack: seriesModel.get('stack'),
  67676. markPoint: seriesModel.get('markPoint'),
  67677. markLine: seriesModel.get('markLine')
  67678. }, model.get(['option', 'line']) || {}, true);
  67679. }
  67680. },
  67681. 'bar': function (seriesType, seriesId, seriesModel, model) {
  67682. if (seriesType === 'line') {
  67683. return merge({
  67684. id: seriesId,
  67685. type: 'bar',
  67686. // Preserve data related option
  67687. data: seriesModel.get('data'),
  67688. stack: seriesModel.get('stack'),
  67689. markPoint: seriesModel.get('markPoint'),
  67690. markLine: seriesModel.get('markLine')
  67691. }, model.get(['option', 'bar']) || {}, true);
  67692. }
  67693. },
  67694. 'stack': function (seriesType, seriesId, seriesModel, model) {
  67695. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  67696. if (seriesType === 'line' || seriesType === 'bar') {
  67697. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  67698. return merge({
  67699. id: seriesId,
  67700. stack: isStack ? '' : INNER_STACK_KEYWORD
  67701. }, model.get(['option', 'stack']) || {}, true);
  67702. }
  67703. }
  67704. }; // TODO: SELF REGISTERED.
  67705. registerAction({
  67706. type: 'changeMagicType',
  67707. event: 'magicTypeChanged',
  67708. update: 'prepareAndUpdate'
  67709. }, function (payload, ecModel) {
  67710. ecModel.mergeOption(payload.newOption);
  67711. });
  67712. var BLOCK_SPLITER = new Array(60).join('-');
  67713. var ITEM_SPLITER = '\t';
  67714. /**
  67715. * Group series into two types
  67716. * 1. on category axis, like line, bar
  67717. * 2. others, like scatter, pie
  67718. */
  67719. function groupSeries(ecModel) {
  67720. var seriesGroupByCategoryAxis = {};
  67721. var otherSeries = [];
  67722. var meta = [];
  67723. ecModel.eachRawSeries(function (seriesModel) {
  67724. var coordSys = seriesModel.coordinateSystem;
  67725. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  67726. // TODO: TYPE Consider polar? Include polar may increase unecessary bundle size.
  67727. var baseAxis = coordSys.getBaseAxis();
  67728. if (baseAxis.type === 'category') {
  67729. var key = baseAxis.dim + '_' + baseAxis.index;
  67730. if (!seriesGroupByCategoryAxis[key]) {
  67731. seriesGroupByCategoryAxis[key] = {
  67732. categoryAxis: baseAxis,
  67733. valueAxis: coordSys.getOtherAxis(baseAxis),
  67734. series: []
  67735. };
  67736. meta.push({
  67737. axisDim: baseAxis.dim,
  67738. axisIndex: baseAxis.index
  67739. });
  67740. }
  67741. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  67742. } else {
  67743. otherSeries.push(seriesModel);
  67744. }
  67745. } else {
  67746. otherSeries.push(seriesModel);
  67747. }
  67748. });
  67749. return {
  67750. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  67751. other: otherSeries,
  67752. meta: meta
  67753. };
  67754. }
  67755. /**
  67756. * Assemble content of series on cateogory axis
  67757. * @inner
  67758. */
  67759. function assembleSeriesWithCategoryAxis(groups) {
  67760. var tables = [];
  67761. each(groups, function (group, key) {
  67762. var categoryAxis = group.categoryAxis;
  67763. var valueAxis = group.valueAxis;
  67764. var valueAxisDim = valueAxis.dim;
  67765. var headers = [' '].concat(map(group.series, function (series) {
  67766. return series.name;
  67767. })); // @ts-ignore TODO Polar
  67768. var columns = [categoryAxis.model.getCategories()];
  67769. each(group.series, function (series) {
  67770. var rawData = series.getRawData();
  67771. columns.push(series.getRawData().mapArray(rawData.mapDimension(valueAxisDim), function (val) {
  67772. return val;
  67773. }));
  67774. }); // Assemble table content
  67775. var lines = [headers.join(ITEM_SPLITER)];
  67776. for (var i = 0; i < columns[0].length; i++) {
  67777. var items = [];
  67778. for (var j = 0; j < columns.length; j++) {
  67779. items.push(columns[j][i]);
  67780. }
  67781. lines.push(items.join(ITEM_SPLITER));
  67782. }
  67783. tables.push(lines.join('\n'));
  67784. });
  67785. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  67786. }
  67787. /**
  67788. * Assemble content of other series
  67789. */
  67790. function assembleOtherSeries(series) {
  67791. return map(series, function (series) {
  67792. var data = series.getRawData();
  67793. var lines = [series.name];
  67794. var vals = [];
  67795. data.each(data.dimensions, function () {
  67796. var argLen = arguments.length;
  67797. var dataIndex = arguments[argLen - 1];
  67798. var name = data.getName(dataIndex);
  67799. for (var i = 0; i < argLen - 1; i++) {
  67800. vals[i] = arguments[i];
  67801. }
  67802. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  67803. });
  67804. return lines.join('\n');
  67805. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  67806. }
  67807. function getContentFromModel(ecModel) {
  67808. var result = groupSeries(ecModel);
  67809. return {
  67810. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  67811. return !!str.replace(/[\n\t\s]/g, '');
  67812. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  67813. meta: result.meta
  67814. };
  67815. }
  67816. function trim$1(str) {
  67817. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  67818. }
  67819. /**
  67820. * If a block is tsv format
  67821. */
  67822. function isTSVFormat(block) {
  67823. // Simple method to find out if a block is tsv format
  67824. var firstLine = block.slice(0, block.indexOf('\n'));
  67825. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  67826. return true;
  67827. }
  67828. }
  67829. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  67830. /**
  67831. * @param {string} tsv
  67832. * @return {Object}
  67833. */
  67834. function parseTSVContents(tsv) {
  67835. var tsvLines = tsv.split(/\n+/g);
  67836. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  67837. var categories = [];
  67838. var series = map(headers, function (header) {
  67839. return {
  67840. name: header,
  67841. data: []
  67842. };
  67843. });
  67844. for (var i = 0; i < tsvLines.length; i++) {
  67845. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  67846. categories.push(items.shift());
  67847. for (var j = 0; j < items.length; j++) {
  67848. series[j] && (series[j].data[i] = items[j]);
  67849. }
  67850. }
  67851. return {
  67852. series: series,
  67853. categories: categories
  67854. };
  67855. }
  67856. function parseListContents(str) {
  67857. var lines = str.split(/\n+/g);
  67858. var seriesName = trim$1(lines.shift());
  67859. var data = [];
  67860. for (var i = 0; i < lines.length; i++) {
  67861. // if line is empty, ignore it.
  67862. // there is a case that a user forgot to delete `\n`.
  67863. var line = trim$1(lines[i]);
  67864. if (!line) {
  67865. continue;
  67866. }
  67867. var items = line.split(itemSplitRegex);
  67868. var name_1 = '';
  67869. var value = void 0;
  67870. var hasName = false;
  67871. if (isNaN(items[0])) {
  67872. // First item is name
  67873. hasName = true;
  67874. name_1 = items[0];
  67875. items = items.slice(1);
  67876. data[i] = {
  67877. name: name_1,
  67878. value: []
  67879. };
  67880. value = data[i].value;
  67881. } else {
  67882. value = data[i] = [];
  67883. }
  67884. for (var j = 0; j < items.length; j++) {
  67885. value.push(+items[j]);
  67886. }
  67887. if (value.length === 1) {
  67888. hasName ? data[i].value = value[0] : data[i] = value[0];
  67889. }
  67890. }
  67891. return {
  67892. name: seriesName,
  67893. data: data
  67894. };
  67895. }
  67896. function parseContents(str, blockMetaList) {
  67897. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  67898. var newOption = {
  67899. series: []
  67900. };
  67901. each(blocks, function (block, idx) {
  67902. if (isTSVFormat(block)) {
  67903. var result = parseTSVContents(block);
  67904. var blockMeta = blockMetaList[idx];
  67905. var axisKey = blockMeta.axisDim + 'Axis';
  67906. if (blockMeta) {
  67907. newOption[axisKey] = newOption[axisKey] || [];
  67908. newOption[axisKey][blockMeta.axisIndex] = {
  67909. data: result.categories
  67910. };
  67911. newOption.series = newOption.series.concat(result.series);
  67912. }
  67913. } else {
  67914. var result = parseListContents(block);
  67915. newOption.series.push(result);
  67916. }
  67917. });
  67918. return newOption;
  67919. }
  67920. var DataView =
  67921. /** @class */
  67922. function (_super) {
  67923. __extends(DataView, _super);
  67924. function DataView() {
  67925. return _super !== null && _super.apply(this, arguments) || this;
  67926. }
  67927. DataView.prototype.onclick = function (ecModel, api) {
  67928. var container = api.getDom();
  67929. var model = this.model;
  67930. if (this._dom) {
  67931. container.removeChild(this._dom);
  67932. }
  67933. var root = document.createElement('div');
  67934. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  67935. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  67936. var header = document.createElement('h4');
  67937. var lang = model.get('lang') || [];
  67938. header.innerHTML = lang[0] || model.get('title');
  67939. header.style.cssText = 'margin: 10px 20px;';
  67940. header.style.color = model.get('textColor');
  67941. var viewMain = document.createElement('div');
  67942. var textarea = document.createElement('textarea');
  67943. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  67944. var optionToContent = model.get('optionToContent');
  67945. var contentToOption = model.get('contentToOption');
  67946. var result = getContentFromModel(ecModel);
  67947. if (typeof optionToContent === 'function') {
  67948. var htmlOrDom = optionToContent(api.getOption());
  67949. if (typeof htmlOrDom === 'string') {
  67950. viewMain.innerHTML = htmlOrDom;
  67951. } else if (isDom(htmlOrDom)) {
  67952. viewMain.appendChild(htmlOrDom);
  67953. }
  67954. } else {
  67955. // Use default textarea
  67956. viewMain.appendChild(textarea);
  67957. textarea.readOnly = model.get('readOnly');
  67958. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  67959. textarea.style.color = model.get('textColor');
  67960. textarea.style.borderColor = model.get('textareaBorderColor');
  67961. textarea.style.backgroundColor = model.get('textareaColor');
  67962. textarea.value = result.value;
  67963. }
  67964. var blockMetaList = result.meta;
  67965. var buttonContainer = document.createElement('div');
  67966. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  67967. var buttonStyle = 'float:right;margin-right:20px;border:none;' + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  67968. var closeButton = document.createElement('div');
  67969. var refreshButton = document.createElement('div');
  67970. buttonStyle += ';background-color:' + model.get('buttonColor');
  67971. buttonStyle += ';color:' + model.get('buttonTextColor');
  67972. var self = this;
  67973. function close() {
  67974. container.removeChild(root);
  67975. self._dom = null;
  67976. }
  67977. addEventListener(closeButton, 'click', close);
  67978. addEventListener(refreshButton, 'click', function () {
  67979. if (contentToOption == null && optionToContent != null || contentToOption != null && optionToContent == null) {
  67980. if ("development" !== 'production') {
  67981. // eslint-disable-next-line
  67982. console.warn('It seems you have just provided one of `contentToOption` and `optionToContent` functions but missed the other one. Data change is ignored.');
  67983. }
  67984. close();
  67985. return;
  67986. }
  67987. var newOption;
  67988. try {
  67989. if (typeof contentToOption === 'function') {
  67990. newOption = contentToOption(viewMain, api.getOption());
  67991. } else {
  67992. newOption = parseContents(textarea.value, blockMetaList);
  67993. }
  67994. } catch (e) {
  67995. close();
  67996. throw new Error('Data view format error ' + e);
  67997. }
  67998. if (newOption) {
  67999. api.dispatchAction({
  68000. type: 'changeDataView',
  68001. newOption: newOption
  68002. });
  68003. }
  68004. close();
  68005. });
  68006. closeButton.innerHTML = lang[1];
  68007. refreshButton.innerHTML = lang[2];
  68008. refreshButton.style.cssText = buttonStyle;
  68009. closeButton.style.cssText = buttonStyle;
  68010. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  68011. buttonContainer.appendChild(closeButton);
  68012. root.appendChild(header);
  68013. root.appendChild(viewMain);
  68014. root.appendChild(buttonContainer);
  68015. viewMain.style.height = container.clientHeight - 80 + 'px';
  68016. container.appendChild(root);
  68017. this._dom = root;
  68018. };
  68019. DataView.prototype.remove = function (ecModel, api) {
  68020. this._dom && api.getDom().removeChild(this._dom);
  68021. };
  68022. DataView.prototype.dispose = function (ecModel, api) {
  68023. this.remove(ecModel, api);
  68024. };
  68025. DataView.getDefaultOption = function (ecModel) {
  68026. var defaultOption = {
  68027. show: true,
  68028. readOnly: false,
  68029. optionToContent: null,
  68030. contentToOption: null,
  68031. // eslint-disable-next-line
  68032. 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',
  68033. title: ecModel.getLocale(['toolbox', 'dataView', 'title']),
  68034. lang: ecModel.getLocale(['toolbox', 'dataView', 'lang']),
  68035. backgroundColor: '#fff',
  68036. textColor: '#000',
  68037. textareaColor: '#fff',
  68038. textareaBorderColor: '#333',
  68039. buttonColor: '#c23531',
  68040. buttonTextColor: '#fff'
  68041. };
  68042. return defaultOption;
  68043. };
  68044. return DataView;
  68045. }(ToolboxFeature);
  68046. /**
  68047. * @inner
  68048. */
  68049. function tryMergeDataOption(newData, originalData) {
  68050. return map(newData, function (newVal, idx) {
  68051. var original = originalData && originalData[idx];
  68052. if (isObject(original) && !isArray(original)) {
  68053. var newValIsObject = isObject(newVal) && !isArray(newVal);
  68054. if (!newValIsObject) {
  68055. newVal = {
  68056. value: newVal
  68057. };
  68058. } // original data has name but new data has no name
  68059. var shouldDeleteName = original.name != null && newVal.name == null; // Original data has option
  68060. newVal = defaults(newVal, original);
  68061. shouldDeleteName && delete newVal.name;
  68062. return newVal;
  68063. } else {
  68064. return newVal;
  68065. }
  68066. });
  68067. } // TODO: SELF REGISTERED.
  68068. registerAction({
  68069. type: 'changeDataView',
  68070. event: 'dataViewChanged',
  68071. update: 'prepareAndUpdate'
  68072. }, function (payload, ecModel) {
  68073. var newSeriesOptList = [];
  68074. each(payload.newOption.series, function (seriesOpt) {
  68075. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  68076. if (!seriesModel) {
  68077. // New created series
  68078. // Geuss the series type
  68079. newSeriesOptList.push(extend({
  68080. // Default is scatter
  68081. type: 'scatter'
  68082. }, seriesOpt));
  68083. } else {
  68084. var originalData = seriesModel.get('data');
  68085. newSeriesOptList.push({
  68086. name: seriesOpt.name,
  68087. data: tryMergeDataOption(seriesOpt.data, originalData)
  68088. });
  68089. }
  68090. });
  68091. ecModel.mergeOption(defaults({
  68092. series: newSeriesOptList
  68093. }, payload.newOption));
  68094. });
  68095. var each$a = each;
  68096. var inner$h = makeInner();
  68097. /**
  68098. * @param ecModel
  68099. * @param newSnapshot key is dataZoomId
  68100. */
  68101. function push(ecModel, newSnapshot) {
  68102. var storedSnapshots = getStoreSnapshots(ecModel); // If previous dataZoom can not be found,
  68103. // complete an range with current range.
  68104. each$a(newSnapshot, function (batchItem, dataZoomId) {
  68105. var i = storedSnapshots.length - 1;
  68106. for (; i >= 0; i--) {
  68107. var snapshot = storedSnapshots[i];
  68108. if (snapshot[dataZoomId]) {
  68109. break;
  68110. }
  68111. }
  68112. if (i < 0) {
  68113. // No origin range set, create one by current range.
  68114. var dataZoomModel = ecModel.queryComponents({
  68115. mainType: 'dataZoom',
  68116. subType: 'select',
  68117. id: dataZoomId
  68118. })[0];
  68119. if (dataZoomModel) {
  68120. var percentRange = dataZoomModel.getPercentRange();
  68121. storedSnapshots[0][dataZoomId] = {
  68122. dataZoomId: dataZoomId,
  68123. start: percentRange[0],
  68124. end: percentRange[1]
  68125. };
  68126. }
  68127. }
  68128. });
  68129. storedSnapshots.push(newSnapshot);
  68130. }
  68131. function pop(ecModel) {
  68132. var storedSnapshots = getStoreSnapshots(ecModel);
  68133. var head = storedSnapshots[storedSnapshots.length - 1];
  68134. storedSnapshots.length > 1 && storedSnapshots.pop(); // Find top for all dataZoom.
  68135. var snapshot = {};
  68136. each$a(head, function (batchItem, dataZoomId) {
  68137. for (var i = storedSnapshots.length - 1; i >= 0; i--) {
  68138. batchItem = storedSnapshots[i][dataZoomId];
  68139. if (batchItem) {
  68140. snapshot[dataZoomId] = batchItem;
  68141. break;
  68142. }
  68143. }
  68144. });
  68145. return snapshot;
  68146. }
  68147. function clear$1(ecModel) {
  68148. inner$h(ecModel).snapshots = null;
  68149. }
  68150. function count(ecModel) {
  68151. return getStoreSnapshots(ecModel).length;
  68152. }
  68153. /**
  68154. * History length of each dataZoom may be different.
  68155. * this._history[0] is used to store origin range.
  68156. */
  68157. function getStoreSnapshots(ecModel) {
  68158. var store = inner$h(ecModel);
  68159. if (!store.snapshots) {
  68160. store.snapshots = [{}];
  68161. }
  68162. return store.snapshots;
  68163. }
  68164. var RestoreOption =
  68165. /** @class */
  68166. function (_super) {
  68167. __extends(RestoreOption, _super);
  68168. function RestoreOption() {
  68169. return _super !== null && _super.apply(this, arguments) || this;
  68170. }
  68171. RestoreOption.prototype.onclick = function (ecModel, api) {
  68172. clear$1(ecModel);
  68173. api.dispatchAction({
  68174. type: 'restore',
  68175. from: this.uid
  68176. });
  68177. };
  68178. RestoreOption.getDefaultOption = function (ecModel) {
  68179. var defaultOption = {
  68180. show: true,
  68181. // eslint-disable-next-line
  68182. 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',
  68183. title: ecModel.getLocale(['toolbox', 'restore', 'title'])
  68184. };
  68185. return defaultOption;
  68186. };
  68187. return RestoreOption;
  68188. }(ToolboxFeature); // TODO: SELF REGISTERED.
  68189. registerAction({
  68190. type: 'restore',
  68191. event: 'restore',
  68192. update: 'prepareAndUpdate'
  68193. }, function (payload, ecModel) {
  68194. ecModel.resetOption('recreate');
  68195. });
  68196. var COORD_CONVERTS = ['dataToPoint', 'pointToData']; // FIXME
  68197. // how to genarialize to more coordinate systems.
  68198. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  68199. var BrushTargetManager =
  68200. /** @class */
  68201. function () {
  68202. /**
  68203. * @param finder contains Index/Id/Name of xAxis/yAxis/geo/grid
  68204. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  68205. * @param opt.include include coordinate system types.
  68206. */
  68207. function BrushTargetManager(finder, ecModel, opt) {
  68208. var _this = this;
  68209. this._targetInfoList = [];
  68210. var foundCpts = parseFinder$1(ecModel, finder);
  68211. each(targetInfoBuilders, function (builder, type) {
  68212. if (!opt || !opt.include || indexOf(opt.include, type) >= 0) {
  68213. builder(foundCpts, _this._targetInfoList);
  68214. }
  68215. });
  68216. }
  68217. BrushTargetManager.prototype.setOutputRanges = function (areas, ecModel) {
  68218. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  68219. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  68220. if (!area.coordRange) {
  68221. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  68222. // rebuild range by coordRange accrately, which may bring trouble when
  68223. // brushing only one item. So we use __rangeOffset to rebuilding range
  68224. // by coordRange. And this it only used in brush component so it is no
  68225. // need to be adapted to coordRanges.
  68226. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  68227. area.__rangeOffset = {
  68228. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  68229. xyMinMax: result.xyMinMax
  68230. };
  68231. }
  68232. });
  68233. return areas;
  68234. };
  68235. BrushTargetManager.prototype.matchOutputRanges = function (areas, ecModel, cb) {
  68236. each(areas, function (area) {
  68237. var targetInfo = this.findTargetInfo(area, ecModel);
  68238. if (targetInfo && targetInfo !== true) {
  68239. each(targetInfo.coordSyses, function (coordSys) {
  68240. var result = coordConvert[area.brushType](1, coordSys, area.range);
  68241. cb(area, result.values, coordSys, ecModel);
  68242. });
  68243. }
  68244. }, this);
  68245. };
  68246. /**
  68247. * the `areas` is `BrushModel.areas`.
  68248. * Called in layout stage.
  68249. * convert `area.coordRange` to global range and set panelId to `area.range`.
  68250. */
  68251. BrushTargetManager.prototype.setInputRanges = function (areas, ecModel) {
  68252. each(areas, function (area) {
  68253. var targetInfo = this.findTargetInfo(area, ecModel);
  68254. if ("development" !== 'production') {
  68255. assert(!targetInfo || targetInfo === true || area.coordRange, 'coordRange must be specified when coord index specified.');
  68256. assert(!targetInfo || targetInfo !== true || area.range, 'range must be specified in global brush.');
  68257. }
  68258. area.range = area.range || []; // convert coordRange to global range and set panelId.
  68259. if (targetInfo && targetInfo !== true) {
  68260. area.panelId = targetInfo.panelId; // (1) area.range shoule always be calculate from coordRange but does
  68261. // not keep its original value, for the sake of the dataZoom scenario,
  68262. // where area.coordRange remains unchanged but area.range may be changed.
  68263. // (2) Only support converting one coordRange to pixel range in brush
  68264. // component. So do not consider `coordRanges`.
  68265. // (3) About __rangeOffset, see comment above.
  68266. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  68267. var rangeOffset = area.__rangeOffset;
  68268. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  68269. }
  68270. }, this);
  68271. };
  68272. BrushTargetManager.prototype.makePanelOpts = function (api, getDefaultBrushType) {
  68273. return map(this._targetInfoList, function (targetInfo) {
  68274. var rect = targetInfo.getPanelRect();
  68275. return {
  68276. panelId: targetInfo.panelId,
  68277. defaultBrushType: getDefaultBrushType ? getDefaultBrushType(targetInfo) : null,
  68278. clipPath: makeRectPanelClipPath(rect),
  68279. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  68280. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  68281. };
  68282. });
  68283. };
  68284. BrushTargetManager.prototype.controlSeries = function (area, seriesModel, ecModel) {
  68285. // Check whether area is bound in coord, and series do not belong to that coord.
  68286. // If do not do this check, some brush (like lineX) will controll all axes.
  68287. var targetInfo = this.findTargetInfo(area, ecModel);
  68288. return targetInfo === true || targetInfo && indexOf(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  68289. };
  68290. /**
  68291. * If return Object, a coord found.
  68292. * If reutrn true, global found.
  68293. * Otherwise nothing found.
  68294. */
  68295. BrushTargetManager.prototype.findTargetInfo = function (area, ecModel) {
  68296. var targetInfoList = this._targetInfoList;
  68297. var foundCpts = parseFinder$1(ecModel, area);
  68298. for (var i = 0; i < targetInfoList.length; i++) {
  68299. var targetInfo = targetInfoList[i];
  68300. var areaPanelId = area.panelId;
  68301. if (areaPanelId) {
  68302. if (targetInfo.panelId === areaPanelId) {
  68303. return targetInfo;
  68304. }
  68305. } else {
  68306. for (var j = 0; j < targetInfoMatchers.length; j++) {
  68307. if (targetInfoMatchers[j](foundCpts, targetInfo)) {
  68308. return targetInfo;
  68309. }
  68310. }
  68311. }
  68312. }
  68313. return true;
  68314. };
  68315. return BrushTargetManager;
  68316. }();
  68317. function formatMinMax(minMax) {
  68318. minMax[0] > minMax[1] && minMax.reverse();
  68319. return minMax;
  68320. }
  68321. function parseFinder$1(ecModel, finder) {
  68322. return parseFinder(ecModel, finder, {
  68323. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  68324. });
  68325. }
  68326. var targetInfoBuilders = {
  68327. grid: function (foundCpts, targetInfoList) {
  68328. var xAxisModels = foundCpts.xAxisModels;
  68329. var yAxisModels = foundCpts.yAxisModels;
  68330. var gridModels = foundCpts.gridModels; // Remove duplicated.
  68331. var gridModelMap = createHashMap();
  68332. var xAxesHas = {};
  68333. var yAxesHas = {};
  68334. if (!xAxisModels && !yAxisModels && !gridModels) {
  68335. return;
  68336. }
  68337. each(xAxisModels, function (axisModel) {
  68338. var gridModel = axisModel.axis.grid.model;
  68339. gridModelMap.set(gridModel.id, gridModel);
  68340. xAxesHas[gridModel.id] = true;
  68341. });
  68342. each(yAxisModels, function (axisModel) {
  68343. var gridModel = axisModel.axis.grid.model;
  68344. gridModelMap.set(gridModel.id, gridModel);
  68345. yAxesHas[gridModel.id] = true;
  68346. });
  68347. each(gridModels, function (gridModel) {
  68348. gridModelMap.set(gridModel.id, gridModel);
  68349. xAxesHas[gridModel.id] = true;
  68350. yAxesHas[gridModel.id] = true;
  68351. });
  68352. gridModelMap.each(function (gridModel) {
  68353. var grid = gridModel.coordinateSystem;
  68354. var cartesians = [];
  68355. each(grid.getCartesians(), function (cartesian, index) {
  68356. if (indexOf(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  68357. cartesians.push(cartesian);
  68358. }
  68359. });
  68360. targetInfoList.push({
  68361. panelId: 'grid--' + gridModel.id,
  68362. gridModel: gridModel,
  68363. coordSysModel: gridModel,
  68364. // Use the first one as the representitive coordSys.
  68365. coordSys: cartesians[0],
  68366. coordSyses: cartesians,
  68367. getPanelRect: panelRectBuilders.grid,
  68368. xAxisDeclared: xAxesHas[gridModel.id],
  68369. yAxisDeclared: yAxesHas[gridModel.id]
  68370. });
  68371. });
  68372. },
  68373. geo: function (foundCpts, targetInfoList) {
  68374. each(foundCpts.geoModels, function (geoModel) {
  68375. var coordSys = geoModel.coordinateSystem;
  68376. targetInfoList.push({
  68377. panelId: 'geo--' + geoModel.id,
  68378. geoModel: geoModel,
  68379. coordSysModel: geoModel,
  68380. coordSys: coordSys,
  68381. coordSyses: [coordSys],
  68382. getPanelRect: panelRectBuilders.geo
  68383. });
  68384. });
  68385. }
  68386. };
  68387. var targetInfoMatchers = [// grid
  68388. function (foundCpts, targetInfo) {
  68389. var xAxisModel = foundCpts.xAxisModel;
  68390. var yAxisModel = foundCpts.yAxisModel;
  68391. var gridModel = foundCpts.gridModel;
  68392. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  68393. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  68394. return gridModel && gridModel === targetInfo.gridModel;
  68395. }, // geo
  68396. function (foundCpts, targetInfo) {
  68397. var geoModel = foundCpts.geoModel;
  68398. return geoModel && geoModel === targetInfo.geoModel;
  68399. }];
  68400. var panelRectBuilders = {
  68401. grid: function () {
  68402. // grid is not Transformable.
  68403. return this.coordSys.master.getRect().clone();
  68404. },
  68405. geo: function () {
  68406. var coordSys = this.coordSys;
  68407. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  68408. rect.applyTransform(getTransform(coordSys));
  68409. return rect;
  68410. }
  68411. };
  68412. var coordConvert = {
  68413. lineX: curry(axisConvert, 0),
  68414. lineY: curry(axisConvert, 1),
  68415. rect: function (to, coordSys, rangeOrCoordRange) {
  68416. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  68417. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  68418. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  68419. return {
  68420. values: values,
  68421. xyMinMax: values
  68422. };
  68423. },
  68424. polygon: function (to, coordSys, rangeOrCoordRange) {
  68425. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  68426. var values = map(rangeOrCoordRange, function (item) {
  68427. var p = coordSys[COORD_CONVERTS[to]](item);
  68428. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  68429. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  68430. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  68431. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  68432. return p;
  68433. });
  68434. return {
  68435. values: values,
  68436. xyMinMax: xyMinMax
  68437. };
  68438. }
  68439. };
  68440. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  68441. if ("development" !== 'production') {
  68442. assert(coordSys.type === 'cartesian2d', 'lineX/lineY brush is available only in cartesian2d.');
  68443. }
  68444. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  68445. var values = formatMinMax(map([0, 1], function (i) {
  68446. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i])) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  68447. }));
  68448. var xyMinMax = [];
  68449. xyMinMax[axisNameIndex] = values;
  68450. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  68451. return {
  68452. values: values,
  68453. xyMinMax: xyMinMax
  68454. };
  68455. }
  68456. var diffProcessor = {
  68457. lineX: curry(axisDiffProcessor, 0),
  68458. lineY: curry(axisDiffProcessor, 1),
  68459. rect: function (values, refer, scales) {
  68460. 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]]];
  68461. },
  68462. polygon: function (values, refer, scales) {
  68463. return map(values, function (item, idx) {
  68464. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  68465. });
  68466. }
  68467. };
  68468. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  68469. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  68470. } // We have to process scale caused by dataZoom manually,
  68471. // although it might be not accurate.
  68472. // Return [0~1, 0~1]
  68473. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  68474. var sizeCurr = getSize(xyMinMaxCurr);
  68475. var sizeOrigin = getSize(xyMinMaxOrigin);
  68476. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  68477. isNaN(scales[0]) && (scales[0] = 1);
  68478. isNaN(scales[1]) && (scales[1] = 1);
  68479. return scales;
  68480. }
  68481. function getSize(xyMinMax) {
  68482. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  68483. }
  68484. var each$b = each;
  68485. var DATA_ZOOM_ID_BASE = makeInternalComponentId('toolbox-dataZoom_');
  68486. var DataZoomFeature =
  68487. /** @class */
  68488. function (_super) {
  68489. __extends(DataZoomFeature, _super);
  68490. function DataZoomFeature() {
  68491. return _super !== null && _super.apply(this, arguments) || this;
  68492. }
  68493. DataZoomFeature.prototype.render = function (featureModel, ecModel, api, payload) {
  68494. if (!this._brushController) {
  68495. this._brushController = new BrushController(api.getZr());
  68496. this._brushController.on('brush', bind(this._onBrush, this)).mount();
  68497. }
  68498. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  68499. updateBackBtnStatus(featureModel, ecModel);
  68500. };
  68501. DataZoomFeature.prototype.onclick = function (ecModel, api, type) {
  68502. handlers$1[type].call(this);
  68503. };
  68504. DataZoomFeature.prototype.remove = function (ecModel, api) {
  68505. this._brushController && this._brushController.unmount();
  68506. };
  68507. DataZoomFeature.prototype.dispose = function (ecModel, api) {
  68508. this._brushController && this._brushController.dispose();
  68509. };
  68510. DataZoomFeature.prototype._onBrush = function (eventParam) {
  68511. var areas = eventParam.areas;
  68512. if (!eventParam.isEnd || !areas.length) {
  68513. return;
  68514. }
  68515. var snapshot = {};
  68516. var ecModel = this.ecModel;
  68517. this._brushController.updateCovers([]); // remove cover
  68518. var brushTargetManager = new BrushTargetManager(makeAxisFinder(this.model), ecModel, {
  68519. include: ['grid']
  68520. });
  68521. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  68522. if (coordSys.type !== 'cartesian2d') {
  68523. return;
  68524. }
  68525. var brushType = area.brushType;
  68526. if (brushType === 'rect') {
  68527. setBatch('x', coordSys, coordRange[0]);
  68528. setBatch('y', coordSys, coordRange[1]);
  68529. } else {
  68530. setBatch({
  68531. lineX: 'x',
  68532. lineY: 'y'
  68533. }[brushType], coordSys, coordRange);
  68534. }
  68535. });
  68536. push(ecModel, snapshot);
  68537. this._dispatchZoomAction(snapshot);
  68538. function setBatch(dimName, coordSys, minMax) {
  68539. var axis = coordSys.getAxis(dimName);
  68540. var axisModel = axis.model;
  68541. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  68542. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  68543. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  68544. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  68545. }
  68546. dataZoomModel && (snapshot[dataZoomModel.id] = {
  68547. dataZoomId: dataZoomModel.id,
  68548. startValue: minMax[0],
  68549. endValue: minMax[1]
  68550. });
  68551. }
  68552. function findDataZoom(dimName, axisModel, ecModel) {
  68553. var found;
  68554. ecModel.eachComponent({
  68555. mainType: 'dataZoom',
  68556. subType: 'select'
  68557. }, function (dzModel) {
  68558. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  68559. has && (found = dzModel);
  68560. });
  68561. return found;
  68562. }
  68563. };
  68564. DataZoomFeature.prototype._dispatchZoomAction = function (snapshot) {
  68565. var batch = []; // Convert from hash map to array.
  68566. each$b(snapshot, function (batchItem, dataZoomId) {
  68567. batch.push(clone(batchItem));
  68568. });
  68569. batch.length && this.api.dispatchAction({
  68570. type: 'dataZoom',
  68571. from: this.uid,
  68572. batch: batch
  68573. });
  68574. };
  68575. DataZoomFeature.getDefaultOption = function (ecModel) {
  68576. var defaultOption = {
  68577. show: true,
  68578. filterMode: 'filter',
  68579. // Icon group
  68580. icon: {
  68581. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  68582. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  68583. },
  68584. // `zoom`, `back`
  68585. title: ecModel.getLocale(['toolbox', 'dataZoom', 'title']),
  68586. brushStyle: {
  68587. borderWidth: 0,
  68588. color: 'rgba(210,219,238,0.2)'
  68589. }
  68590. };
  68591. return defaultOption;
  68592. };
  68593. return DataZoomFeature;
  68594. }(ToolboxFeature);
  68595. var handlers$1 = {
  68596. zoom: function () {
  68597. var nextActive = !this._isZoomActive;
  68598. this.api.dispatchAction({
  68599. type: 'takeGlobalCursor',
  68600. key: 'dataZoomSelect',
  68601. dataZoomSelectActive: nextActive
  68602. });
  68603. },
  68604. back: function () {
  68605. this._dispatchZoomAction(pop(this.ecModel));
  68606. }
  68607. };
  68608. function makeAxisFinder(dzFeatureModel) {
  68609. var setting = {
  68610. xAxisIndex: dzFeatureModel.get('xAxisIndex', true),
  68611. yAxisIndex: dzFeatureModel.get('yAxisIndex', true),
  68612. xAxisId: dzFeatureModel.get('xAxisId', true),
  68613. yAxisId: dzFeatureModel.get('yAxisId', true)
  68614. }; // If both `xAxisIndex` `xAxisId` not set, it means 'all'.
  68615. // If both `yAxisIndex` `yAxisId` not set, it means 'all'.
  68616. // Some old cases set like this below to close yAxis control but leave xAxis control:
  68617. // `{ feature: { dataZoom: { yAxisIndex: false } }`.
  68618. if (setting.xAxisIndex == null && setting.xAxisId == null) {
  68619. setting.xAxisIndex = 'all';
  68620. }
  68621. if (setting.yAxisIndex == null && setting.yAxisId == null) {
  68622. setting.yAxisIndex = 'all';
  68623. }
  68624. return setting;
  68625. }
  68626. function updateBackBtnStatus(featureModel, ecModel) {
  68627. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  68628. }
  68629. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  68630. var zoomActive = view._isZoomActive;
  68631. if (payload && payload.type === 'takeGlobalCursor') {
  68632. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  68633. }
  68634. view._isZoomActive = zoomActive;
  68635. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  68636. var brushTargetManager = new BrushTargetManager(makeAxisFinder(featureModel), ecModel, {
  68637. include: ['grid']
  68638. });
  68639. var panels = brushTargetManager.makePanelOpts(api, function (targetInfo) {
  68640. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  68641. });
  68642. view._brushController.setPanels(panels).enableBrush(zoomActive && panels.length ? {
  68643. brushType: 'auto',
  68644. brushStyle: featureModel.getModel('brushStyle').getItemStyle()
  68645. } : false);
  68646. }
  68647. registerInternalOptionCreator('dataZoom', function (ecModel) {
  68648. var toolboxModel = ecModel.getComponent('toolbox', 0);
  68649. if (!toolboxModel) {
  68650. return;
  68651. }
  68652. var dzFeatureModel = toolboxModel.getModel(['feature', 'dataZoom']);
  68653. var dzOptions = [];
  68654. var finder = makeAxisFinder(dzFeatureModel);
  68655. var finderResult = parseFinder(ecModel, finder);
  68656. each$b(finderResult.xAxisModels, function (axisModel) {
  68657. return buildInternalOptions(axisModel, 'xAxis', 'xAxisIndex');
  68658. });
  68659. each$b(finderResult.yAxisModels, function (axisModel) {
  68660. return buildInternalOptions(axisModel, 'yAxis', 'yAxisIndex');
  68661. });
  68662. function buildInternalOptions(axisModel, axisMainType, axisIndexPropName) {
  68663. var axisIndex = axisModel.componentIndex;
  68664. var newOpt = {
  68665. type: 'select',
  68666. $fromToolbox: true,
  68667. // Default to be filter
  68668. filterMode: dzFeatureModel.get('filterMode', true) || 'filter',
  68669. // Id for merge mapping.
  68670. id: DATA_ZOOM_ID_BASE + axisMainType + axisIndex
  68671. };
  68672. newOpt[axisIndexPropName] = axisIndex;
  68673. dzOptions.push(newOpt);
  68674. }
  68675. return dzOptions;
  68676. });
  68677. function install$z(registers) {
  68678. registers.registerComponentModel(ToolboxModel);
  68679. registers.registerComponentView(ToolboxView);
  68680. registerFeature('saveAsImage', SaveAsImage);
  68681. registerFeature('magicType', MagicType);
  68682. registerFeature('dataView', DataView);
  68683. registerFeature('dataZoom', DataZoomFeature);
  68684. registerFeature('restore', RestoreOption);
  68685. use(install$y);
  68686. }
  68687. var TooltipModel =
  68688. /** @class */
  68689. function (_super) {
  68690. __extends(TooltipModel, _super);
  68691. function TooltipModel() {
  68692. var _this = _super !== null && _super.apply(this, arguments) || this;
  68693. _this.type = TooltipModel.type;
  68694. return _this;
  68695. }
  68696. TooltipModel.type = 'tooltip';
  68697. TooltipModel.dependencies = ['axisPointer'];
  68698. TooltipModel.defaultOption = {
  68699. zlevel: 0,
  68700. z: 60,
  68701. show: true,
  68702. // tooltip main content
  68703. showContent: true,
  68704. // 'trigger' only works on coordinate system.
  68705. // 'item' | 'axis' | 'none'
  68706. trigger: 'item',
  68707. // 'click' | 'mousemove' | 'none'
  68708. triggerOn: 'mousemove|click',
  68709. alwaysShowContent: false,
  68710. displayMode: 'single',
  68711. renderMode: 'auto',
  68712. // whether restraint content inside viewRect.
  68713. // If renderMode: 'richText', default true.
  68714. // If renderMode: 'html', defaut false (for backward compat).
  68715. confine: null,
  68716. showDelay: 0,
  68717. hideDelay: 100,
  68718. // Animation transition time, unit is second
  68719. transitionDuration: 0.4,
  68720. enterable: false,
  68721. backgroundColor: '#fff',
  68722. // box shadow
  68723. shadowBlur: 10,
  68724. shadowColor: 'rgba(0, 0, 0, .2)',
  68725. shadowOffsetX: 1,
  68726. shadowOffsetY: 2,
  68727. // tooltip border radius, unit is px, default is 4
  68728. borderRadius: 4,
  68729. // tooltip border width, unit is px, default is 0 (no border)
  68730. borderWidth: 1,
  68731. // Tooltip inside padding, default is 5 for all direction
  68732. // Array is allowed to set up, right, bottom, left, same with css
  68733. // The default value: See `tooltip/tooltipMarkup.ts#getPaddingFromTooltipModel`.
  68734. padding: null,
  68735. // Extra css text
  68736. extraCssText: '',
  68737. // axis indicator, trigger by axis
  68738. axisPointer: {
  68739. // default is line
  68740. // legal values: 'line' | 'shadow' | 'cross'
  68741. type: 'line',
  68742. // Valid when type is line, appoint tooltip line locate on which line. Optional
  68743. // legal values: 'x' | 'y' | 'angle' | 'radius' | 'auto'
  68744. // default is 'auto', chose the axis which type is category.
  68745. // for multiply y axis, cartesian coord chose x axis, polar chose angle axis
  68746. axis: 'auto',
  68747. animation: 'auto',
  68748. animationDurationUpdate: 200,
  68749. animationEasingUpdate: 'exponentialOut',
  68750. crossStyle: {
  68751. color: '#999',
  68752. width: 1,
  68753. type: 'dashed',
  68754. // TODO formatter
  68755. textStyle: {}
  68756. } // lineStyle and shadowStyle should not be specified here,
  68757. // otherwise it will always override those styles on option.axisPointer.
  68758. },
  68759. textStyle: {
  68760. color: '#666',
  68761. fontSize: 14
  68762. }
  68763. };
  68764. return TooltipModel;
  68765. }(ComponentModel);
  68766. /*
  68767. * Licensed to the Apache Software Foundation (ASF) under one
  68768. * or more contributor license agreements. See the NOTICE file
  68769. * distributed with this work for additional information
  68770. * regarding copyright ownership. The ASF licenses this file
  68771. * to you under the Apache License, Version 2.0 (the
  68772. * "License"); you may not use this file except in compliance
  68773. * with the License. You may obtain a copy of the License at
  68774. *
  68775. * http://www.apache.org/licenses/LICENSE-2.0
  68776. *
  68777. * Unless required by applicable law or agreed to in writing,
  68778. * software distributed under the License is distributed on an
  68779. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68780. * KIND, either express or implied. See the License for the
  68781. * specific language governing permissions and limitations
  68782. * under the License.
  68783. */
  68784. /**
  68785. * AUTO-GENERATED FILE. DO NOT MODIFY.
  68786. */
  68787. /*
  68788. * Licensed to the Apache Software Foundation (ASF) under one
  68789. * or more contributor license agreements. See the NOTICE file
  68790. * distributed with this work for additional information
  68791. * regarding copyright ownership. The ASF licenses this file
  68792. * to you under the Apache License, Version 2.0 (the
  68793. * "License"); you may not use this file except in compliance
  68794. * with the License. You may obtain a copy of the License at
  68795. *
  68796. * http://www.apache.org/licenses/LICENSE-2.0
  68797. *
  68798. * Unless required by applicable law or agreed to in writing,
  68799. * software distributed under the License is distributed on an
  68800. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68801. * KIND, either express or implied. See the License for the
  68802. * specific language governing permissions and limitations
  68803. * under the License.
  68804. */
  68805. function shouldTooltipConfine(tooltipModel) {
  68806. var confineOption = tooltipModel.get('confine');
  68807. return confineOption != null ? !!confineOption // In richText mode, the outside part can not be visible.
  68808. : tooltipModel.get('renderMode') === 'richText';
  68809. }
  68810. var vendors = ['-ms-', '-moz-', '-o-', '-webkit-', ''];
  68811. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  68812. function mirrorPos(pos) {
  68813. pos = pos === 'left' ? 'right' : pos === 'right' ? 'left' : pos === 'top' ? 'bottom' : 'top';
  68814. return pos;
  68815. }
  68816. function assembleArrow(backgroundColor, borderColor, arrowPosition) {
  68817. if (!isString(arrowPosition) || arrowPosition === 'inside') {
  68818. return '';
  68819. }
  68820. borderColor = convertToColorString(borderColor);
  68821. var arrowPos = mirrorPos(arrowPosition);
  68822. var positionStyle = '';
  68823. var transformStyle = '';
  68824. if (indexOf(['left', 'right'], arrowPos) > -1) {
  68825. positionStyle = arrowPos + ":-6px;top:50%;";
  68826. transformStyle = "translateY(-50%) rotate(" + (arrowPos === 'left' ? -225 : -45) + "deg)";
  68827. } else {
  68828. positionStyle = arrowPos + ":-6px;left:50%;";
  68829. transformStyle = "translateX(-50%) rotate(" + (arrowPos === 'top' ? 225 : 45) + "deg)";
  68830. }
  68831. transformStyle = map(vendors, function (vendorPrefix) {
  68832. return vendorPrefix + 'transform:' + transformStyle;
  68833. }).join(';');
  68834. var styleCss = ['position:absolute;width:10px;height:10px;', "" + positionStyle + transformStyle + ";", "border-bottom: " + borderColor + " solid 1px;", "border-right: " + borderColor + " solid 1px;", "background-color: " + backgroundColor + ";", 'box-shadow: 8px 8px 16px -3px #000;'];
  68835. return "<div style=\"" + styleCss.join('') + "\"></div>";
  68836. }
  68837. function assembleTransition(duration, onlyFade) {
  68838. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  68839. var transitionText = 'opacity ' + duration / 2 + 's ' + transitionCurve + ',' + 'visibility ' + duration / 2 + 's ' + transitionCurve;
  68840. if (!onlyFade) {
  68841. transitionText += ',left ' + duration + 's ' + transitionCurve + ',top ' + duration + 's ' + transitionCurve;
  68842. }
  68843. return map(vendors, function (vendorPrefix) {
  68844. return vendorPrefix + 'transition:' + transitionText;
  68845. }).join(';');
  68846. }
  68847. /**
  68848. * @param {Object} textStyle
  68849. * @return {string}
  68850. * @inner
  68851. */
  68852. function assembleFont(textStyleModel) {
  68853. var cssText = [];
  68854. var fontSize = textStyleModel.get('fontSize');
  68855. var color = textStyleModel.getTextColor();
  68856. color && cssText.push('color:' + color);
  68857. cssText.push('font:' + textStyleModel.getFont());
  68858. fontSize // @ts-ignore, leave it to the tooltip refactor.
  68859. && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  68860. var shadowColor = textStyleModel.get('textShadowColor');
  68861. var shadowBlur = textStyleModel.get('textShadowBlur') || 0;
  68862. var shadowOffsetX = textStyleModel.get('textShadowOffsetX') || 0;
  68863. var shadowOffsetY = textStyleModel.get('textShadowOffsetY') || 0;
  68864. shadowColor && shadowBlur && cssText.push('text-shadow:' + shadowOffsetX + 'px ' + shadowOffsetY + 'px ' + shadowBlur + 'px ' + shadowColor);
  68865. each(['decoration', 'align'], function (name) {
  68866. var val = textStyleModel.get(name);
  68867. val && cssText.push('text-' + name + ':' + val);
  68868. });
  68869. return cssText.join(';');
  68870. }
  68871. function assembleCssText(tooltipModel, enableTransition, onlyFade) {
  68872. var cssText = [];
  68873. var transitionDuration = tooltipModel.get('transitionDuration');
  68874. var backgroundColor = tooltipModel.get('backgroundColor');
  68875. var shadowBlur = tooltipModel.get('shadowBlur');
  68876. var shadowColor = tooltipModel.get('shadowColor');
  68877. var shadowOffsetX = tooltipModel.get('shadowOffsetX');
  68878. var shadowOffsetY = tooltipModel.get('shadowOffsetY');
  68879. var textStyleModel = tooltipModel.getModel('textStyle');
  68880. var padding = getPaddingFromTooltipModel(tooltipModel, 'html');
  68881. var boxShadow = shadowOffsetX + "px " + shadowOffsetY + "px " + shadowBlur + "px " + shadowColor;
  68882. cssText.push('box-shadow:' + boxShadow); // Animation transition. Do not animate when transitionDuration is 0.
  68883. enableTransition && transitionDuration && cssText.push(assembleTransition(transitionDuration, onlyFade));
  68884. if (backgroundColor) {
  68885. if (env.canvasSupported) {
  68886. cssText.push('background-Color:' + backgroundColor);
  68887. } else {
  68888. // for ie
  68889. cssText.push('background-Color:#' + toHex(backgroundColor));
  68890. cssText.push('filter:alpha(opacity=70)');
  68891. }
  68892. } // Border style
  68893. each(['width', 'color', 'radius'], function (name) {
  68894. var borderName = 'border-' + name;
  68895. var camelCase = toCamelCase(borderName);
  68896. var val = tooltipModel.get(camelCase);
  68897. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  68898. }); // Text style
  68899. cssText.push(assembleFont(textStyleModel)); // Padding
  68900. if (padding != null) {
  68901. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  68902. }
  68903. return cssText.join(';') + ';';
  68904. } // If not able to make, do not modify the input `out`.
  68905. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  68906. var zrPainter = zr && zr.painter;
  68907. if (appendToBody) {
  68908. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  68909. if (zrViewportRoot) {
  68910. // Some APPs might use scale on body, so we support CSS transform here.
  68911. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  68912. }
  68913. } else {
  68914. out[0] = zrX;
  68915. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  68916. // the sibling of canvas root. So padding of ec container
  68917. // should be considered here.
  68918. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  68919. if (viewportRootOffset) {
  68920. out[0] += viewportRootOffset.offsetLeft;
  68921. out[1] += viewportRootOffset.offsetTop;
  68922. }
  68923. }
  68924. out[2] = out[0] / zr.getWidth();
  68925. out[3] = out[1] / zr.getHeight();
  68926. }
  68927. var TooltipHTMLContent =
  68928. /** @class */
  68929. function () {
  68930. function TooltipHTMLContent(container, api, opt) {
  68931. this._show = false;
  68932. this._styleCoord = [0, 0, 0, 0];
  68933. this._enterable = true;
  68934. this._firstShow = true;
  68935. this._longHide = true;
  68936. if (env.wxa) {
  68937. return null;
  68938. }
  68939. var el = document.createElement('div'); // TODO: TYPE
  68940. el.domBelongToZr = true;
  68941. this.el = el;
  68942. var zr = this._zr = api.getZr();
  68943. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  68944. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  68945. if (appendToBody) {
  68946. document.body.appendChild(el);
  68947. } else {
  68948. container.appendChild(el);
  68949. }
  68950. this._container = container; // FIXME
  68951. // Is it needed to trigger zr event manually if
  68952. // the browser do not support `pointer-events: none`.
  68953. var self = this;
  68954. el.onmouseenter = function () {
  68955. // clear the timeout in hideLater and keep showing tooltip
  68956. if (self._enterable) {
  68957. clearTimeout(self._hideTimeout);
  68958. self._show = true;
  68959. }
  68960. self._inContent = true;
  68961. };
  68962. el.onmousemove = function (e) {
  68963. e = e || window.event;
  68964. if (!self._enterable) {
  68965. // `pointer-events: none` is set to tooltip content div
  68966. // if `enterable` is set as `false`, and `el.onmousemove`
  68967. // can not be triggered. But in browser that do not
  68968. // support `pointer-events`, we need to do this:
  68969. // Try trigger zrender event to avoid mouse
  68970. // in and out shape too frequently
  68971. var handler = zr.handler;
  68972. var zrViewportRoot = zr.painter.getViewportRoot();
  68973. normalizeEvent(zrViewportRoot, e, true);
  68974. handler.dispatch('mousemove', e);
  68975. }
  68976. };
  68977. el.onmouseleave = function () {
  68978. // set `_inContent` to `false` before `hideLater`
  68979. self._inContent = false;
  68980. if (self._enterable) {
  68981. if (self._show) {
  68982. self.hideLater(self._hideDelay);
  68983. }
  68984. }
  68985. };
  68986. }
  68987. /**
  68988. * Update when tooltip is rendered
  68989. */
  68990. TooltipHTMLContent.prototype.update = function (tooltipModel) {
  68991. // FIXME
  68992. // Move this logic to ec main?
  68993. var container = this._container;
  68994. var stl = container.currentStyle || document.defaultView.getComputedStyle(container);
  68995. var domStyle = container.style;
  68996. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  68997. domStyle.position = 'relative';
  68998. } // move tooltip if chart resized
  68999. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  69000. alwaysShowContent && this._moveIfResized(); // update className
  69001. this.el.className = tooltipModel.get('className') || ''; // Hide the tooltip
  69002. // PENDING
  69003. // this.hide();
  69004. };
  69005. TooltipHTMLContent.prototype.show = function (tooltipModel, nearPointColor) {
  69006. clearTimeout(this._hideTimeout);
  69007. clearTimeout(this._longHideTimeout);
  69008. var el = this.el;
  69009. var styleCoord = this._styleCoord;
  69010. var offset = el.offsetHeight / 2;
  69011. nearPointColor = convertToColorString(nearPointColor);
  69012. el.style.cssText = gCssText + assembleCssText(tooltipModel, !this._firstShow, this._longHide) // Because of the reason described in:
  69013. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  69014. // we should set initial value to `left` and `top`.
  69015. + ';left:' + styleCoord[0] + 'px;top:' + (styleCoord[1] - offset) + 'px;' + ("border-color: " + nearPointColor + ";") + (tooltipModel.get('extraCssText') || '');
  69016. el.style.display = el.innerHTML ? 'block' : 'none'; // If mouse occasionally move over the tooltip, a mouseout event will be
  69017. // triggered by canvas, and cause some unexpectable result like dragging
  69018. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  69019. // it. Although it is not supported by IE8~IE10, fortunately it is a rare
  69020. // scenario.
  69021. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  69022. this._show = true;
  69023. this._firstShow = false;
  69024. this._longHide = false;
  69025. };
  69026. TooltipHTMLContent.prototype.setContent = function (content, markers, tooltipModel, borderColor, arrowPosition) {
  69027. if (content == null) {
  69028. return;
  69029. }
  69030. var el = this.el;
  69031. if (isString(arrowPosition) && tooltipModel.get('trigger') === 'item' && !shouldTooltipConfine(tooltipModel)) {
  69032. content += assembleArrow(tooltipModel.get('backgroundColor'), borderColor, arrowPosition);
  69033. }
  69034. if (isString(content)) {
  69035. el.innerHTML = content;
  69036. } else if (content) {
  69037. // Clear previous
  69038. el.innerHTML = '';
  69039. if (!isArray(content)) {
  69040. content = [content];
  69041. }
  69042. for (var i = 0; i < content.length; i++) {
  69043. if (isDom(content[i]) && content[i].parentNode !== el) {
  69044. el.appendChild(content[i]);
  69045. }
  69046. }
  69047. }
  69048. };
  69049. TooltipHTMLContent.prototype.setEnterable = function (enterable) {
  69050. this._enterable = enterable;
  69051. };
  69052. TooltipHTMLContent.prototype.getSize = function () {
  69053. var el = this.el;
  69054. return [el.clientWidth, el.clientHeight];
  69055. };
  69056. TooltipHTMLContent.prototype.moveTo = function (zrX, zrY) {
  69057. var styleCoord = this._styleCoord;
  69058. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  69059. if (styleCoord[0] != null && styleCoord[1] != null) {
  69060. var style = this.el.style; // If using float on style, the final width of the dom might
  69061. // keep changing slightly while mouse move. So `toFixed(0)` them.
  69062. style.left = styleCoord[0].toFixed(0) + 'px';
  69063. style.top = styleCoord[1].toFixed(0) + 'px';
  69064. }
  69065. };
  69066. /**
  69067. * when `alwaysShowContent` is true,
  69068. * move the tooltip after chart resized
  69069. */
  69070. TooltipHTMLContent.prototype._moveIfResized = function () {
  69071. // The ratio of left to width
  69072. var ratioX = this._styleCoord[2]; // The ratio of top to height
  69073. var ratioY = this._styleCoord[3];
  69074. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  69075. };
  69076. TooltipHTMLContent.prototype.hide = function () {
  69077. var _this = this;
  69078. this.el.style.visibility = 'hidden';
  69079. this.el.style.opacity = '0';
  69080. this._show = false;
  69081. this._longHideTimeout = setTimeout(function () {
  69082. return _this._longHide = true;
  69083. }, 500);
  69084. };
  69085. TooltipHTMLContent.prototype.hideLater = function (time) {
  69086. if (this._show && !(this._inContent && this._enterable)) {
  69087. if (time) {
  69088. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  69089. this._show = false;
  69090. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  69091. } else {
  69092. this.hide();
  69093. }
  69094. }
  69095. };
  69096. TooltipHTMLContent.prototype.isShow = function () {
  69097. return this._show;
  69098. };
  69099. TooltipHTMLContent.prototype.dispose = function () {
  69100. this.el.parentNode.removeChild(this.el);
  69101. };
  69102. TooltipHTMLContent.prototype.getOuterSize = function () {
  69103. var width = this.el.clientWidth;
  69104. var height = this.el.clientHeight; // Consider browser compatibility.
  69105. // IE8 does not support getComputedStyle.
  69106. if (document.defaultView && document.defaultView.getComputedStyle) {
  69107. var stl = document.defaultView.getComputedStyle(this.el);
  69108. if (stl) {
  69109. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  69110. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  69111. }
  69112. }
  69113. return {
  69114. width: width,
  69115. height: height
  69116. };
  69117. };
  69118. return TooltipHTMLContent;
  69119. }();
  69120. var TooltipRichContent =
  69121. /** @class */
  69122. function () {
  69123. function TooltipRichContent(api) {
  69124. this._show = false;
  69125. this._styleCoord = [0, 0, 0, 0];
  69126. this._enterable = true;
  69127. this._zr = api.getZr();
  69128. makeStyleCoord$1(this._styleCoord, this._zr, api.getWidth() / 2, api.getHeight() / 2);
  69129. }
  69130. /**
  69131. * Update when tooltip is rendered
  69132. */
  69133. TooltipRichContent.prototype.update = function (tooltipModel) {
  69134. var alwaysShowContent = tooltipModel.get('alwaysShowContent');
  69135. alwaysShowContent && this._moveIfResized();
  69136. };
  69137. TooltipRichContent.prototype.show = function () {
  69138. if (this._hideTimeout) {
  69139. clearTimeout(this._hideTimeout);
  69140. }
  69141. this.el.show();
  69142. this._show = true;
  69143. };
  69144. /**
  69145. * Set tooltip content
  69146. */
  69147. TooltipRichContent.prototype.setContent = function (content, markupStyleCreator, tooltipModel, borderColor, arrowPosition) {
  69148. if (isObject(content)) {
  69149. throwError("development" !== 'production' ? 'Passing DOM nodes as content is not supported in richText tooltip!' : '');
  69150. }
  69151. if (this.el) {
  69152. this._zr.remove(this.el);
  69153. }
  69154. var textStyleModel = tooltipModel.getModel('textStyle');
  69155. this.el = new ZRText({
  69156. style: {
  69157. rich: markupStyleCreator.richTextStyles,
  69158. text: content,
  69159. lineHeight: 22,
  69160. backgroundColor: tooltipModel.get('backgroundColor'),
  69161. borderRadius: tooltipModel.get('borderRadius'),
  69162. borderWidth: 1,
  69163. borderColor: borderColor,
  69164. shadowColor: tooltipModel.get('shadowColor'),
  69165. shadowBlur: tooltipModel.get('shadowBlur'),
  69166. shadowOffsetX: tooltipModel.get('shadowOffsetX'),
  69167. shadowOffsetY: tooltipModel.get('shadowOffsetY'),
  69168. textShadowColor: textStyleModel.get('textShadowColor'),
  69169. textShadowBlur: textStyleModel.get('textShadowBlur') || 0,
  69170. textShadowOffsetX: textStyleModel.get('textShadowOffsetX') || 0,
  69171. textShadowOffsetY: textStyleModel.get('textShadowOffsetY') || 0,
  69172. fill: tooltipModel.get(['textStyle', 'color']),
  69173. padding: getPaddingFromTooltipModel(tooltipModel, 'richText'),
  69174. verticalAlign: 'top',
  69175. align: 'left'
  69176. },
  69177. z: tooltipModel.get('z')
  69178. });
  69179. this._zr.add(this.el);
  69180. var self = this;
  69181. this.el.on('mouseover', function () {
  69182. // clear the timeout in hideLater and keep showing tooltip
  69183. if (self._enterable) {
  69184. clearTimeout(self._hideTimeout);
  69185. self._show = true;
  69186. }
  69187. self._inContent = true;
  69188. });
  69189. this.el.on('mouseout', function () {
  69190. if (self._enterable) {
  69191. if (self._show) {
  69192. self.hideLater(self._hideDelay);
  69193. }
  69194. }
  69195. self._inContent = false;
  69196. });
  69197. };
  69198. TooltipRichContent.prototype.setEnterable = function (enterable) {
  69199. this._enterable = enterable;
  69200. };
  69201. TooltipRichContent.prototype.getSize = function () {
  69202. var el = this.el;
  69203. var bounding = this.el.getBoundingRect(); // bounding rect does not include shadow. For renderMode richText,
  69204. // if overflow, it will be cut. So calculate them accurately.
  69205. var shadowOuterSize = calcShadowOuterSize(el.style);
  69206. return [bounding.width + shadowOuterSize.left + shadowOuterSize.right, bounding.height + shadowOuterSize.top + shadowOuterSize.bottom];
  69207. };
  69208. TooltipRichContent.prototype.moveTo = function (x, y) {
  69209. var el = this.el;
  69210. if (el) {
  69211. var styleCoord = this._styleCoord;
  69212. makeStyleCoord$1(styleCoord, this._zr, x, y);
  69213. x = styleCoord[0];
  69214. y = styleCoord[1];
  69215. var style = el.style;
  69216. var borderWidth = mathMaxWith0(style.borderWidth || 0);
  69217. var shadowOuterSize = calcShadowOuterSize(style); // rich text x, y do not include border.
  69218. el.x = x + borderWidth + shadowOuterSize.left;
  69219. el.y = y + borderWidth + shadowOuterSize.top;
  69220. el.markRedraw();
  69221. }
  69222. };
  69223. /**
  69224. * when `alwaysShowContent` is true,
  69225. * move the tooltip after chart resized
  69226. */
  69227. TooltipRichContent.prototype._moveIfResized = function () {
  69228. // The ratio of left to width
  69229. var ratioX = this._styleCoord[2]; // The ratio of top to height
  69230. var ratioY = this._styleCoord[3];
  69231. this.moveTo(ratioX * this._zr.getWidth(), ratioY * this._zr.getHeight());
  69232. };
  69233. TooltipRichContent.prototype.hide = function () {
  69234. if (this.el) {
  69235. this.el.hide();
  69236. }
  69237. this._show = false;
  69238. };
  69239. TooltipRichContent.prototype.hideLater = function (time) {
  69240. if (this._show && !(this._inContent && this._enterable)) {
  69241. if (time) {
  69242. this._hideDelay = time; // Set show false to avoid invoke hideLater multiple times
  69243. this._show = false;
  69244. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  69245. } else {
  69246. this.hide();
  69247. }
  69248. }
  69249. };
  69250. TooltipRichContent.prototype.isShow = function () {
  69251. return this._show;
  69252. };
  69253. TooltipRichContent.prototype.getOuterSize = function () {
  69254. var size = this.getSize();
  69255. return {
  69256. width: size[0],
  69257. height: size[1]
  69258. };
  69259. };
  69260. TooltipRichContent.prototype.dispose = function () {
  69261. this._zr.remove(this.el);
  69262. };
  69263. return TooltipRichContent;
  69264. }();
  69265. function mathMaxWith0(val) {
  69266. return Math.max(0, val);
  69267. }
  69268. function calcShadowOuterSize(style) {
  69269. var shadowBlur = mathMaxWith0(style.shadowBlur || 0);
  69270. var shadowOffsetX = mathMaxWith0(style.shadowOffsetX || 0);
  69271. var shadowOffsetY = mathMaxWith0(style.shadowOffsetY || 0);
  69272. return {
  69273. left: mathMaxWith0(shadowBlur - shadowOffsetX),
  69274. right: mathMaxWith0(shadowBlur + shadowOffsetX),
  69275. top: mathMaxWith0(shadowBlur - shadowOffsetY),
  69276. bottom: mathMaxWith0(shadowBlur + shadowOffsetY)
  69277. };
  69278. }
  69279. function makeStyleCoord$1(out, zr, zrX, zrY) {
  69280. out[0] = zrX;
  69281. out[1] = zrY;
  69282. out[2] = out[0] / zr.getWidth();
  69283. out[3] = out[1] / zr.getHeight();
  69284. }
  69285. var bind$2 = bind;
  69286. var each$c = each;
  69287. var parsePercent$3 = parsePercent$1;
  69288. var proxyRect = new Rect({
  69289. shape: {
  69290. x: -1,
  69291. y: -1,
  69292. width: 2,
  69293. height: 2
  69294. }
  69295. });
  69296. var TooltipView =
  69297. /** @class */
  69298. function (_super) {
  69299. __extends(TooltipView, _super);
  69300. function TooltipView() {
  69301. var _this = _super !== null && _super.apply(this, arguments) || this;
  69302. _this.type = TooltipView.type;
  69303. return _this;
  69304. }
  69305. TooltipView.prototype.init = function (ecModel, api) {
  69306. if (env.node) {
  69307. return;
  69308. }
  69309. var tooltipModel = ecModel.getComponent('tooltip');
  69310. var renderMode = tooltipModel.get('renderMode');
  69311. this._renderMode = getTooltipRenderMode(renderMode);
  69312. this._tooltipContent = this._renderMode === 'richText' ? new TooltipRichContent(api) : new TooltipHTMLContent(api.getDom(), api, {
  69313. appendToBody: tooltipModel.get('appendToBody', true)
  69314. });
  69315. };
  69316. TooltipView.prototype.render = function (tooltipModel, ecModel, api) {
  69317. if (env.node) {
  69318. return;
  69319. } // Reset
  69320. this.group.removeAll();
  69321. this._tooltipModel = tooltipModel;
  69322. this._ecModel = ecModel;
  69323. this._api = api;
  69324. /**
  69325. * @private
  69326. * @type {boolean}
  69327. */
  69328. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  69329. var tooltipContent = this._tooltipContent;
  69330. tooltipContent.update(tooltipModel);
  69331. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  69332. this._initGlobalListener();
  69333. this._keepShow();
  69334. };
  69335. TooltipView.prototype._initGlobalListener = function () {
  69336. var tooltipModel = this._tooltipModel;
  69337. var triggerOn = tooltipModel.get('triggerOn');
  69338. register('itemTooltip', this._api, bind$2(function (currTrigger, e, dispatchAction) {
  69339. // If 'none', it is not controlled by mouse totally.
  69340. if (triggerOn !== 'none') {
  69341. if (triggerOn.indexOf(currTrigger) >= 0) {
  69342. this._tryShow(e, dispatchAction);
  69343. } else if (currTrigger === 'leave') {
  69344. this._hide(dispatchAction);
  69345. }
  69346. }
  69347. }, this));
  69348. };
  69349. TooltipView.prototype._keepShow = function () {
  69350. var tooltipModel = this._tooltipModel;
  69351. var ecModel = this._ecModel;
  69352. var api = this._api; // Try to keep the tooltip show when refreshing
  69353. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  69354. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  69355. // which is not expected.
  69356. && tooltipModel.get('triggerOn') !== 'none') {
  69357. var self_1 = this;
  69358. clearTimeout(this._refreshUpdateTimeout);
  69359. this._refreshUpdateTimeout = setTimeout(function () {
  69360. // Show tip next tick after other charts are rendered
  69361. // In case highlight action has wrong result
  69362. // FIXME
  69363. !api.isDisposed() && self_1.manuallyShowTip(tooltipModel, ecModel, api, {
  69364. x: self_1._lastX,
  69365. y: self_1._lastY,
  69366. dataByCoordSys: self_1._lastDataByCoordSys
  69367. });
  69368. });
  69369. }
  69370. };
  69371. /**
  69372. * Show tip manually by
  69373. * dispatchAction({
  69374. * type: 'showTip',
  69375. * x: 10,
  69376. * y: 10
  69377. * });
  69378. * Or
  69379. * dispatchAction({
  69380. * type: 'showTip',
  69381. * seriesIndex: 0,
  69382. * dataIndex or dataIndexInside or name
  69383. * });
  69384. *
  69385. * TODO Batch
  69386. */
  69387. TooltipView.prototype.manuallyShowTip = function (tooltipModel, ecModel, api, payload) {
  69388. if (payload.from === this.uid || env.node) {
  69389. return;
  69390. }
  69391. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  69392. this._ticket = ''; // When triggered from axisPointer.
  69393. var dataByCoordSys = payload.dataByCoordSys;
  69394. if (payload.tooltip && payload.x != null && payload.y != null) {
  69395. var el = proxyRect;
  69396. el.x = payload.x;
  69397. el.y = payload.y;
  69398. el.update();
  69399. el.tooltip = payload.tooltip; // Manually show tooltip while view is not using zrender elements.
  69400. this._tryShow({
  69401. offsetX: payload.x,
  69402. offsetY: payload.y,
  69403. target: el
  69404. }, dispatchAction);
  69405. } else if (dataByCoordSys) {
  69406. this._tryShow({
  69407. offsetX: payload.x,
  69408. offsetY: payload.y,
  69409. position: payload.position,
  69410. dataByCoordSys: dataByCoordSys,
  69411. tooltipOption: payload.tooltipOption
  69412. }, dispatchAction);
  69413. } else if (payload.seriesIndex != null) {
  69414. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  69415. return;
  69416. }
  69417. var pointInfo = findPointFromSeries(payload, ecModel);
  69418. var cx = pointInfo.point[0];
  69419. var cy = pointInfo.point[1];
  69420. if (cx != null && cy != null) {
  69421. this._tryShow({
  69422. offsetX: cx,
  69423. offsetY: cy,
  69424. position: payload.position,
  69425. target: pointInfo.el
  69426. }, dispatchAction);
  69427. }
  69428. } else if (payload.x != null && payload.y != null) {
  69429. // FIXME
  69430. // should wrap dispatchAction like `axisPointer/globalListener` ?
  69431. api.dispatchAction({
  69432. type: 'updateAxisPointer',
  69433. x: payload.x,
  69434. y: payload.y
  69435. });
  69436. this._tryShow({
  69437. offsetX: payload.x,
  69438. offsetY: payload.y,
  69439. position: payload.position,
  69440. target: api.getZr().findHover(payload.x, payload.y).target
  69441. }, dispatchAction);
  69442. }
  69443. };
  69444. TooltipView.prototype.manuallyHideTip = function (tooltipModel, ecModel, api, payload) {
  69445. var tooltipContent = this._tooltipContent;
  69446. if (!this._alwaysShowContent && this._tooltipModel) {
  69447. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  69448. }
  69449. this._lastX = this._lastY = this._lastDataByCoordSys = null;
  69450. if (payload.from !== this.uid) {
  69451. this._hide(makeDispatchAction$1(payload, api));
  69452. }
  69453. }; // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  69454. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  69455. // and tooltip.
  69456. TooltipView.prototype._manuallyAxisShowTip = function (tooltipModel, ecModel, api, payload) {
  69457. var seriesIndex = payload.seriesIndex;
  69458. var dataIndex = payload.dataIndex; // @ts-ignore
  69459. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  69460. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  69461. return;
  69462. }
  69463. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  69464. if (!seriesModel) {
  69465. return;
  69466. }
  69467. var data = seriesModel.getData();
  69468. var tooltipCascadedModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model, tooltipModel]);
  69469. if (tooltipCascadedModel.get('trigger') !== 'axis') {
  69470. return;
  69471. }
  69472. api.dispatchAction({
  69473. type: 'updateAxisPointer',
  69474. seriesIndex: seriesIndex,
  69475. dataIndex: dataIndex,
  69476. position: payload.position
  69477. });
  69478. return true;
  69479. };
  69480. TooltipView.prototype._tryShow = function (e, dispatchAction) {
  69481. var el = e.target;
  69482. var tooltipModel = this._tooltipModel;
  69483. if (!tooltipModel) {
  69484. return;
  69485. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  69486. this._lastX = e.offsetX;
  69487. this._lastY = e.offsetY;
  69488. var dataByCoordSys = e.dataByCoordSys;
  69489. if (dataByCoordSys && dataByCoordSys.length) {
  69490. this._showAxisTooltip(dataByCoordSys, e);
  69491. } // Always show item tooltip if mouse is on the element with dataIndex
  69492. else if (el && findEventDispatcher(el, function (target) {
  69493. return getECData(target).dataIndex != null;
  69494. }, true)) {
  69495. this._lastDataByCoordSys = null;
  69496. this._showSeriesItemTooltip(e, el, dispatchAction);
  69497. } // Tooltip provided directly. Like legend.
  69498. else if (el && el.tooltip) {
  69499. this._lastDataByCoordSys = null;
  69500. this._showComponentItemTooltip(e, el, dispatchAction);
  69501. } else {
  69502. this._lastDataByCoordSys = null;
  69503. this._hide(dispatchAction);
  69504. }
  69505. };
  69506. TooltipView.prototype._showOrMove = function (tooltipModel, cb) {
  69507. // showDelay is used in this case: tooltip.enterable is set
  69508. // as true. User intent to move mouse into tooltip and click
  69509. // something. `showDelay` makes it easier to enter the content
  69510. // but tooltip do not move immediately.
  69511. var delay = tooltipModel.get('showDelay');
  69512. cb = bind(cb, this);
  69513. clearTimeout(this._showTimout);
  69514. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  69515. };
  69516. TooltipView.prototype._showAxisTooltip = function (dataByCoordSys, e) {
  69517. var ecModel = this._ecModel;
  69518. var globalTooltipModel = this._tooltipModel;
  69519. var point = [e.offsetX, e.offsetY];
  69520. var singleTooltipModel = buildTooltipModel([e.tooltipOption, globalTooltipModel]);
  69521. var renderMode = this._renderMode;
  69522. var cbParamsList = [];
  69523. var articleMarkup = createTooltipMarkup('section', {
  69524. blocks: [],
  69525. noHeader: true
  69526. }); // Only for legacy: `Serise['formatTooltip']` returns a string.
  69527. var markupTextArrLegacy = [];
  69528. var markupStyleCreator = new TooltipMarkupStyleCreator();
  69529. each$c(dataByCoordSys, function (itemCoordSys) {
  69530. each$c(itemCoordSys.dataByAxis, function (axisItem) {
  69531. var axisModel = ecModel.getComponent(axisItem.axisDim + 'Axis', axisItem.axisIndex);
  69532. var axisValue = axisItem.value;
  69533. if (!axisModel || axisValue == null) {
  69534. return;
  69535. }
  69536. var axisValueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, axisItem.seriesDataIndices, axisItem.valueLabelOpt);
  69537. var axisSectionMarkup = createTooltipMarkup('section', {
  69538. header: axisValueLabel,
  69539. noHeader: !trim(axisValueLabel),
  69540. sortBlocks: true,
  69541. blocks: []
  69542. });
  69543. articleMarkup.blocks.push(axisSectionMarkup);
  69544. each(axisItem.seriesDataIndices, function (idxItem) {
  69545. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  69546. var dataIndex = idxItem.dataIndexInside;
  69547. var cbParams = series.getDataParams(dataIndex);
  69548. cbParams.axisDim = axisItem.axisDim;
  69549. cbParams.axisIndex = axisItem.axisIndex;
  69550. cbParams.axisType = axisItem.axisType;
  69551. cbParams.axisId = axisItem.axisId;
  69552. cbParams.axisValue = getAxisRawValue(axisModel.axis, {
  69553. value: axisValue
  69554. });
  69555. cbParams.axisValueLabel = axisValueLabel; // Pre-create marker style for makers. Users can assemble richText
  69556. // text in `formatter` callback and use those markers style.
  69557. cbParams.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(cbParams.color), renderMode);
  69558. var seriesTooltipResult = normalizeTooltipFormatResult(series.formatTooltip(dataIndex, true, null));
  69559. if (seriesTooltipResult.markupFragment) {
  69560. axisSectionMarkup.blocks.push(seriesTooltipResult.markupFragment);
  69561. }
  69562. if (seriesTooltipResult.markupText) {
  69563. markupTextArrLegacy.push(seriesTooltipResult.markupText);
  69564. }
  69565. cbParamsList.push(cbParams);
  69566. });
  69567. });
  69568. }); // In most cases, the second axis is displays upper on the first one.
  69569. // So we reverse it to look better.
  69570. articleMarkup.blocks.reverse();
  69571. markupTextArrLegacy.reverse();
  69572. var positionExpr = e.position;
  69573. var orderMode = singleTooltipModel.get('order');
  69574. var builtMarkupText = buildTooltipMarkup(articleMarkup, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), singleTooltipModel.get('textStyle'));
  69575. builtMarkupText && markupTextArrLegacy.unshift(builtMarkupText);
  69576. var blockBreak = renderMode === 'richText' ? '\n\n' : '<br/>';
  69577. var allMarkupText = markupTextArrLegacy.join(blockBreak);
  69578. this._showOrMove(singleTooltipModel, function () {
  69579. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  69580. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, cbParamsList);
  69581. } else {
  69582. this._showTooltipContent(singleTooltipModel, allMarkupText, cbParamsList, Math.random() + '', point[0], point[1], positionExpr, null, markupStyleCreator);
  69583. }
  69584. }); // Do not trigger events here, because this branch only be entered
  69585. // from dispatchAction.
  69586. };
  69587. TooltipView.prototype._showSeriesItemTooltip = function (e, el, dispatchAction) {
  69588. var dispatcher = findEventDispatcher(el, function (target) {
  69589. return getECData(target).dataIndex != null;
  69590. }, true);
  69591. var ecModel = this._ecModel;
  69592. var ecData = getECData(dispatcher); // Use dataModel in element if possible
  69593. // Used when mouseover on a element like markPoint or edge
  69594. // In which case, the data is not main data in series.
  69595. var seriesIndex = ecData.seriesIndex;
  69596. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  69597. var dataModel = ecData.dataModel || seriesModel;
  69598. var dataIndex = ecData.dataIndex;
  69599. var dataType = ecData.dataType;
  69600. var data = dataModel.getData(dataType);
  69601. var renderMode = this._renderMode;
  69602. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model, this._tooltipModel]);
  69603. var tooltipTrigger = tooltipModel.get('trigger');
  69604. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  69605. return;
  69606. }
  69607. var params = dataModel.getDataParams(dataIndex, dataType);
  69608. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Pre-create marker style for makers. Users can assemble richText
  69609. // text in `formatter` callback and use those markers style.
  69610. params.marker = markupStyleCreator.makeTooltipMarker('item', convertToColorString(params.color), renderMode);
  69611. var seriesTooltipResult = normalizeTooltipFormatResult(dataModel.formatTooltip(dataIndex, false, dataType));
  69612. var orderMode = tooltipModel.get('order');
  69613. var markupText = seriesTooltipResult.markupFragment ? buildTooltipMarkup(seriesTooltipResult.markupFragment, markupStyleCreator, renderMode, orderMode, ecModel.get('useUTC'), tooltipModel.get('textStyle')) : seriesTooltipResult.markupText;
  69614. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  69615. this._showOrMove(tooltipModel, function () {
  69616. this._showTooltipContent(tooltipModel, markupText, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markupStyleCreator);
  69617. }); // FIXME
  69618. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  69619. dispatchAction({
  69620. type: 'showTip',
  69621. dataIndexInside: dataIndex,
  69622. dataIndex: data.getRawIndex(dataIndex),
  69623. seriesIndex: seriesIndex,
  69624. from: this.uid
  69625. });
  69626. };
  69627. TooltipView.prototype._showComponentItemTooltip = function (e, el, dispatchAction) {
  69628. var tooltipOpt = el.tooltip;
  69629. if (isString(tooltipOpt)) {
  69630. var content = tooltipOpt;
  69631. tooltipOpt = {
  69632. content: content,
  69633. // Fixed formatter
  69634. formatter: content
  69635. };
  69636. }
  69637. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  69638. var defaultHtml = subTooltipModel.get('content');
  69639. var asyncTicket = Math.random() + ''; // PENDING: this case do not support richText style yet.
  69640. var markupStyleCreator = new TooltipMarkupStyleCreator(); // Do not check whether `trigger` is 'none' here, because `trigger`
  69641. // only works on coordinate system. In fact, we have not found case
  69642. // that requires setting `trigger` nothing on component yet.
  69643. this._showOrMove(subTooltipModel, function () {
  69644. this._showTooltipContent( // Use formatterParams from element defined in component
  69645. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {}, asyncTicket, e.offsetX, e.offsetY, e.position, el, markupStyleCreator);
  69646. }); // If not dispatch showTip, tip may be hide triggered by axis.
  69647. dispatchAction({
  69648. type: 'showTip',
  69649. from: this.uid
  69650. });
  69651. };
  69652. TooltipView.prototype._showTooltipContent = function ( // Use Model<TooltipOption> insteadof TooltipModel because this model may be from series or other options.
  69653. // Instead of top level tooltip.
  69654. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markupStyleCreator) {
  69655. // Reset ticket
  69656. this._ticket = '';
  69657. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  69658. return;
  69659. }
  69660. var tooltipContent = this._tooltipContent;
  69661. var formatter = tooltipModel.get('formatter');
  69662. positionExpr = positionExpr || tooltipModel.get('position');
  69663. var html = defaultHtml;
  69664. var nearPoint = this._getNearestPoint([x, y], params, tooltipModel.get('trigger'), tooltipModel.get('borderColor'));
  69665. if (formatter && isString(formatter)) {
  69666. var useUTC = tooltipModel.ecModel.get('useUTC');
  69667. var params0 = isArray(params) ? params[0] : params;
  69668. var isTimeAxis = params0 && params0.axisType && params0.axisType.indexOf('time') >= 0;
  69669. html = formatter;
  69670. if (isTimeAxis) {
  69671. html = format(params0.axisValue, html, useUTC);
  69672. }
  69673. html = formatTpl(html, params, true);
  69674. } else if (isFunction(formatter)) {
  69675. var callback = bind$2(function (cbTicket, html) {
  69676. if (cbTicket === this._ticket) {
  69677. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPoint.color, positionExpr);
  69678. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  69679. }
  69680. }, this);
  69681. this._ticket = asyncTicket;
  69682. html = formatter(params, asyncTicket, callback);
  69683. }
  69684. tooltipContent.setContent(html, markupStyleCreator, tooltipModel, nearPoint.color, positionExpr);
  69685. tooltipContent.show(tooltipModel, nearPoint.color);
  69686. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  69687. };
  69688. TooltipView.prototype._getNearestPoint = function (point, tooltipDataParams, trigger, borderColor) {
  69689. if (trigger === 'axis' || isArray(tooltipDataParams)) {
  69690. return {
  69691. color: borderColor || (this._renderMode === 'html' ? '#fff' : 'none')
  69692. };
  69693. }
  69694. if (!isArray(tooltipDataParams)) {
  69695. return {
  69696. color: borderColor || tooltipDataParams.color || tooltipDataParams.borderColor
  69697. };
  69698. }
  69699. };
  69700. TooltipView.prototype._updatePosition = function (tooltipModel, positionExpr, x, // Mouse x
  69701. y, // Mouse y
  69702. content, params, el) {
  69703. var viewWidth = this._api.getWidth();
  69704. var viewHeight = this._api.getHeight();
  69705. positionExpr = positionExpr || tooltipModel.get('position');
  69706. var contentSize = content.getSize();
  69707. var align = tooltipModel.get('align');
  69708. var vAlign = tooltipModel.get('verticalAlign');
  69709. var rect = el && el.getBoundingRect().clone();
  69710. el && rect.applyTransform(el.transform);
  69711. if (isFunction(positionExpr)) {
  69712. // Callback of position can be an array or a string specify the position
  69713. positionExpr = positionExpr([x, y], params, content.el, rect, {
  69714. viewSize: [viewWidth, viewHeight],
  69715. contentSize: contentSize.slice()
  69716. });
  69717. }
  69718. if (isArray(positionExpr)) {
  69719. x = parsePercent$3(positionExpr[0], viewWidth);
  69720. y = parsePercent$3(positionExpr[1], viewHeight);
  69721. } else if (isObject(positionExpr)) {
  69722. var boxLayoutPosition = positionExpr;
  69723. boxLayoutPosition.width = contentSize[0];
  69724. boxLayoutPosition.height = contentSize[1];
  69725. var layoutRect = getLayoutRect(boxLayoutPosition, {
  69726. width: viewWidth,
  69727. height: viewHeight
  69728. });
  69729. x = layoutRect.x;
  69730. y = layoutRect.y;
  69731. align = null; // When positionExpr is left/top/right/bottom,
  69732. // align and verticalAlign will not work.
  69733. vAlign = null;
  69734. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  69735. else if (isString(positionExpr) && el) {
  69736. var pos = calcTooltipPosition(positionExpr, rect, contentSize);
  69737. x = pos[0];
  69738. y = pos[1];
  69739. } else {
  69740. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  69741. x = pos[0];
  69742. y = pos[1];
  69743. }
  69744. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  69745. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  69746. if (shouldTooltipConfine(tooltipModel)) {
  69747. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  69748. x = pos[0];
  69749. y = pos[1];
  69750. }
  69751. content.moveTo(x, y);
  69752. }; // FIXME
  69753. // Should we remove this but leave this to user?
  69754. TooltipView.prototype._updateContentNotChangedOnAxis = function (dataByCoordSys) {
  69755. var lastCoordSys = this._lastDataByCoordSys;
  69756. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  69757. contentNotChanged && each$c(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  69758. var lastDataByAxis = lastItemCoordSys.dataByAxis || [];
  69759. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  69760. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  69761. contentNotChanged = contentNotChanged && lastDataByAxis.length === thisDataByAxis.length;
  69762. contentNotChanged && each$c(lastDataByAxis, function (lastItem, indexAxis) {
  69763. var thisItem = thisDataByAxis[indexAxis] || {};
  69764. var lastIndices = lastItem.seriesDataIndices || [];
  69765. var newIndices = thisItem.seriesDataIndices || [];
  69766. contentNotChanged = contentNotChanged && lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  69767. contentNotChanged && each$c(lastIndices, function (lastIdxItem, j) {
  69768. var newIdxItem = newIndices[j];
  69769. contentNotChanged = contentNotChanged && lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  69770. });
  69771. });
  69772. });
  69773. this._lastDataByCoordSys = dataByCoordSys;
  69774. return !!contentNotChanged;
  69775. };
  69776. TooltipView.prototype._hide = function (dispatchAction) {
  69777. // Do not directly hideLater here, because this behavior may be prevented
  69778. // in dispatchAction when showTip is dispatched.
  69779. // FIXME
  69780. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  69781. this._lastDataByCoordSys = null;
  69782. dispatchAction({
  69783. type: 'hideTip',
  69784. from: this.uid
  69785. });
  69786. };
  69787. TooltipView.prototype.dispose = function (ecModel, api) {
  69788. if (env.node) {
  69789. return;
  69790. }
  69791. this._tooltipContent.dispose();
  69792. unregister('itemTooltip', api);
  69793. };
  69794. TooltipView.type = 'tooltip';
  69795. return TooltipView;
  69796. }(ComponentView);
  69797. /**
  69798. * From top to bottom. (the last one should be globalTooltipModel);
  69799. */
  69800. function buildTooltipModel(modelCascade) {
  69801. // Last is always tooltip model.
  69802. var resultModel = modelCascade.pop();
  69803. while (modelCascade.length) {
  69804. var tooltipOpt = modelCascade.pop();
  69805. if (tooltipOpt) {
  69806. if (tooltipOpt instanceof Model) {
  69807. tooltipOpt = tooltipOpt.get('tooltip', true);
  69808. } // In each data item tooltip can be simply write:
  69809. // {
  69810. // value: 10,
  69811. // tooltip: 'Something you need to know'
  69812. // }
  69813. if (isString(tooltipOpt)) {
  69814. tooltipOpt = {
  69815. formatter: tooltipOpt
  69816. };
  69817. }
  69818. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  69819. }
  69820. }
  69821. return resultModel;
  69822. }
  69823. function makeDispatchAction$1(payload, api) {
  69824. return payload.dispatchAction || bind(api.dispatchAction, api);
  69825. }
  69826. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  69827. var size = content.getOuterSize();
  69828. var width = size.width;
  69829. var height = size.height;
  69830. if (gapH != null) {
  69831. // Add extra 2 pixels for this case:
  69832. // At present the "values" in defaut tooltip are using CSS `float: right`.
  69833. // When the right edge of the tooltip box is on the right side of the
  69834. // viewport, the `float` layout might push the "values" to the second line.
  69835. if (x + width + gapH + 2 > viewWidth) {
  69836. x -= width + gapH;
  69837. } else {
  69838. x += gapH;
  69839. }
  69840. }
  69841. if (gapV != null) {
  69842. if (y + height + gapV > viewHeight) {
  69843. y -= height + gapV;
  69844. } else {
  69845. y += gapV;
  69846. }
  69847. }
  69848. return [x, y];
  69849. }
  69850. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  69851. var size = content.getOuterSize();
  69852. var width = size.width;
  69853. var height = size.height;
  69854. x = Math.min(x + width, viewWidth) - width;
  69855. y = Math.min(y + height, viewHeight) - height;
  69856. x = Math.max(x, 0);
  69857. y = Math.max(y, 0);
  69858. return [x, y];
  69859. }
  69860. function calcTooltipPosition(position, rect, contentSize) {
  69861. var domWidth = contentSize[0];
  69862. var domHeight = contentSize[1];
  69863. var gap = 10;
  69864. var offset = 5;
  69865. var x = 0;
  69866. var y = 0;
  69867. var rectWidth = rect.width;
  69868. var rectHeight = rect.height;
  69869. switch (position) {
  69870. case 'inside':
  69871. x = rect.x + rectWidth / 2 - domWidth / 2;
  69872. y = rect.y + rectHeight / 2 - domHeight / 2;
  69873. break;
  69874. case 'top':
  69875. x = rect.x + rectWidth / 2 - domWidth / 2;
  69876. y = rect.y - domHeight - gap;
  69877. break;
  69878. case 'bottom':
  69879. x = rect.x + rectWidth / 2 - domWidth / 2;
  69880. y = rect.y + rectHeight + gap;
  69881. break;
  69882. case 'left':
  69883. x = rect.x - domWidth - gap - offset;
  69884. y = rect.y + rectHeight / 2 - domHeight / 2;
  69885. break;
  69886. case 'right':
  69887. x = rect.x + rectWidth + gap + offset;
  69888. y = rect.y + rectHeight / 2 - domHeight / 2;
  69889. }
  69890. return [x, y];
  69891. }
  69892. function isCenterAlign(align) {
  69893. return align === 'center' || align === 'middle';
  69894. }
  69895. function install$A(registers) {
  69896. use(install$s);
  69897. registers.registerComponentModel(TooltipModel);
  69898. registers.registerComponentView(TooltipView);
  69899. /**
  69900. * @action
  69901. * @property {string} type
  69902. * @property {number} seriesIndex
  69903. * @property {number} dataIndex
  69904. * @property {number} [x]
  69905. * @property {number} [y]
  69906. */
  69907. registers.registerAction({
  69908. type: 'showTip',
  69909. event: 'showTip',
  69910. update: 'tooltip:manuallyShowTip'
  69911. }, // noop
  69912. function () {});
  69913. registers.registerAction({
  69914. type: 'hideTip',
  69915. event: 'hideTip',
  69916. update: 'tooltip:manuallyHideTip'
  69917. }, // noop
  69918. function () {});
  69919. }
  69920. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  69921. function brushPreprocessor(option, isNew) {
  69922. var brushComponents = normalizeToArray(option ? option.brush : []);
  69923. if (!brushComponents.length) {
  69924. return;
  69925. }
  69926. var brushComponentSpecifiedBtns = [];
  69927. each(brushComponents, function (brushOpt) {
  69928. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  69929. if (tbs instanceof Array) {
  69930. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  69931. }
  69932. });
  69933. var toolbox = option && option.toolbox;
  69934. if (isArray(toolbox)) {
  69935. toolbox = toolbox[0];
  69936. }
  69937. if (!toolbox) {
  69938. toolbox = {
  69939. feature: {}
  69940. };
  69941. option.toolbox = [toolbox];
  69942. }
  69943. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  69944. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  69945. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  69946. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  69947. removeDuplicate(brushTypes);
  69948. if (isNew && !brushTypes.length) {
  69949. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  69950. }
  69951. }
  69952. function removeDuplicate(arr) {
  69953. var map = {};
  69954. each(arr, function (val) {
  69955. map[val] = 1;
  69956. });
  69957. arr.length = 0;
  69958. each(map, function (flag, val) {
  69959. arr.push(val);
  69960. });
  69961. }
  69962. var each$d = each;
  69963. function hasKeys(obj) {
  69964. if (obj) {
  69965. for (var name_1 in obj) {
  69966. if (obj.hasOwnProperty(name_1)) {
  69967. return true;
  69968. }
  69969. }
  69970. }
  69971. }
  69972. function createVisualMappings(option, stateList, supplementVisualOption) {
  69973. var visualMappings = {};
  69974. each$d(stateList, function (state) {
  69975. var mappings = visualMappings[state] = createMappings();
  69976. each$d(option[state], function (visualData, visualType) {
  69977. if (!VisualMapping.isValidType(visualType)) {
  69978. return;
  69979. }
  69980. var mappingOption = {
  69981. type: visualType,
  69982. visual: visualData
  69983. };
  69984. supplementVisualOption && supplementVisualOption(mappingOption, state);
  69985. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  69986. // is not supported, such as rendering using gradient color.
  69987. if (visualType === 'opacity') {
  69988. mappingOption = clone(mappingOption);
  69989. mappingOption.type = 'colorAlpha';
  69990. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  69991. }
  69992. });
  69993. });
  69994. return visualMappings;
  69995. function createMappings() {
  69996. var Creater = function () {}; // Make sure hidden fields will not be visited by
  69997. // object iteration (with hasOwnProperty checking).
  69998. Creater.prototype.__hidden = Creater.prototype;
  69999. var obj = new Creater();
  70000. return obj;
  70001. }
  70002. }
  70003. function replaceVisualOption(thisOption, newOption, keys) {
  70004. // Visual attributes merge is not supported, otherwise it
  70005. // brings overcomplicated merge logic. See #2853. So if
  70006. // newOption has anyone of these keys, all of these keys
  70007. // will be reset. Otherwise, all keys remain.
  70008. var has;
  70009. each(keys, function (key) {
  70010. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  70011. has = true;
  70012. }
  70013. });
  70014. has && each(keys, function (key) {
  70015. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  70016. thisOption[key] = clone(newOption[key]);
  70017. } else {
  70018. delete thisOption[key];
  70019. }
  70020. });
  70021. }
  70022. /**
  70023. * @param stateList
  70024. * @param visualMappings
  70025. * @param list
  70026. * @param getValueState param: valueOrIndex, return: state.
  70027. * @param scope Scope for getValueState
  70028. * @param dimension Concrete dimension, if used.
  70029. */
  70030. // ???! handle brush?
  70031. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  70032. var visualTypesMap = {};
  70033. each(stateList, function (state) {
  70034. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  70035. visualTypesMap[state] = visualTypes;
  70036. });
  70037. var dataIndex;
  70038. function getVisual(key) {
  70039. return getItemVisualFromData(data, dataIndex, key);
  70040. }
  70041. function setVisual(key, value) {
  70042. setItemVisualFromData(data, dataIndex, key, value);
  70043. }
  70044. if (dimension == null) {
  70045. data.each(eachItem);
  70046. } else {
  70047. data.each([dimension], eachItem);
  70048. }
  70049. function eachItem(valueOrIndex, index) {
  70050. dataIndex = dimension == null ? valueOrIndex // First argument is index
  70051. : index;
  70052. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  70053. // @ts-ignore
  70054. if (rawDataItem && rawDataItem.visualMap === false) {
  70055. return;
  70056. }
  70057. var valueState = getValueState.call(scope, valueOrIndex);
  70058. var mappings = visualMappings[valueState];
  70059. var visualTypes = visualTypesMap[valueState];
  70060. for (var i = 0, len = visualTypes.length; i < len; i++) {
  70061. var type = visualTypes[i];
  70062. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  70063. }
  70064. }
  70065. }
  70066. /**
  70067. * @param data
  70068. * @param stateList
  70069. * @param visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  70070. * @param getValueState param: valueOrIndex, return: state.
  70071. * @param dim dimension or dimension index.
  70072. */
  70073. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  70074. var visualTypesMap = {};
  70075. each(stateList, function (state) {
  70076. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  70077. visualTypesMap[state] = visualTypes;
  70078. });
  70079. return {
  70080. progress: function progress(params, data) {
  70081. var dimName;
  70082. if (dim != null) {
  70083. dimName = data.getDimension(dim);
  70084. }
  70085. function getVisual(key) {
  70086. return getItemVisualFromData(data, dataIndex, key);
  70087. }
  70088. function setVisual(key, value) {
  70089. setItemVisualFromData(data, dataIndex, key, value);
  70090. }
  70091. var dataIndex;
  70092. while ((dataIndex = params.next()) != null) {
  70093. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  70094. // @ts-ignore
  70095. if (rawDataItem && rawDataItem.visualMap === false) {
  70096. continue;
  70097. }
  70098. var value = dim != null ? data.get(dimName, dataIndex) : dataIndex;
  70099. var valueState = getValueState(value);
  70100. var mappings = visualMappings[valueState];
  70101. var visualTypes = visualTypesMap[valueState];
  70102. for (var i = 0, len = visualTypes.length; i < len; i++) {
  70103. var type = visualTypes[i];
  70104. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  70105. }
  70106. }
  70107. }
  70108. };
  70109. }
  70110. function makeBrushCommonSelectorForSeries(area) {
  70111. var brushType = area.brushType; // Do not use function binding or curry for performance.
  70112. var selectors = {
  70113. point: function (itemLayout) {
  70114. return selector[brushType].point(itemLayout, selectors, area);
  70115. },
  70116. rect: function (itemLayout) {
  70117. return selector[brushType].rect(itemLayout, selectors, area);
  70118. }
  70119. };
  70120. return selectors;
  70121. }
  70122. var selector = {
  70123. lineX: getLineSelectors(0),
  70124. lineY: getLineSelectors(1),
  70125. rect: {
  70126. point: function (itemLayout, selectors, area) {
  70127. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  70128. },
  70129. rect: function (itemLayout, selectors, area) {
  70130. return itemLayout && area.boundingRect.intersect(itemLayout);
  70131. }
  70132. },
  70133. polygon: {
  70134. point: function (itemLayout, selectors, area) {
  70135. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$2(area.range, itemLayout[0], itemLayout[1]);
  70136. },
  70137. rect: function (itemLayout, selectors, area) {
  70138. var points = area.range;
  70139. if (!itemLayout || points.length <= 1) {
  70140. return false;
  70141. }
  70142. var x = itemLayout.x;
  70143. var y = itemLayout.y;
  70144. var width = itemLayout.width;
  70145. var height = itemLayout.height;
  70146. var p = points[0];
  70147. 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)) {
  70148. return true;
  70149. }
  70150. }
  70151. }
  70152. };
  70153. function getLineSelectors(xyIndex) {
  70154. var xy = ['x', 'y'];
  70155. var wh = ['width', 'height'];
  70156. return {
  70157. point: function (itemLayout, selectors, area) {
  70158. if (itemLayout) {
  70159. var range = area.range;
  70160. var p = itemLayout[xyIndex];
  70161. return inLineRange(p, range);
  70162. }
  70163. },
  70164. rect: function (itemLayout, selectors, area) {
  70165. if (itemLayout) {
  70166. var range = area.range;
  70167. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  70168. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  70169. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  70170. }
  70171. }
  70172. };
  70173. }
  70174. function inLineRange(p, range) {
  70175. return range[0] <= p && p <= range[1];
  70176. }
  70177. var STATE_LIST = ['inBrush', 'outOfBrush'];
  70178. var DISPATCH_METHOD = '__ecBrushSelect';
  70179. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  70180. function layoutCovers(ecModel) {
  70181. ecModel.eachComponent({
  70182. mainType: 'brush'
  70183. }, function (brushModel) {
  70184. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  70185. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  70186. });
  70187. }
  70188. /**
  70189. * Register the visual encoding if this modules required.
  70190. */
  70191. function brushVisual(ecModel, api, payload) {
  70192. var brushSelected = [];
  70193. var throttleType;
  70194. var throttleDelay;
  70195. ecModel.eachComponent({
  70196. mainType: 'brush'
  70197. }, function (brushModel) {
  70198. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  70199. brushType: false
  70200. });
  70201. });
  70202. layoutCovers(ecModel);
  70203. ecModel.eachComponent({
  70204. mainType: 'brush'
  70205. }, function (brushModel, brushIndex) {
  70206. var thisBrushSelected = {
  70207. brushId: brushModel.id,
  70208. brushIndex: brushIndex,
  70209. brushName: brushModel.name,
  70210. areas: clone(brushModel.areas),
  70211. selected: []
  70212. }; // Every brush component exists in event params, convenient
  70213. // for user to find by index.
  70214. brushSelected.push(thisBrushSelected);
  70215. var brushOption = brushModel.option;
  70216. var brushLink = brushOption.brushLink;
  70217. var linkedSeriesMap = [];
  70218. var selectedDataIndexForLink = [];
  70219. var rangeInfoBySeries = [];
  70220. var hasBrushExists = false;
  70221. if (!brushIndex) {
  70222. // Only the first throttle setting works.
  70223. throttleType = brushOption.throttleType;
  70224. throttleDelay = brushOption.throttleDelay;
  70225. } // Add boundingRect and selectors to range.
  70226. var areas = map(brushModel.areas, function (area) {
  70227. var builder = boundingRectBuilders[area.brushType];
  70228. var selectableArea = defaults({
  70229. boundingRect: builder ? builder(area) : void 0
  70230. }, area);
  70231. selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
  70232. return selectableArea;
  70233. });
  70234. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  70235. mappingOption.mappingMethod = 'fixed';
  70236. });
  70237. isArray(brushLink) && each(brushLink, function (seriesIndex) {
  70238. linkedSeriesMap[seriesIndex] = 1;
  70239. });
  70240. function linkOthers(seriesIndex) {
  70241. return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
  70242. } // If no supported brush or no brush on the series,
  70243. // all visuals should be in original state.
  70244. function brushed(rangeInfoList) {
  70245. return !!rangeInfoList.length;
  70246. }
  70247. /**
  70248. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  70249. *
  70250. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  70251. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  70252. * └!hasBrushExist┘ └nothing.
  70253. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  70254. * └!hasBrushExist┘ └nothing.
  70255. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  70256. * !brushed┘ └nothing.
  70257. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  70258. */
  70259. // Step A
  70260. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  70261. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  70262. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  70263. });
  70264. function stepAParallel(seriesModel, seriesIndex) {
  70265. var coordSys = seriesModel.coordinateSystem;
  70266. hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
  70267. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  70268. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  70269. });
  70270. }
  70271. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  70272. if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
  70273. return;
  70274. }
  70275. each(areas, function (area) {
  70276. if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
  70277. rangeInfoList.push(area);
  70278. }
  70279. hasBrushExists = hasBrushExists || brushed(rangeInfoList);
  70280. });
  70281. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  70282. var data_1 = seriesModel.getData();
  70283. data_1.each(function (dataIndex) {
  70284. if (checkInRange(seriesModel, rangeInfoList, data_1, dataIndex)) {
  70285. selectedDataIndexForLink[dataIndex] = 1;
  70286. }
  70287. });
  70288. }
  70289. } // Step B
  70290. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  70291. var seriesBrushSelected = {
  70292. seriesId: seriesModel.id,
  70293. seriesIndex: seriesIndex,
  70294. seriesName: seriesModel.name,
  70295. dataIndex: []
  70296. }; // Every series exists in event params, convenient
  70297. // for user to find series by seriesIndex.
  70298. thisBrushSelected.selected.push(seriesBrushSelected);
  70299. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  70300. var data = seriesModel.getData();
  70301. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  70302. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  70303. } : function (dataIndex) {
  70304. return checkInRange(seriesModel, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  70305. }; // If no supported brush or no brush, all visuals are in original state.
  70306. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  70307. });
  70308. });
  70309. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  70310. }
  70311. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  70312. // This event will not be triggered when `setOpion`, otherwise dead lock may
  70313. // triggered when do `setOption` in event listener, which we do not find
  70314. // satisfactory way to solve yet. Some considered resolutions:
  70315. // (a) Diff with prevoius selected data ant only trigger event when changed.
  70316. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  70317. // also detect value changes in selected data) might bring complexity or fragility.
  70318. // (b) Use spectial param like `silent` to suppress event triggering.
  70319. // But such kind of volatile param may be weird in `setOption`.
  70320. if (!payload) {
  70321. return;
  70322. }
  70323. var zr = api.getZr();
  70324. if (zr[DISPATCH_FLAG]) {
  70325. return;
  70326. }
  70327. if (!zr[DISPATCH_METHOD]) {
  70328. zr[DISPATCH_METHOD] = doDispatch;
  70329. }
  70330. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  70331. fn(api, brushSelected);
  70332. }
  70333. function doDispatch(api, brushSelected) {
  70334. if (!api.isDisposed()) {
  70335. var zr = api.getZr();
  70336. zr[DISPATCH_FLAG] = true;
  70337. api.dispatchAction({
  70338. type: 'brushSelect',
  70339. batch: brushSelected
  70340. });
  70341. zr[DISPATCH_FLAG] = false;
  70342. }
  70343. }
  70344. function checkInRange(seriesModel, rangeInfoList, data, dataIndex) {
  70345. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  70346. var area = rangeInfoList[i];
  70347. if (seriesModel.brushSelector(dataIndex, data, area.selectors, area)) {
  70348. return true;
  70349. }
  70350. }
  70351. }
  70352. function brushModelNotControll(brushModel, seriesIndex) {
  70353. var seriesIndices = brushModel.option.seriesIndex;
  70354. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  70355. }
  70356. var boundingRectBuilders = {
  70357. rect: function (area) {
  70358. return getBoundingRectFromMinMax(area.range);
  70359. },
  70360. polygon: function (area) {
  70361. var minMax;
  70362. var range = area.range;
  70363. for (var i = 0, len = range.length; i < len; i++) {
  70364. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  70365. var rg = range[i];
  70366. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  70367. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  70368. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  70369. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  70370. }
  70371. return minMax && getBoundingRectFromMinMax(minMax);
  70372. }
  70373. };
  70374. function getBoundingRectFromMinMax(minMax) {
  70375. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  70376. }
  70377. var BrushView =
  70378. /** @class */
  70379. function (_super) {
  70380. __extends(BrushView, _super);
  70381. function BrushView() {
  70382. var _this = _super !== null && _super.apply(this, arguments) || this;
  70383. _this.type = BrushView.type;
  70384. return _this;
  70385. }
  70386. BrushView.prototype.init = function (ecModel, api) {
  70387. this.ecModel = ecModel;
  70388. this.api = api;
  70389. this.model;
  70390. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  70391. };
  70392. BrushView.prototype.render = function (brushModel, ecModel, api, payload) {
  70393. this.model = brushModel;
  70394. this._updateController(brushModel, ecModel, api, payload);
  70395. };
  70396. BrushView.prototype.updateTransform = function (brushModel, ecModel, api, payload) {
  70397. // PENDING: `updateTransform` is a little tricky, whose layout need
  70398. // to be calculate mandatorily and other stages will not be performed.
  70399. // Take care the correctness of the logic. See #11754 .
  70400. layoutCovers(ecModel);
  70401. this._updateController(brushModel, ecModel, api, payload);
  70402. };
  70403. BrushView.prototype.updateVisual = function (brushModel, ecModel, api, payload) {
  70404. this.updateTransform(brushModel, ecModel, api, payload);
  70405. };
  70406. BrushView.prototype.updateView = function (brushModel, ecModel, api, payload) {
  70407. this._updateController(brushModel, ecModel, api, payload);
  70408. };
  70409. BrushView.prototype._updateController = function (brushModel, ecModel, api, payload) {
  70410. // Do not update controller when drawing.
  70411. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  70412. }; // updateLayout: updateController,
  70413. // updateVisual: updateController,
  70414. BrushView.prototype.dispose = function () {
  70415. this._brushController.dispose();
  70416. };
  70417. BrushView.prototype._onBrush = function (eventParam) {
  70418. var modelId = this.model.id;
  70419. var areas = this.model.brushTargetManager.setOutputRanges(eventParam.areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  70420. // emits the same params with the last drag move event, and
  70421. // may have some delay when using touch pad, which makes
  70422. // animation not smooth (when using debounce).
  70423. (!eventParam.isEnd || eventParam.removeOnClick) && this.api.dispatchAction({
  70424. type: 'brush',
  70425. brushId: modelId,
  70426. areas: clone(areas),
  70427. $from: modelId
  70428. });
  70429. eventParam.isEnd && this.api.dispatchAction({
  70430. type: 'brushEnd',
  70431. brushId: modelId,
  70432. areas: clone(areas),
  70433. $from: modelId
  70434. });
  70435. };
  70436. BrushView.type = 'brush';
  70437. return BrushView;
  70438. }(ComponentView);
  70439. var DEFAULT_OUT_OF_BRUSH_COLOR = '#ddd';
  70440. var BrushModel =
  70441. /** @class */
  70442. function (_super) {
  70443. __extends(BrushModel, _super);
  70444. function BrushModel() {
  70445. var _this = _super !== null && _super.apply(this, arguments) || this;
  70446. _this.type = BrushModel.type;
  70447. /**
  70448. * @readOnly
  70449. */
  70450. _this.areas = [];
  70451. /**
  70452. * Current brush painting area settings.
  70453. * @readOnly
  70454. */
  70455. _this.brushOption = {};
  70456. return _this;
  70457. }
  70458. BrushModel.prototype.optionUpdated = function (newOption, isInit) {
  70459. var thisOption = this.option;
  70460. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  70461. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  70462. thisOption.outOfBrush = thisOption.outOfBrush || {
  70463. color: DEFAULT_OUT_OF_BRUSH_COLOR
  70464. };
  70465. if (!inBrush.hasOwnProperty('liftZ')) {
  70466. // Bigger than the highlight z lift, otherwise it will
  70467. // be effected by the highlight z when brush.
  70468. inBrush.liftZ = 5;
  70469. }
  70470. };
  70471. /**
  70472. * If `areas` is null/undefined, range state remain.
  70473. */
  70474. BrushModel.prototype.setAreas = function (areas) {
  70475. if ("development" !== 'production') {
  70476. assert(isArray(areas));
  70477. each(areas, function (area) {
  70478. assert(area.brushType, 'Illegal areas');
  70479. });
  70480. } // If areas is null/undefined, range state remain.
  70481. // This helps user to dispatchAction({type: 'brush'}) with no areas
  70482. // set but just want to get the current brush select info from a `brush` event.
  70483. if (!areas) {
  70484. return;
  70485. }
  70486. this.areas = map(areas, function (area) {
  70487. return generateBrushOption(this.option, area);
  70488. }, this);
  70489. };
  70490. /**
  70491. * Set the current painting brush option.
  70492. */
  70493. BrushModel.prototype.setBrushOption = function (brushOption) {
  70494. this.brushOption = generateBrushOption(this.option, brushOption);
  70495. this.brushType = this.brushOption.brushType;
  70496. };
  70497. BrushModel.type = 'brush';
  70498. BrushModel.dependencies = ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'];
  70499. BrushModel.defaultOption = {
  70500. seriesIndex: 'all',
  70501. brushType: 'rect',
  70502. brushMode: 'single',
  70503. transformable: true,
  70504. brushStyle: {
  70505. borderWidth: 1,
  70506. color: 'rgba(210,219,238,0.3)',
  70507. borderColor: '#D2DBEE'
  70508. },
  70509. throttleType: 'fixRate',
  70510. throttleDelay: 0,
  70511. removeOnClick: true,
  70512. z: 10000
  70513. };
  70514. return BrushModel;
  70515. }(ComponentModel);
  70516. function generateBrushOption(option, brushOption) {
  70517. return merge({
  70518. brushType: option.brushType,
  70519. brushMode: option.brushMode,
  70520. transformable: option.transformable,
  70521. brushStyle: new Model(option.brushStyle).getItemStyle(),
  70522. removeOnClick: option.removeOnClick,
  70523. z: option.z
  70524. }, brushOption, true);
  70525. }
  70526. var ICON_TYPES = ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'];
  70527. var BrushFeature =
  70528. /** @class */
  70529. function (_super) {
  70530. __extends(BrushFeature, _super);
  70531. function BrushFeature() {
  70532. return _super !== null && _super.apply(this, arguments) || this;
  70533. }
  70534. BrushFeature.prototype.render = function (featureModel, ecModel, api) {
  70535. var brushType;
  70536. var brushMode;
  70537. var isBrushed;
  70538. ecModel.eachComponent({
  70539. mainType: 'brush'
  70540. }, function (brushModel) {
  70541. brushType = brushModel.brushType;
  70542. brushMode = brushModel.brushOption.brushMode || 'single';
  70543. isBrushed = isBrushed || !!brushModel.areas.length;
  70544. });
  70545. this._brushType = brushType;
  70546. this._brushMode = brushMode;
  70547. each(featureModel.get('type', true), function (type) {
  70548. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  70549. });
  70550. };
  70551. BrushFeature.prototype.updateView = function (featureModel, ecModel, api) {
  70552. this.render(featureModel, ecModel, api);
  70553. };
  70554. BrushFeature.prototype.getIcons = function () {
  70555. var model = this.model;
  70556. var availableIcons = model.get('icon', true);
  70557. var icons = {};
  70558. each(model.get('type', true), function (type) {
  70559. if (availableIcons[type]) {
  70560. icons[type] = availableIcons[type];
  70561. }
  70562. });
  70563. return icons;
  70564. };
  70565. BrushFeature.prototype.onclick = function (ecModel, api, type) {
  70566. var brushType = this._brushType;
  70567. var brushMode = this._brushMode;
  70568. if (type === 'clear') {
  70569. // Trigger parallel action firstly
  70570. api.dispatchAction({
  70571. type: 'axisAreaSelect',
  70572. intervals: []
  70573. });
  70574. api.dispatchAction({
  70575. type: 'brush',
  70576. command: 'clear',
  70577. // Clear all areas of all brush components.
  70578. areas: []
  70579. });
  70580. } else {
  70581. api.dispatchAction({
  70582. type: 'takeGlobalCursor',
  70583. key: 'brush',
  70584. brushOption: {
  70585. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  70586. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  70587. }
  70588. });
  70589. }
  70590. };
  70591. BrushFeature.getDefaultOption = function (ecModel) {
  70592. var defaultOption = {
  70593. show: true,
  70594. type: ICON_TYPES.slice(),
  70595. icon: {
  70596. /* eslint-disable */
  70597. 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',
  70598. 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',
  70599. 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',
  70600. 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',
  70601. 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',
  70602. 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
  70603. /* eslint-enable */
  70604. },
  70605. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  70606. title: ecModel.getLocale(['toolbox', 'brush', 'title'])
  70607. };
  70608. return defaultOption;
  70609. };
  70610. return BrushFeature;
  70611. }(ToolboxFeature);
  70612. function install$B(registers) {
  70613. registers.registerComponentView(BrushView);
  70614. registers.registerComponentModel(BrushModel);
  70615. registers.registerPreprocessor(brushPreprocessor);
  70616. registers.registerVisual(registers.PRIORITY.VISUAL.BRUSH, brushVisual);
  70617. registers.registerAction({
  70618. type: 'brush',
  70619. event: 'brush',
  70620. update: 'updateVisual'
  70621. }, function (payload, ecModel) {
  70622. ecModel.eachComponent({
  70623. mainType: 'brush',
  70624. query: payload
  70625. }, function (brushModel) {
  70626. brushModel.setAreas(payload.areas);
  70627. });
  70628. });
  70629. /**
  70630. * payload: {
  70631. * brushComponents: [
  70632. * {
  70633. * brushId,
  70634. * brushIndex,
  70635. * brushName,
  70636. * series: [
  70637. * {
  70638. * seriesId,
  70639. * seriesIndex,
  70640. * seriesName,
  70641. * rawIndices: [21, 34, ...]
  70642. * },
  70643. * ...
  70644. * ]
  70645. * },
  70646. * ...
  70647. * ]
  70648. * }
  70649. */
  70650. registers.registerAction({
  70651. type: 'brushSelect',
  70652. event: 'brushSelected',
  70653. update: 'none'
  70654. }, function () {});
  70655. registers.registerAction({
  70656. type: 'brushEnd',
  70657. event: 'brushEnd',
  70658. update: 'none'
  70659. }, function () {});
  70660. registerFeature('brush', BrushFeature);
  70661. }
  70662. var TitleModel =
  70663. /** @class */
  70664. function (_super) {
  70665. __extends(TitleModel, _super);
  70666. function TitleModel() {
  70667. var _this = _super !== null && _super.apply(this, arguments) || this;
  70668. _this.type = TitleModel.type;
  70669. _this.layoutMode = {
  70670. type: 'box',
  70671. ignoreSize: true
  70672. };
  70673. return _this;
  70674. }
  70675. TitleModel.type = 'title';
  70676. TitleModel.defaultOption = {
  70677. zlevel: 0,
  70678. z: 6,
  70679. show: true,
  70680. text: '',
  70681. target: 'blank',
  70682. subtext: '',
  70683. subtarget: 'blank',
  70684. left: 0,
  70685. top: 0,
  70686. backgroundColor: 'rgba(0,0,0,0)',
  70687. borderColor: '#ccc',
  70688. borderWidth: 0,
  70689. padding: 5,
  70690. itemGap: 10,
  70691. textStyle: {
  70692. fontSize: 18,
  70693. fontWeight: 'bold',
  70694. color: '#464646'
  70695. },
  70696. subtextStyle: {
  70697. fontSize: 12,
  70698. color: '#6E7079'
  70699. }
  70700. };
  70701. return TitleModel;
  70702. }(ComponentModel); // View
  70703. var TitleView =
  70704. /** @class */
  70705. function (_super) {
  70706. __extends(TitleView, _super);
  70707. function TitleView() {
  70708. var _this = _super !== null && _super.apply(this, arguments) || this;
  70709. _this.type = TitleView.type;
  70710. return _this;
  70711. }
  70712. TitleView.prototype.render = function (titleModel, ecModel, api) {
  70713. this.group.removeAll();
  70714. if (!titleModel.get('show')) {
  70715. return;
  70716. }
  70717. var group = this.group;
  70718. var textStyleModel = titleModel.getModel('textStyle');
  70719. var subtextStyleModel = titleModel.getModel('subtextStyle');
  70720. var textAlign = titleModel.get('textAlign');
  70721. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  70722. var textEl = new ZRText({
  70723. style: createTextStyle(textStyleModel, {
  70724. text: titleModel.get('text'),
  70725. fill: textStyleModel.getTextColor()
  70726. }, {
  70727. disableBox: true
  70728. }),
  70729. z2: 10
  70730. });
  70731. var textRect = textEl.getBoundingRect();
  70732. var subText = titleModel.get('subtext');
  70733. var subTextEl = new ZRText({
  70734. style: createTextStyle(subtextStyleModel, {
  70735. text: subText,
  70736. fill: subtextStyleModel.getTextColor(),
  70737. y: textRect.height + titleModel.get('itemGap'),
  70738. verticalAlign: 'top'
  70739. }, {
  70740. disableBox: true
  70741. }),
  70742. z2: 10
  70743. });
  70744. var link = titleModel.get('link');
  70745. var sublink = titleModel.get('sublink');
  70746. var triggerEvent = titleModel.get('triggerEvent', true);
  70747. textEl.silent = !link && !triggerEvent;
  70748. subTextEl.silent = !sublink && !triggerEvent;
  70749. if (link) {
  70750. textEl.on('click', function () {
  70751. windowOpen(link, '_' + titleModel.get('target'));
  70752. });
  70753. }
  70754. if (sublink) {
  70755. subTextEl.on('click', function () {
  70756. windowOpen(sublink, '_' + titleModel.get('subtarget'));
  70757. });
  70758. }
  70759. getECData(textEl).eventData = getECData(subTextEl).eventData = triggerEvent ? {
  70760. componentType: 'title',
  70761. componentIndex: titleModel.componentIndex
  70762. } : null;
  70763. group.add(textEl);
  70764. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  70765. var groupRect = group.getBoundingRect();
  70766. var layoutOption = titleModel.getBoxLayoutParams();
  70767. layoutOption.width = groupRect.width;
  70768. layoutOption.height = groupRect.height;
  70769. var layoutRect = getLayoutRect(layoutOption, {
  70770. width: api.getWidth(),
  70771. height: api.getHeight()
  70772. }, titleModel.get('padding')); // Adjust text align based on position
  70773. if (!textAlign) {
  70774. // Align left if title is on the left. center and right is same
  70775. textAlign = titleModel.get('left') || titleModel.get('right'); // @ts-ignore
  70776. if (textAlign === 'middle') {
  70777. textAlign = 'center';
  70778. } // Adjust layout by text align
  70779. if (textAlign === 'right') {
  70780. layoutRect.x += layoutRect.width;
  70781. } else if (textAlign === 'center') {
  70782. layoutRect.x += layoutRect.width / 2;
  70783. }
  70784. }
  70785. if (!textVerticalAlign) {
  70786. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom'); // @ts-ignore
  70787. if (textVerticalAlign === 'center') {
  70788. textVerticalAlign = 'middle';
  70789. }
  70790. if (textVerticalAlign === 'bottom') {
  70791. layoutRect.y += layoutRect.height;
  70792. } else if (textVerticalAlign === 'middle') {
  70793. layoutRect.y += layoutRect.height / 2;
  70794. }
  70795. textVerticalAlign = textVerticalAlign || 'top';
  70796. }
  70797. group.x = layoutRect.x;
  70798. group.y = layoutRect.y;
  70799. group.markRedraw();
  70800. var alignStyle = {
  70801. align: textAlign,
  70802. verticalAlign: textVerticalAlign
  70803. };
  70804. textEl.setStyle(alignStyle);
  70805. subTextEl.setStyle(alignStyle); // Render background
  70806. // Get groupRect again because textAlign has been changed
  70807. groupRect = group.getBoundingRect();
  70808. var padding = layoutRect.margin;
  70809. var style = titleModel.getItemStyle(['color', 'opacity']);
  70810. style.fill = titleModel.get('backgroundColor');
  70811. var rect = new Rect({
  70812. shape: {
  70813. x: groupRect.x - padding[3],
  70814. y: groupRect.y - padding[0],
  70815. width: groupRect.width + padding[1] + padding[3],
  70816. height: groupRect.height + padding[0] + padding[2],
  70817. r: titleModel.get('borderRadius')
  70818. },
  70819. style: style,
  70820. subPixelOptimize: true,
  70821. silent: true
  70822. });
  70823. group.add(rect);
  70824. };
  70825. TitleView.type = 'title';
  70826. return TitleView;
  70827. }(ComponentView);
  70828. function install$C(registers) {
  70829. registers.registerComponentModel(TitleModel);
  70830. registers.registerComponentView(TitleView);
  70831. }
  70832. var TimelineModel =
  70833. /** @class */
  70834. function (_super) {
  70835. __extends(TimelineModel, _super);
  70836. function TimelineModel() {
  70837. var _this = _super !== null && _super.apply(this, arguments) || this;
  70838. _this.type = TimelineModel.type;
  70839. _this.layoutMode = 'box';
  70840. return _this;
  70841. }
  70842. /**
  70843. * @override
  70844. */
  70845. TimelineModel.prototype.init = function (option, parentModel, ecModel) {
  70846. this.mergeDefaultAndTheme(option, ecModel);
  70847. this._initData();
  70848. };
  70849. /**
  70850. * @override
  70851. */
  70852. TimelineModel.prototype.mergeOption = function (option) {
  70853. _super.prototype.mergeOption.apply(this, arguments);
  70854. this._initData();
  70855. };
  70856. TimelineModel.prototype.setCurrentIndex = function (currentIndex) {
  70857. if (currentIndex == null) {
  70858. currentIndex = this.option.currentIndex;
  70859. }
  70860. var count = this._data.count();
  70861. if (this.option.loop) {
  70862. currentIndex = (currentIndex % count + count) % count;
  70863. } else {
  70864. currentIndex >= count && (currentIndex = count - 1);
  70865. currentIndex < 0 && (currentIndex = 0);
  70866. }
  70867. this.option.currentIndex = currentIndex;
  70868. };
  70869. /**
  70870. * @return {number} currentIndex
  70871. */
  70872. TimelineModel.prototype.getCurrentIndex = function () {
  70873. return this.option.currentIndex;
  70874. };
  70875. /**
  70876. * @return {boolean}
  70877. */
  70878. TimelineModel.prototype.isIndexMax = function () {
  70879. return this.getCurrentIndex() >= this._data.count() - 1;
  70880. };
  70881. /**
  70882. * @param {boolean} state true: play, false: stop
  70883. */
  70884. TimelineModel.prototype.setPlayState = function (state) {
  70885. this.option.autoPlay = !!state;
  70886. };
  70887. /**
  70888. * @return {boolean} true: play, false: stop
  70889. */
  70890. TimelineModel.prototype.getPlayState = function () {
  70891. return !!this.option.autoPlay;
  70892. };
  70893. /**
  70894. * @private
  70895. */
  70896. TimelineModel.prototype._initData = function () {
  70897. var thisOption = this.option;
  70898. var dataArr = thisOption.data || [];
  70899. var axisType = thisOption.axisType;
  70900. var names = this._names = [];
  70901. var processedDataArr;
  70902. if (axisType === 'category') {
  70903. processedDataArr = [];
  70904. each(dataArr, function (item, index) {
  70905. var value = convertOptionIdName(getDataItemValue(item), '');
  70906. var newItem;
  70907. if (isObject(item)) {
  70908. newItem = clone(item);
  70909. newItem.value = index;
  70910. } else {
  70911. newItem = index;
  70912. }
  70913. processedDataArr.push(newItem);
  70914. names.push(value);
  70915. });
  70916. } else {
  70917. processedDataArr = dataArr;
  70918. }
  70919. var dimType = {
  70920. category: 'ordinal',
  70921. time: 'time',
  70922. value: 'number'
  70923. }[axisType] || 'number';
  70924. var data = this._data = new List([{
  70925. name: 'value',
  70926. type: dimType
  70927. }], this);
  70928. data.initData(processedDataArr, names);
  70929. };
  70930. TimelineModel.prototype.getData = function () {
  70931. return this._data;
  70932. };
  70933. /**
  70934. * @public
  70935. * @return {Array.<string>} categoreis
  70936. */
  70937. TimelineModel.prototype.getCategories = function () {
  70938. if (this.get('axisType') === 'category') {
  70939. return this._names.slice();
  70940. }
  70941. };
  70942. TimelineModel.type = 'timeline';
  70943. /**
  70944. * @protected
  70945. */
  70946. TimelineModel.defaultOption = {
  70947. zlevel: 0,
  70948. z: 4,
  70949. show: true,
  70950. axisType: 'time',
  70951. realtime: true,
  70952. left: '20%',
  70953. top: null,
  70954. right: '20%',
  70955. bottom: 0,
  70956. width: null,
  70957. height: 40,
  70958. padding: 5,
  70959. controlPosition: 'left',
  70960. autoPlay: false,
  70961. rewind: false,
  70962. loop: true,
  70963. playInterval: 2000,
  70964. currentIndex: 0,
  70965. itemStyle: {},
  70966. label: {
  70967. color: '#000'
  70968. },
  70969. data: []
  70970. };
  70971. return TimelineModel;
  70972. }(ComponentModel);
  70973. var SliderTimelineModel =
  70974. /** @class */
  70975. function (_super) {
  70976. __extends(SliderTimelineModel, _super);
  70977. function SliderTimelineModel() {
  70978. var _this = _super !== null && _super.apply(this, arguments) || this;
  70979. _this.type = SliderTimelineModel.type;
  70980. return _this;
  70981. }
  70982. SliderTimelineModel.type = 'timeline.slider';
  70983. /**
  70984. * @protected
  70985. */
  70986. SliderTimelineModel.defaultOption = inheritDefaultOption(TimelineModel.defaultOption, {
  70987. backgroundColor: 'rgba(0,0,0,0)',
  70988. borderColor: '#ccc',
  70989. borderWidth: 0,
  70990. orient: 'horizontal',
  70991. inverse: false,
  70992. tooltip: {
  70993. trigger: 'item' // data item may also have tootip attr.
  70994. },
  70995. symbol: 'circle',
  70996. symbolSize: 12,
  70997. lineStyle: {
  70998. show: true,
  70999. width: 2,
  71000. color: '#DAE1F5'
  71001. },
  71002. label: {
  71003. position: 'auto',
  71004. // When using number, label position is not
  71005. // restricted by viewRect.
  71006. // positive: right/bottom, negative: left/top
  71007. show: true,
  71008. interval: 'auto',
  71009. rotate: 0,
  71010. // formatter: null,
  71011. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  71012. color: '#A4B1D7'
  71013. },
  71014. itemStyle: {
  71015. color: '#A4B1D7',
  71016. borderWidth: 1
  71017. },
  71018. checkpointStyle: {
  71019. symbol: 'circle',
  71020. symbolSize: 15,
  71021. color: '#316bf3',
  71022. borderColor: '#fff',
  71023. borderWidth: 2,
  71024. shadowBlur: 2,
  71025. shadowOffsetX: 1,
  71026. shadowOffsetY: 1,
  71027. shadowColor: 'rgba(0, 0, 0, 0.3)',
  71028. // borderColor: 'rgba(194,53,49, 0.5)',
  71029. animation: true,
  71030. animationDuration: 300,
  71031. animationEasing: 'quinticInOut'
  71032. },
  71033. controlStyle: {
  71034. show: true,
  71035. showPlayBtn: true,
  71036. showPrevBtn: true,
  71037. showNextBtn: true,
  71038. itemSize: 24,
  71039. itemGap: 12,
  71040. position: 'left',
  71041. 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',
  71042. 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',
  71043. 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',
  71044. 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',
  71045. prevBtnSize: 18,
  71046. nextBtnSize: 18,
  71047. color: '#A4B1D7',
  71048. borderColor: '#A4B1D7',
  71049. borderWidth: 1
  71050. },
  71051. emphasis: {
  71052. label: {
  71053. show: true,
  71054. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  71055. color: '#6f778d'
  71056. },
  71057. itemStyle: {
  71058. color: '#316BF3'
  71059. },
  71060. controlStyle: {
  71061. color: '#316BF3',
  71062. borderColor: '#316BF3',
  71063. borderWidth: 2
  71064. }
  71065. },
  71066. progress: {
  71067. lineStyle: {
  71068. color: '#316BF3'
  71069. },
  71070. itemStyle: {
  71071. color: '#316BF3'
  71072. },
  71073. label: {
  71074. color: '#6f778d'
  71075. }
  71076. },
  71077. data: []
  71078. });
  71079. return SliderTimelineModel;
  71080. }(TimelineModel);
  71081. mixin(SliderTimelineModel, DataFormatMixin.prototype);
  71082. var TimelineView =
  71083. /** @class */
  71084. function (_super) {
  71085. __extends(TimelineView, _super);
  71086. function TimelineView() {
  71087. var _this = _super !== null && _super.apply(this, arguments) || this;
  71088. _this.type = TimelineView.type;
  71089. return _this;
  71090. }
  71091. TimelineView.type = 'timeline';
  71092. return TimelineView;
  71093. }(ComponentView);
  71094. /**
  71095. * Extend axis 2d
  71096. */
  71097. var TimelineAxis =
  71098. /** @class */
  71099. function (_super) {
  71100. __extends(TimelineAxis, _super);
  71101. function TimelineAxis(dim, scale, coordExtent, axisType) {
  71102. var _this = _super.call(this, dim, scale, coordExtent) || this;
  71103. _this.type = axisType || 'value';
  71104. return _this;
  71105. }
  71106. /**
  71107. * @override
  71108. */
  71109. TimelineAxis.prototype.getLabelModel = function () {
  71110. // Force override
  71111. return this.model.getModel('label');
  71112. };
  71113. /**
  71114. * @override
  71115. */
  71116. TimelineAxis.prototype.isHorizontal = function () {
  71117. return this.model.get('orient') === 'horizontal';
  71118. };
  71119. return TimelineAxis;
  71120. }(Axis);
  71121. var PI$8 = Math.PI;
  71122. var labelDataIndexStore = makeInner();
  71123. var SliderTimelineView =
  71124. /** @class */
  71125. function (_super) {
  71126. __extends(SliderTimelineView, _super);
  71127. function SliderTimelineView() {
  71128. var _this = _super !== null && _super.apply(this, arguments) || this;
  71129. _this.type = SliderTimelineView.type;
  71130. return _this;
  71131. }
  71132. SliderTimelineView.prototype.init = function (ecModel, api) {
  71133. this.api = api;
  71134. };
  71135. /**
  71136. * @override
  71137. */
  71138. SliderTimelineView.prototype.render = function (timelineModel, ecModel, api) {
  71139. this.model = timelineModel;
  71140. this.api = api;
  71141. this.ecModel = ecModel;
  71142. this.group.removeAll();
  71143. if (timelineModel.get('show', true)) {
  71144. var layoutInfo_1 = this._layout(timelineModel, api);
  71145. var mainGroup_1 = this._createGroup('_mainGroup');
  71146. var labelGroup = this._createGroup('_labelGroup');
  71147. var axis_1 = this._axis = this._createAxis(layoutInfo_1, timelineModel);
  71148. timelineModel.formatTooltip = function (dataIndex) {
  71149. var name = axis_1.scale.getLabel({
  71150. value: dataIndex
  71151. });
  71152. return createTooltipMarkup('nameValue', {
  71153. noName: true,
  71154. value: name
  71155. });
  71156. };
  71157. each(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  71158. this['_render' + name](layoutInfo_1, mainGroup_1, axis_1, timelineModel);
  71159. }, this);
  71160. this._renderAxisLabel(layoutInfo_1, labelGroup, axis_1, timelineModel);
  71161. this._position(layoutInfo_1, timelineModel);
  71162. }
  71163. this._doPlayStop();
  71164. this._updateTicksStatus();
  71165. };
  71166. /**
  71167. * @override
  71168. */
  71169. SliderTimelineView.prototype.remove = function () {
  71170. this._clearTimer();
  71171. this.group.removeAll();
  71172. };
  71173. /**
  71174. * @override
  71175. */
  71176. SliderTimelineView.prototype.dispose = function () {
  71177. this._clearTimer();
  71178. };
  71179. SliderTimelineView.prototype._layout = function (timelineModel, api) {
  71180. var labelPosOpt = timelineModel.get(['label', 'position']);
  71181. var orient = timelineModel.get('orient');
  71182. var viewRect = getViewRect$5(timelineModel, api);
  71183. var parsedLabelPos; // Auto label offset.
  71184. if (labelPosOpt == null || labelPosOpt === 'auto') {
  71185. parsedLabelPos = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  71186. } else if (isString(labelPosOpt)) {
  71187. parsedLabelPos = {
  71188. horizontal: {
  71189. top: '-',
  71190. bottom: '+'
  71191. },
  71192. vertical: {
  71193. left: '-',
  71194. right: '+'
  71195. }
  71196. }[orient][labelPosOpt];
  71197. } else {
  71198. // is number
  71199. parsedLabelPos = labelPosOpt;
  71200. }
  71201. var labelAlignMap = {
  71202. horizontal: 'center',
  71203. vertical: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'left' : 'right'
  71204. };
  71205. var labelBaselineMap = {
  71206. horizontal: parsedLabelPos >= 0 || parsedLabelPos === '+' ? 'top' : 'bottom',
  71207. vertical: 'middle'
  71208. };
  71209. var rotationMap = {
  71210. horizontal: 0,
  71211. vertical: PI$8 / 2
  71212. }; // Position
  71213. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  71214. var controlModel = timelineModel.getModel('controlStyle');
  71215. var showControl = controlModel.get('show', true);
  71216. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  71217. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  71218. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  71219. var labelRotation = timelineModel.get(['label', 'rotate']) || 0;
  71220. labelRotation = labelRotation * PI$8 / 180; // To radian.
  71221. var playPosition;
  71222. var prevBtnPosition;
  71223. var nextBtnPosition;
  71224. var controlPosition = controlModel.get('position', true);
  71225. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  71226. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  71227. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  71228. var xLeft = 0;
  71229. var xRight = mainLength; // position[0] means left, position[1] means middle.
  71230. if (controlPosition === 'left' || controlPosition === 'bottom') {
  71231. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  71232. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  71233. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  71234. } else {
  71235. // 'top' 'right'
  71236. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  71237. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  71238. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  71239. }
  71240. var axisExtent = [xLeft, xRight];
  71241. if (timelineModel.get('inverse')) {
  71242. axisExtent.reverse();
  71243. }
  71244. return {
  71245. viewRect: viewRect,
  71246. mainLength: mainLength,
  71247. orient: orient,
  71248. rotation: rotationMap[orient],
  71249. labelRotation: labelRotation,
  71250. labelPosOpt: parsedLabelPos,
  71251. labelAlign: timelineModel.get(['label', 'align']) || labelAlignMap[orient],
  71252. labelBaseline: timelineModel.get(['label', 'verticalAlign']) || timelineModel.get(['label', 'baseline']) || labelBaselineMap[orient],
  71253. // Based on mainGroup.
  71254. playPosition: playPosition,
  71255. prevBtnPosition: prevBtnPosition,
  71256. nextBtnPosition: nextBtnPosition,
  71257. axisExtent: axisExtent,
  71258. controlSize: controlSize,
  71259. controlGap: controlGap
  71260. };
  71261. };
  71262. SliderTimelineView.prototype._position = function (layoutInfo, timelineModel) {
  71263. // Position is be called finally, because bounding rect is needed for
  71264. // adapt content to fill viewRect (auto adapt offset).
  71265. // Timeline may be not all in the viewRect when 'offset' is specified
  71266. // as a number, because it is more appropriate that label aligns at
  71267. // 'offset' but not the other edge defined by viewRect.
  71268. var mainGroup = this._mainGroup;
  71269. var labelGroup = this._labelGroup;
  71270. var viewRect = layoutInfo.viewRect;
  71271. if (layoutInfo.orient === 'vertical') {
  71272. // transform to horizontal, inverse rotate by left-top point.
  71273. var m = create$1();
  71274. var rotateOriginX = viewRect.x;
  71275. var rotateOriginY = viewRect.y + viewRect.height;
  71276. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  71277. rotate(m, m, -PI$8 / 2);
  71278. translate(m, m, [rotateOriginX, rotateOriginY]);
  71279. viewRect = viewRect.clone();
  71280. viewRect.applyTransform(m);
  71281. }
  71282. var viewBound = getBound(viewRect);
  71283. var mainBound = getBound(mainGroup.getBoundingRect());
  71284. var labelBound = getBound(labelGroup.getBoundingRect());
  71285. var mainPosition = [mainGroup.x, mainGroup.y];
  71286. var labelsPosition = [labelGroup.x, labelGroup.y];
  71287. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  71288. var labelPosOpt = layoutInfo.labelPosOpt;
  71289. if (labelPosOpt == null || isString(labelPosOpt)) {
  71290. // '+' or '-'
  71291. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  71292. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  71293. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  71294. } else {
  71295. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  71296. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  71297. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  71298. }
  71299. mainGroup.setPosition(mainPosition);
  71300. labelGroup.setPosition(labelsPosition);
  71301. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  71302. setOrigin(mainGroup);
  71303. setOrigin(labelGroup);
  71304. function setOrigin(targetGroup) {
  71305. targetGroup.originX = viewBound[0][0] - targetGroup.x;
  71306. targetGroup.originY = viewBound[1][0] - targetGroup.y;
  71307. }
  71308. function getBound(rect) {
  71309. // [[xmin, xmax], [ymin, ymax]]
  71310. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  71311. }
  71312. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  71313. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  71314. }
  71315. };
  71316. SliderTimelineView.prototype._createAxis = function (layoutInfo, timelineModel) {
  71317. var data = timelineModel.getData();
  71318. var axisType = timelineModel.get('axisType');
  71319. var scale = createScaleByModel$1(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  71320. scale.getTicks = function () {
  71321. return data.mapArray(['value'], function (value) {
  71322. return {
  71323. value: value
  71324. };
  71325. });
  71326. };
  71327. var dataExtent = data.getDataExtent('value');
  71328. scale.setExtent(dataExtent[0], dataExtent[1]);
  71329. scale.niceTicks();
  71330. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  71331. axis.model = timelineModel;
  71332. return axis;
  71333. };
  71334. SliderTimelineView.prototype._createGroup = function (key) {
  71335. var newGroup = this[key] = new Group();
  71336. this.group.add(newGroup);
  71337. return newGroup;
  71338. };
  71339. SliderTimelineView.prototype._renderAxisLine = function (layoutInfo, group, axis, timelineModel) {
  71340. var axisExtent = axis.getExtent();
  71341. if (!timelineModel.get(['lineStyle', 'show'])) {
  71342. return;
  71343. }
  71344. var line = new Line({
  71345. shape: {
  71346. x1: axisExtent[0],
  71347. y1: 0,
  71348. x2: axisExtent[1],
  71349. y2: 0
  71350. },
  71351. style: extend({
  71352. lineCap: 'round'
  71353. }, timelineModel.getModel('lineStyle').getLineStyle()),
  71354. silent: true,
  71355. z2: 1
  71356. });
  71357. group.add(line);
  71358. var progressLine = this._progressLine = new Line({
  71359. shape: {
  71360. x1: axisExtent[0],
  71361. x2: this._currentPointer ? this._currentPointer.x : axisExtent[0],
  71362. y1: 0,
  71363. y2: 0
  71364. },
  71365. style: defaults({
  71366. lineCap: 'round',
  71367. lineWidth: line.style.lineWidth
  71368. }, timelineModel.getModel(['progress', 'lineStyle']).getLineStyle()),
  71369. silent: true,
  71370. z2: 1
  71371. });
  71372. group.add(progressLine);
  71373. };
  71374. SliderTimelineView.prototype._renderAxisTick = function (layoutInfo, group, axis, timelineModel) {
  71375. var _this = this;
  71376. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  71377. var ticks = axis.scale.getTicks();
  71378. this._tickSymbols = []; // The value is dataIndex, see the costomized scale.
  71379. each(ticks, function (tick) {
  71380. var tickCoord = axis.dataToCoord(tick.value);
  71381. var itemModel = data.getItemModel(tick.value);
  71382. var itemStyleModel = itemModel.getModel('itemStyle');
  71383. var hoverStyleModel = itemModel.getModel(['emphasis', 'itemStyle']);
  71384. var progressStyleModel = itemModel.getModel(['progress', 'itemStyle']);
  71385. var symbolOpt = {
  71386. x: tickCoord,
  71387. y: 0,
  71388. onclick: bind(_this._changeTimeline, _this, tick.value)
  71389. };
  71390. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  71391. el.ensureState('emphasis').style = hoverStyleModel.getItemStyle();
  71392. el.ensureState('progress').style = progressStyleModel.getItemStyle();
  71393. enableHoverEmphasis(el);
  71394. var ecData = getECData(el);
  71395. if (itemModel.get('tooltip')) {
  71396. ecData.dataIndex = tick.value;
  71397. ecData.dataModel = timelineModel;
  71398. } else {
  71399. ecData.dataIndex = ecData.dataModel = null;
  71400. }
  71401. _this._tickSymbols.push(el);
  71402. });
  71403. };
  71404. SliderTimelineView.prototype._renderAxisLabel = function (layoutInfo, group, axis, timelineModel) {
  71405. var _this = this;
  71406. var labelModel = axis.getLabelModel();
  71407. if (!labelModel.get('show')) {
  71408. return;
  71409. }
  71410. var data = timelineModel.getData();
  71411. var labels = axis.getViewLabels();
  71412. this._tickLabels = [];
  71413. each(labels, function (labelItem) {
  71414. // The tickValue is dataIndex, see the costomized scale.
  71415. var dataIndex = labelItem.tickValue;
  71416. var itemModel = data.getItemModel(dataIndex);
  71417. var normalLabelModel = itemModel.getModel('label');
  71418. var hoverLabelModel = itemModel.getModel(['emphasis', 'label']);
  71419. var progressLabelModel = itemModel.getModel(['progress', 'label']);
  71420. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  71421. var textEl = new ZRText({
  71422. x: tickCoord,
  71423. y: 0,
  71424. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  71425. onclick: bind(_this._changeTimeline, _this, dataIndex),
  71426. silent: false,
  71427. style: createTextStyle(normalLabelModel, {
  71428. text: labelItem.formattedLabel,
  71429. align: layoutInfo.labelAlign,
  71430. verticalAlign: layoutInfo.labelBaseline
  71431. })
  71432. });
  71433. textEl.ensureState('emphasis').style = createTextStyle(hoverLabelModel);
  71434. textEl.ensureState('progress').style = createTextStyle(progressLabelModel);
  71435. group.add(textEl);
  71436. enableHoverEmphasis(textEl);
  71437. labelDataIndexStore(textEl).dataIndex = dataIndex;
  71438. _this._tickLabels.push(textEl);
  71439. });
  71440. };
  71441. SliderTimelineView.prototype._renderControl = function (layoutInfo, group, axis, timelineModel) {
  71442. var controlSize = layoutInfo.controlSize;
  71443. var rotation = layoutInfo.rotation;
  71444. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  71445. var hoverStyle = timelineModel.getModel(['emphasis', 'controlStyle']).getItemStyle();
  71446. var playState = timelineModel.getPlayState();
  71447. var inverse = timelineModel.get('inverse', true);
  71448. makeBtn(layoutInfo.nextBtnPosition, 'next', bind(this._changeTimeline, this, inverse ? '-' : '+'));
  71449. makeBtn(layoutInfo.prevBtnPosition, 'prev', bind(this._changeTimeline, this, inverse ? '+' : '-'));
  71450. makeBtn(layoutInfo.playPosition, playState ? 'stop' : 'play', bind(this._handlePlayClick, this, !playState), true);
  71451. function makeBtn(position, iconName, onclick, willRotate) {
  71452. if (!position) {
  71453. return;
  71454. }
  71455. var iconSize = parsePercent(retrieve2(timelineModel.get(['controlStyle', iconName + 'BtnSize']), controlSize), controlSize);
  71456. var rect = [0, -iconSize / 2, iconSize, iconSize];
  71457. var opt = {
  71458. position: position,
  71459. origin: [controlSize / 2, 0],
  71460. rotation: willRotate ? -rotation : 0,
  71461. rectHover: true,
  71462. style: itemStyle,
  71463. onclick: onclick
  71464. };
  71465. var btn = makeControlIcon(timelineModel, iconName + 'Icon', rect, opt);
  71466. btn.ensureState('emphasis').style = hoverStyle;
  71467. group.add(btn);
  71468. enableHoverEmphasis(btn);
  71469. }
  71470. };
  71471. SliderTimelineView.prototype._renderCurrentPointer = function (layoutInfo, group, axis, timelineModel) {
  71472. var data = timelineModel.getData();
  71473. var currentIndex = timelineModel.getCurrentIndex();
  71474. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  71475. var me = this;
  71476. var callback = {
  71477. onCreate: function (pointer) {
  71478. pointer.draggable = true;
  71479. pointer.drift = bind(me._handlePointerDrag, me);
  71480. pointer.ondragend = bind(me._handlePointerDragend, me);
  71481. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel, true);
  71482. },
  71483. onUpdate: function (pointer) {
  71484. pointerMoveTo(pointer, me._progressLine, currentIndex, axis, timelineModel);
  71485. }
  71486. }; // Reuse when exists, for animation and drag.
  71487. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  71488. };
  71489. SliderTimelineView.prototype._handlePlayClick = function (nextState) {
  71490. this._clearTimer();
  71491. this.api.dispatchAction({
  71492. type: 'timelinePlayChange',
  71493. playState: nextState,
  71494. from: this.uid
  71495. });
  71496. };
  71497. SliderTimelineView.prototype._handlePointerDrag = function (dx, dy, e) {
  71498. this._clearTimer();
  71499. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  71500. };
  71501. SliderTimelineView.prototype._handlePointerDragend = function (e) {
  71502. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  71503. };
  71504. SliderTimelineView.prototype._pointerChangeTimeline = function (mousePos, trigger) {
  71505. var toCoord = this._toAxisCoord(mousePos)[0];
  71506. var axis = this._axis;
  71507. var axisExtent = asc(axis.getExtent().slice());
  71508. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  71509. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  71510. this._currentPointer.x = toCoord;
  71511. this._currentPointer.markRedraw();
  71512. this._progressLine.shape.x2 = toCoord;
  71513. this._progressLine.dirty();
  71514. var targetDataIndex = this._findNearestTick(toCoord);
  71515. var timelineModel = this.model;
  71516. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  71517. this._changeTimeline(targetDataIndex);
  71518. }
  71519. };
  71520. SliderTimelineView.prototype._doPlayStop = function () {
  71521. var _this = this;
  71522. this._clearTimer();
  71523. if (this.model.getPlayState()) {
  71524. this._timer = setTimeout(function () {
  71525. // Do not cache
  71526. var timelineModel = _this.model;
  71527. _this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  71528. }, this.model.get('playInterval'));
  71529. }
  71530. };
  71531. SliderTimelineView.prototype._toAxisCoord = function (vertex) {
  71532. var trans = this._mainGroup.getLocalTransform();
  71533. return applyTransform$1(vertex, trans, true);
  71534. };
  71535. SliderTimelineView.prototype._findNearestTick = function (axisCoord) {
  71536. var data = this.model.getData();
  71537. var dist = Infinity;
  71538. var targetDataIndex;
  71539. var axis = this._axis;
  71540. data.each(['value'], function (value, dataIndex) {
  71541. var coord = axis.dataToCoord(value);
  71542. var d = Math.abs(coord - axisCoord);
  71543. if (d < dist) {
  71544. dist = d;
  71545. targetDataIndex = dataIndex;
  71546. }
  71547. });
  71548. return targetDataIndex;
  71549. };
  71550. SliderTimelineView.prototype._clearTimer = function () {
  71551. if (this._timer) {
  71552. clearTimeout(this._timer);
  71553. this._timer = null;
  71554. }
  71555. };
  71556. SliderTimelineView.prototype._changeTimeline = function (nextIndex) {
  71557. var currentIndex = this.model.getCurrentIndex();
  71558. if (nextIndex === '+') {
  71559. nextIndex = currentIndex + 1;
  71560. } else if (nextIndex === '-') {
  71561. nextIndex = currentIndex - 1;
  71562. }
  71563. this.api.dispatchAction({
  71564. type: 'timelineChange',
  71565. currentIndex: nextIndex,
  71566. from: this.uid
  71567. });
  71568. };
  71569. SliderTimelineView.prototype._updateTicksStatus = function () {
  71570. var currentIndex = this.model.getCurrentIndex();
  71571. var tickSymbols = this._tickSymbols;
  71572. var tickLabels = this._tickLabels;
  71573. if (tickSymbols) {
  71574. for (var i = 0; i < tickSymbols.length; i++) {
  71575. tickSymbols && tickSymbols[i] && tickSymbols[i].toggleState('progress', i < currentIndex);
  71576. }
  71577. }
  71578. if (tickLabels) {
  71579. for (var i = 0; i < tickLabels.length; i++) {
  71580. tickLabels && tickLabels[i] && tickLabels[i].toggleState('progress', labelDataIndexStore(tickLabels[i]).dataIndex <= currentIndex);
  71581. }
  71582. }
  71583. };
  71584. SliderTimelineView.type = 'timeline.slider';
  71585. return SliderTimelineView;
  71586. }(TimelineView);
  71587. function createScaleByModel$1(model, axisType) {
  71588. axisType = axisType || model.get('type');
  71589. if (axisType) {
  71590. switch (axisType) {
  71591. // Buildin scale
  71592. case 'category':
  71593. return new OrdinalScale({
  71594. ordinalMeta: model.getCategories(),
  71595. extent: [Infinity, -Infinity]
  71596. });
  71597. case 'time':
  71598. return new TimeScale({
  71599. locale: model.ecModel.getLocaleModel(),
  71600. useUTC: model.ecModel.get('useUTC')
  71601. });
  71602. default:
  71603. // default to be value
  71604. return new IntervalScale();
  71605. }
  71606. }
  71607. }
  71608. function getViewRect$5(model, api) {
  71609. return getLayoutRect(model.getBoxLayoutParams(), {
  71610. width: api.getWidth(),
  71611. height: api.getHeight()
  71612. }, model.get('padding'));
  71613. }
  71614. function makeControlIcon(timelineModel, objPath, rect, opts) {
  71615. var style = opts.style;
  71616. 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.
  71617. if (style) {
  71618. icon.setStyle(style);
  71619. }
  71620. return icon;
  71621. }
  71622. /**
  71623. * Create symbol or update symbol
  71624. * opt: basic position and event handlers
  71625. */
  71626. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  71627. var color = itemStyleModel.get('color');
  71628. if (!symbol) {
  71629. var symbolType = hostModel.get('symbol');
  71630. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  71631. symbol.setStyle('strokeNoScale', true);
  71632. group.add(symbol);
  71633. callback && callback.onCreate(symbol);
  71634. } else {
  71635. symbol.setColor(color);
  71636. group.add(symbol); // Group may be new, also need to add.
  71637. callback && callback.onUpdate(symbol);
  71638. } // Style
  71639. var itemStyle = itemStyleModel.getItemStyle(['color']);
  71640. symbol.setStyle(itemStyle); // Transform and events.
  71641. opt = merge({
  71642. rectHover: true,
  71643. z2: 100
  71644. }, opt, true);
  71645. var symbolSize = hostModel.get('symbolSize');
  71646. symbolSize = symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  71647. opt.scaleX = symbolSize[0] / 2;
  71648. opt.scaleY = symbolSize[1] / 2;
  71649. var symbolOffset = hostModel.get('symbolOffset');
  71650. if (symbolOffset) {
  71651. opt.x = opt.x || 0;
  71652. opt.y = opt.y || 0;
  71653. opt.x += parsePercent$1(symbolOffset[0], symbolSize[0]);
  71654. opt.y += parsePercent$1(symbolOffset[1], symbolSize[1]);
  71655. }
  71656. var symbolRotate = hostModel.get('symbolRotate');
  71657. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  71658. symbol.attr(opt); // FIXME
  71659. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  71660. // getBoundingRect will return wrong result.
  71661. // (This is supposed to be resolved in zrender, but it is a little difficult to
  71662. // leverage performance and auto updateTransform)
  71663. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  71664. symbol.updateTransform();
  71665. return symbol;
  71666. }
  71667. function pointerMoveTo(pointer, progressLine, dataIndex, axis, timelineModel, noAnimation) {
  71668. if (pointer.dragging) {
  71669. return;
  71670. }
  71671. var pointerModel = timelineModel.getModel('checkpointStyle');
  71672. var toCoord = axis.dataToCoord(timelineModel.getData().get('value', dataIndex));
  71673. if (noAnimation || !pointerModel.get('animation', true)) {
  71674. pointer.attr({
  71675. x: toCoord,
  71676. y: 0
  71677. });
  71678. progressLine && progressLine.attr({
  71679. shape: {
  71680. x2: toCoord
  71681. }
  71682. });
  71683. } else {
  71684. var animationCfg = {
  71685. duration: pointerModel.get('animationDuration', true),
  71686. easing: pointerModel.get('animationEasing', true)
  71687. };
  71688. pointer.stopAnimation(null, true);
  71689. pointer.animateTo({
  71690. x: toCoord,
  71691. y: 0
  71692. }, animationCfg);
  71693. progressLine && progressLine.animateTo({
  71694. shape: {
  71695. x2: toCoord
  71696. }
  71697. }, animationCfg);
  71698. }
  71699. }
  71700. function installTimelineAction(registers) {
  71701. registers.registerAction({
  71702. type: 'timelineChange',
  71703. event: 'timelineChanged',
  71704. update: 'prepareAndUpdate'
  71705. }, function (payload, ecModel) {
  71706. var timelineModel = ecModel.getComponent('timeline');
  71707. if (timelineModel && payload.currentIndex != null) {
  71708. timelineModel.setCurrentIndex(payload.currentIndex);
  71709. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  71710. timelineModel.setPlayState(false);
  71711. }
  71712. } // Set normalized currentIndex to payload.
  71713. ecModel.resetOption('timeline', {
  71714. replaceMerge: timelineModel.get('replaceMerge', true)
  71715. });
  71716. return defaults({
  71717. currentIndex: timelineModel.option.currentIndex
  71718. }, payload);
  71719. });
  71720. registers.registerAction({
  71721. type: 'timelinePlayChange',
  71722. event: 'timelinePlayChanged',
  71723. update: 'update'
  71724. }, function (payload, ecModel) {
  71725. var timelineModel = ecModel.getComponent('timeline');
  71726. if (timelineModel && payload.playState != null) {
  71727. timelineModel.setPlayState(payload.playState);
  71728. }
  71729. });
  71730. }
  71731. function timelinePreprocessor(option) {
  71732. var timelineOpt = option && option.timeline;
  71733. if (!isArray(timelineOpt)) {
  71734. timelineOpt = timelineOpt ? [timelineOpt] : [];
  71735. }
  71736. each(timelineOpt, function (opt) {
  71737. if (!opt) {
  71738. return;
  71739. }
  71740. compatibleEC2(opt);
  71741. });
  71742. }
  71743. function compatibleEC2(opt) {
  71744. var type = opt.type;
  71745. var ec2Types = {
  71746. 'number': 'value',
  71747. 'time': 'time'
  71748. }; // Compatible with ec2
  71749. if (ec2Types[type]) {
  71750. opt.axisType = ec2Types[type];
  71751. delete opt.type;
  71752. }
  71753. transferItem(opt);
  71754. if (has(opt, 'controlPosition')) {
  71755. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  71756. if (!has(controlStyle, 'position')) {
  71757. controlStyle.position = opt.controlPosition;
  71758. }
  71759. if (controlStyle.position === 'none' && !has(controlStyle, 'show')) {
  71760. controlStyle.show = false;
  71761. delete controlStyle.position;
  71762. }
  71763. delete opt.controlPosition;
  71764. }
  71765. each(opt.data || [], function (dataItem) {
  71766. if (isObject(dataItem) && !isArray(dataItem)) {
  71767. if (!has(dataItem, 'value') && has(dataItem, 'name')) {
  71768. // In ec2, using name as value.
  71769. dataItem.value = dataItem.name;
  71770. }
  71771. transferItem(dataItem);
  71772. }
  71773. });
  71774. }
  71775. function transferItem(opt) {
  71776. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  71777. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  71778. var label = opt.label || opt.label || {};
  71779. var labelNormal = label.normal || (label.normal = {});
  71780. var excludeLabelAttr = {
  71781. normal: 1,
  71782. emphasis: 1
  71783. };
  71784. each(label, function (value, name) {
  71785. if (!excludeLabelAttr[name] && !has(labelNormal, name)) {
  71786. labelNormal[name] = value;
  71787. }
  71788. });
  71789. if (itemStyleEmphasis.label && !has(label, 'emphasis')) {
  71790. label.emphasis = itemStyleEmphasis.label;
  71791. delete itemStyleEmphasis.label;
  71792. }
  71793. }
  71794. function has(obj, attr) {
  71795. return obj.hasOwnProperty(attr);
  71796. }
  71797. function install$D(registers) {
  71798. registers.registerComponentModel(SliderTimelineModel);
  71799. registers.registerComponentView(SliderTimelineView);
  71800. registers.registerSubTypeDefaulter('timeline', function () {
  71801. // Only slider now.
  71802. return 'slider';
  71803. });
  71804. installTimelineAction(registers);
  71805. registers.registerPreprocessor(timelinePreprocessor);
  71806. }
  71807. function fillLabel(opt) {
  71808. defaultEmphasis(opt, 'label', ['show']);
  71809. } // { [componentType]: MarkerModel }
  71810. var inner$i = makeInner();
  71811. var MarkerModel =
  71812. /** @class */
  71813. function (_super) {
  71814. __extends(MarkerModel, _super);
  71815. function MarkerModel() {
  71816. var _this = _super !== null && _super.apply(this, arguments) || this;
  71817. _this.type = MarkerModel.type;
  71818. /**
  71819. * If marker model is created by self from series
  71820. */
  71821. _this.createdBySelf = false;
  71822. return _this;
  71823. }
  71824. /**
  71825. * @overrite
  71826. */
  71827. MarkerModel.prototype.init = function (option, parentModel, ecModel) {
  71828. if ("development" !== 'production') {
  71829. if (this.type === 'marker') {
  71830. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  71831. }
  71832. }
  71833. this.mergeDefaultAndTheme(option, ecModel);
  71834. this._mergeOption(option, ecModel, false, true);
  71835. };
  71836. MarkerModel.prototype.isAnimationEnabled = function () {
  71837. if (env.node) {
  71838. return false;
  71839. }
  71840. var hostSeries = this.__hostSeries;
  71841. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  71842. };
  71843. /**
  71844. * @overrite
  71845. */
  71846. MarkerModel.prototype.mergeOption = function (newOpt, ecModel) {
  71847. this._mergeOption(newOpt, ecModel, false, false);
  71848. };
  71849. MarkerModel.prototype._mergeOption = function (newOpt, ecModel, createdBySelf, isInit) {
  71850. var componentType = this.mainType;
  71851. if (!createdBySelf) {
  71852. ecModel.eachSeries(function (seriesModel) {
  71853. // mainType can be markPoint, markLine, markArea
  71854. var markerOpt = seriesModel.get(this.mainType, true);
  71855. var markerModel = inner$i(seriesModel)[componentType];
  71856. if (!markerOpt || !markerOpt.data) {
  71857. inner$i(seriesModel)[componentType] = null;
  71858. return;
  71859. }
  71860. if (!markerModel) {
  71861. if (isInit) {
  71862. // Default label emphasis `position` and `show`
  71863. fillLabel(markerOpt);
  71864. }
  71865. each(markerOpt.data, function (item) {
  71866. // FIXME Overwrite fillLabel method ?
  71867. if (item instanceof Array) {
  71868. fillLabel(item[0]);
  71869. fillLabel(item[1]);
  71870. } else {
  71871. fillLabel(item);
  71872. }
  71873. });
  71874. markerModel = this.createMarkerModelFromSeries(markerOpt, this, ecModel); // markerModel = new ImplementedMarkerModel(
  71875. // markerOpt, this, ecModel
  71876. // );
  71877. extend(markerModel, {
  71878. mainType: this.mainType,
  71879. // Use the same series index and name
  71880. seriesIndex: seriesModel.seriesIndex,
  71881. name: seriesModel.name,
  71882. createdBySelf: true
  71883. });
  71884. markerModel.__hostSeries = seriesModel;
  71885. } else {
  71886. markerModel._mergeOption(markerOpt, ecModel, true);
  71887. }
  71888. inner$i(seriesModel)[componentType] = markerModel;
  71889. }, this);
  71890. }
  71891. };
  71892. MarkerModel.prototype.formatTooltip = function (dataIndex, multipleSeries, dataType) {
  71893. var data = this.getData();
  71894. var value = this.getRawValue(dataIndex);
  71895. var itemName = data.getName(dataIndex);
  71896. return createTooltipMarkup('section', {
  71897. header: this.name,
  71898. blocks: [createTooltipMarkup('nameValue', {
  71899. name: itemName,
  71900. value: value,
  71901. noName: !itemName,
  71902. noValue: value == null
  71903. })]
  71904. });
  71905. };
  71906. MarkerModel.prototype.getData = function () {
  71907. return this._data;
  71908. };
  71909. MarkerModel.prototype.setData = function (data) {
  71910. this._data = data;
  71911. };
  71912. MarkerModel.getMarkerModelFromSeries = function (seriesModel, // Support three types of markers. Strict check.
  71913. componentType) {
  71914. return inner$i(seriesModel)[componentType];
  71915. };
  71916. MarkerModel.type = 'marker';
  71917. MarkerModel.dependencies = ['series', 'grid', 'polar', 'geo'];
  71918. return MarkerModel;
  71919. }(ComponentModel);
  71920. mixin(MarkerModel, DataFormatMixin.prototype);
  71921. var MarkPointModel =
  71922. /** @class */
  71923. function (_super) {
  71924. __extends(MarkPointModel, _super);
  71925. function MarkPointModel() {
  71926. var _this = _super !== null && _super.apply(this, arguments) || this;
  71927. _this.type = MarkPointModel.type;
  71928. return _this;
  71929. }
  71930. MarkPointModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  71931. return new MarkPointModel(markerOpt, masterMarkerModel, ecModel);
  71932. };
  71933. MarkPointModel.type = 'markPoint';
  71934. MarkPointModel.defaultOption = {
  71935. zlevel: 0,
  71936. z: 5,
  71937. symbol: 'pin',
  71938. symbolSize: 50,
  71939. //symbolRotate: 0,
  71940. //symbolOffset: [0, 0]
  71941. tooltip: {
  71942. trigger: 'item'
  71943. },
  71944. label: {
  71945. show: true,
  71946. position: 'inside'
  71947. },
  71948. itemStyle: {
  71949. borderWidth: 2
  71950. },
  71951. emphasis: {
  71952. label: {
  71953. show: true
  71954. }
  71955. }
  71956. };
  71957. return MarkPointModel;
  71958. }(MarkerModel);
  71959. function hasXOrY(item) {
  71960. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  71961. }
  71962. function hasXAndY(item) {
  71963. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  71964. } // Make it simple, do not visit all stacked value to count precision.
  71965. // function getPrecision(data, valueAxisDim, dataIndex) {
  71966. // let precision = -1;
  71967. // let stackedDim = data.mapDimension(valueAxisDim);
  71968. // do {
  71969. // precision = Math.max(
  71970. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  71971. // precision
  71972. // );
  71973. // let stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  71974. // if (stackedOnSeries) {
  71975. // let byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  71976. // data = stackedOnSeries.getData();
  71977. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  71978. // stackedDim = data.getCalculationInfo('stackedDimension');
  71979. // }
  71980. // else {
  71981. // data = null;
  71982. // }
  71983. // } while (data);
  71984. // return precision;
  71985. // }
  71986. function markerTypeCalculatorWithExtent(markerType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  71987. var coordArr = [];
  71988. var stacked = isDimensionStacked(data, targetDataDim
  71989. /*, otherDataDim*/
  71990. );
  71991. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  71992. var value = numCalculate(data, calcDataDim, markerType);
  71993. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  71994. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  71995. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  71996. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  71997. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  71998. precision = Math.min(precision, 20);
  71999. if (precision >= 0) {
  72000. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  72001. }
  72002. return [coordArr, coordArrValue];
  72003. } // TODO Specified percent
  72004. var markerTypeCalculator = {
  72005. min: curry(markerTypeCalculatorWithExtent, 'min'),
  72006. max: curry(markerTypeCalculatorWithExtent, 'max'),
  72007. average: curry(markerTypeCalculatorWithExtent, 'average'),
  72008. median: curry(markerTypeCalculatorWithExtent, 'median')
  72009. };
  72010. /**
  72011. * Transform markPoint data item to format used in List by do the following
  72012. * 1. Calculate statistic like `max`, `min`, `average`
  72013. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  72014. * @param {module:echarts/model/Series} seriesModel
  72015. * @param {module:echarts/coord/*} [coordSys]
  72016. * @param {Object} item
  72017. * @return {Object}
  72018. */
  72019. function dataTransform(seriesModel, item) {
  72020. var data = seriesModel.getData();
  72021. var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly
  72022. // 2. If `coord` is not a data array. Which uses `xAxis`,
  72023. // `yAxis` to specify the coord on each dimension
  72024. // parseFloat first because item.x and item.y can be percent string like '20%'
  72025. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  72026. var dims = coordSys.dimensions;
  72027. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  72028. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  72029. item = clone(item);
  72030. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  72031. var otherCoordIndex = indexOf(dims, axisInfo.baseAxis.dim);
  72032. var targetCoordIndex = indexOf(dims, axisInfo.valueAxis.dim);
  72033. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  72034. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  72035. // let item use the value without stack.
  72036. item.value = coordInfo[1];
  72037. } else {
  72038. // FIXME Only has one of xAxis and yAxis.
  72039. var coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis]; // Each coord support max, min, average
  72040. for (var i = 0; i < 2; i++) {
  72041. if (markerTypeCalculator[coord[i]]) {
  72042. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  72043. }
  72044. }
  72045. item.coord = coord;
  72046. }
  72047. }
  72048. return item;
  72049. }
  72050. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  72051. var ret = {};
  72052. if (item.valueIndex != null || item.valueDim != null) {
  72053. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  72054. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  72055. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  72056. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  72057. } else {
  72058. ret.baseAxis = seriesModel.getBaseAxis();
  72059. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  72060. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  72061. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  72062. }
  72063. return ret;
  72064. }
  72065. function dataDimToCoordDim(seriesModel, dataDim) {
  72066. var data = seriesModel.getData();
  72067. var dimensions = data.dimensions;
  72068. dataDim = data.getDimension(dataDim);
  72069. for (var i = 0; i < dimensions.length; i++) {
  72070. var dimItem = data.getDimensionInfo(dimensions[i]);
  72071. if (dimItem.name === dataDim) {
  72072. return dimItem.coordDim;
  72073. }
  72074. }
  72075. }
  72076. /**
  72077. * Filter data which is out of coordinateSystem range
  72078. * [dataFilter description]
  72079. */
  72080. function dataFilter$1( // Currently only polar and cartesian has containData.
  72081. coordSys, item) {
  72082. // Alwalys return true if there is no coordSys
  72083. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  72084. }
  72085. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  72086. // x, y, radius, angle
  72087. if (dimIndex < 2) {
  72088. return item.coord && item.coord[dimIndex];
  72089. }
  72090. return item.value;
  72091. }
  72092. function numCalculate(data, valueDataDim, type) {
  72093. if (type === 'average') {
  72094. var sum_1 = 0;
  72095. var count_1 = 0;
  72096. data.each(valueDataDim, function (val, idx) {
  72097. if (!isNaN(val)) {
  72098. sum_1 += val;
  72099. count_1++;
  72100. }
  72101. });
  72102. return sum_1 / count_1;
  72103. } else if (type === 'median') {
  72104. return data.getMedian(valueDataDim);
  72105. } else {
  72106. // max & min
  72107. return data.getDataExtent(valueDataDim)[type === 'max' ? 1 : 0];
  72108. }
  72109. }
  72110. var inner$j = makeInner();
  72111. var MarkerView =
  72112. /** @class */
  72113. function (_super) {
  72114. __extends(MarkerView, _super);
  72115. function MarkerView() {
  72116. var _this = _super !== null && _super.apply(this, arguments) || this;
  72117. _this.type = MarkerView.type;
  72118. return _this;
  72119. }
  72120. MarkerView.prototype.init = function () {
  72121. this.markerGroupMap = createHashMap();
  72122. };
  72123. MarkerView.prototype.render = function (markerModel, ecModel, api) {
  72124. var _this = this;
  72125. var markerGroupMap = this.markerGroupMap;
  72126. markerGroupMap.each(function (item) {
  72127. inner$j(item).keep = false;
  72128. });
  72129. ecModel.eachSeries(function (seriesModel) {
  72130. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  72131. markerModel && _this.renderSeries(seriesModel, markerModel, ecModel, api);
  72132. });
  72133. markerGroupMap.each(function (item) {
  72134. !inner$j(item).keep && _this.group.remove(item.group);
  72135. });
  72136. };
  72137. MarkerView.prototype.markKeep = function (drawGroup) {
  72138. inner$j(drawGroup).keep = true;
  72139. };
  72140. MarkerView.prototype.blurSeries = function (seriesModelList) {
  72141. var _this = this;
  72142. each(seriesModelList, function (seriesModel) {
  72143. var markerModel = MarkerModel.getMarkerModelFromSeries(seriesModel, _this.type);
  72144. if (markerModel) {
  72145. var data = markerModel.getData();
  72146. data.eachItemGraphicEl(function (el) {
  72147. if (el) {
  72148. enterBlur(el);
  72149. }
  72150. });
  72151. }
  72152. });
  72153. };
  72154. MarkerView.type = 'marker';
  72155. return MarkerView;
  72156. }(ComponentView);
  72157. function updateMarkerLayout(mpData, seriesModel, api) {
  72158. var coordSys = seriesModel.coordinateSystem;
  72159. mpData.each(function (idx) {
  72160. var itemModel = mpData.getItemModel(idx);
  72161. var point;
  72162. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  72163. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  72164. if (!isNaN(xPx) && !isNaN(yPx)) {
  72165. point = [xPx, yPx];
  72166. } // Chart like bar may have there own marker positioning logic
  72167. else if (seriesModel.getMarkerPosition) {
  72168. // Use the getMarkerPoisition
  72169. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  72170. } else if (coordSys) {
  72171. var x = mpData.get(coordSys.dimensions[0], idx);
  72172. var y = mpData.get(coordSys.dimensions[1], idx);
  72173. point = coordSys.dataToPoint([x, y]);
  72174. } // Use x, y if has any
  72175. if (!isNaN(xPx)) {
  72176. point[0] = xPx;
  72177. }
  72178. if (!isNaN(yPx)) {
  72179. point[1] = yPx;
  72180. }
  72181. mpData.setItemLayout(idx, point);
  72182. });
  72183. }
  72184. var MarkPointView =
  72185. /** @class */
  72186. function (_super) {
  72187. __extends(MarkPointView, _super);
  72188. function MarkPointView() {
  72189. var _this = _super !== null && _super.apply(this, arguments) || this;
  72190. _this.type = MarkPointView.type;
  72191. return _this;
  72192. }
  72193. MarkPointView.prototype.updateTransform = function (markPointModel, ecModel, api) {
  72194. ecModel.eachSeries(function (seriesModel) {
  72195. var mpModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markPoint');
  72196. if (mpModel) {
  72197. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  72198. this.markerGroupMap.get(seriesModel.id).updateLayout();
  72199. }
  72200. }, this);
  72201. };
  72202. MarkPointView.prototype.renderSeries = function (seriesModel, mpModel, ecModel, api) {
  72203. var coordSys = seriesModel.coordinateSystem;
  72204. var seriesId = seriesModel.id;
  72205. var seriesData = seriesModel.getData();
  72206. var symbolDrawMap = this.markerGroupMap;
  72207. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  72208. var mpData = createList$1(coordSys, seriesModel, mpModel); // FIXME
  72209. mpModel.setData(mpData);
  72210. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  72211. mpData.each(function (idx) {
  72212. var itemModel = mpData.getItemModel(idx);
  72213. var symbol = itemModel.getShallow('symbol');
  72214. var symbolSize = itemModel.getShallow('symbolSize');
  72215. var symbolRotate = itemModel.getShallow('symbolRotate');
  72216. if (isFunction(symbol) || isFunction(symbolSize) || isFunction(symbolRotate)) {
  72217. var rawIdx = mpModel.getRawValue(idx);
  72218. var dataParams = mpModel.getDataParams(idx);
  72219. if (isFunction(symbol)) {
  72220. symbol = symbol(rawIdx, dataParams);
  72221. }
  72222. if (isFunction(symbolSize)) {
  72223. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  72224. symbolSize = symbolSize(rawIdx, dataParams);
  72225. }
  72226. if (isFunction(symbolRotate)) {
  72227. symbolRotate = symbolRotate(rawIdx, dataParams);
  72228. }
  72229. }
  72230. var style = itemModel.getModel('itemStyle').getItemStyle();
  72231. var color = getVisualFromData(seriesData, 'color');
  72232. if (!style.fill) {
  72233. style.fill = color;
  72234. }
  72235. mpData.setItemVisual(idx, {
  72236. symbol: symbol,
  72237. symbolSize: symbolSize,
  72238. symbolRotate: symbolRotate,
  72239. style: style
  72240. });
  72241. }); // TODO Text are wrong
  72242. symbolDraw.updateData(mpData);
  72243. this.group.add(symbolDraw.group); // Set host model for tooltip
  72244. // FIXME
  72245. mpData.eachItemGraphicEl(function (el) {
  72246. el.traverse(function (child) {
  72247. getECData(child).dataModel = mpModel;
  72248. });
  72249. });
  72250. this.markKeep(symbolDraw);
  72251. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  72252. };
  72253. MarkPointView.type = 'markPoint';
  72254. return MarkPointView;
  72255. }(MarkerView);
  72256. function createList$1(coordSys, seriesModel, mpModel) {
  72257. var coordDimsInfos;
  72258. if (coordSys) {
  72259. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72260. 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
  72261. return defaults({
  72262. name: coordDim
  72263. }, info);
  72264. });
  72265. } else {
  72266. coordDimsInfos = [{
  72267. name: 'value',
  72268. type: 'float'
  72269. }];
  72270. }
  72271. var mpData = new List(coordDimsInfos, mpModel);
  72272. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  72273. if (coordSys) {
  72274. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  72275. }
  72276. mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function (item) {
  72277. return item.value;
  72278. });
  72279. return mpData;
  72280. }
  72281. function install$E(registers) {
  72282. registers.registerComponentModel(MarkPointModel);
  72283. registers.registerComponentView(MarkPointView);
  72284. registers.registerPreprocessor(function (opt) {
  72285. // Make sure markPoint component is enabled
  72286. opt.markPoint = opt.markPoint || {};
  72287. });
  72288. }
  72289. var MarkLineModel =
  72290. /** @class */
  72291. function (_super) {
  72292. __extends(MarkLineModel, _super);
  72293. function MarkLineModel() {
  72294. var _this = _super !== null && _super.apply(this, arguments) || this;
  72295. _this.type = MarkLineModel.type;
  72296. return _this;
  72297. }
  72298. MarkLineModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  72299. return new MarkLineModel(markerOpt, masterMarkerModel, ecModel);
  72300. };
  72301. MarkLineModel.type = 'markLine';
  72302. MarkLineModel.defaultOption = {
  72303. zlevel: 0,
  72304. z: 5,
  72305. symbol: ['circle', 'arrow'],
  72306. symbolSize: [8, 16],
  72307. //symbolRotate: 0,
  72308. precision: 2,
  72309. tooltip: {
  72310. trigger: 'item'
  72311. },
  72312. label: {
  72313. show: true,
  72314. position: 'end',
  72315. distance: 5
  72316. },
  72317. lineStyle: {
  72318. type: 'dashed'
  72319. },
  72320. emphasis: {
  72321. label: {
  72322. show: true
  72323. },
  72324. lineStyle: {
  72325. width: 3
  72326. }
  72327. },
  72328. animationEasing: 'linear'
  72329. };
  72330. return MarkLineModel;
  72331. }(MarkerModel);
  72332. var inner$k = makeInner();
  72333. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  72334. var data = seriesModel.getData();
  72335. var itemArray;
  72336. if (!isArray(item)) {
  72337. // Special type markLine like 'min', 'max', 'average', 'median'
  72338. var mlType = item.type;
  72339. if (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  72340. // data: [{
  72341. // yAxis: 10
  72342. // }]
  72343. || item.xAxis != null || item.yAxis != null) {
  72344. var valueAxis = void 0;
  72345. var value = void 0;
  72346. if (item.yAxis != null || item.xAxis != null) {
  72347. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  72348. value = retrieve(item.yAxis, item.xAxis);
  72349. } else {
  72350. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  72351. valueAxis = axisInfo.valueAxis;
  72352. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  72353. value = numCalculate(data, valueDataDim, mlType);
  72354. }
  72355. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  72356. var baseIndex = 1 - valueIndex; // Normized to 2d data with start and end point
  72357. var mlFrom = clone(item);
  72358. var mlTo = {
  72359. coord: []
  72360. };
  72361. mlFrom.type = null;
  72362. mlFrom.coord = [];
  72363. mlFrom.coord[baseIndex] = -Infinity;
  72364. mlTo.coord[baseIndex] = Infinity;
  72365. var precision = mlModel.get('precision');
  72366. if (precision >= 0 && typeof value === 'number') {
  72367. value = +value.toFixed(Math.min(precision, 20));
  72368. }
  72369. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  72370. itemArray = [mlFrom, mlTo, {
  72371. type: mlType,
  72372. valueIndex: item.valueIndex,
  72373. // Force to use the value of calculated value.
  72374. value: value
  72375. }];
  72376. } else {
  72377. // Invalid data
  72378. if ("development" !== 'production') {
  72379. logError('Invalid markLine data.');
  72380. }
  72381. itemArray = [];
  72382. }
  72383. } else {
  72384. itemArray = item;
  72385. }
  72386. var normalizedItem = [dataTransform(seriesModel, itemArray[0]), dataTransform(seriesModel, itemArray[1]), extend({}, itemArray[2])]; // Avoid line data type is extended by from(to) data type
  72387. normalizedItem[2].type = normalizedItem[2].type || null; // Merge from option and to option into line option
  72388. merge(normalizedItem[2], normalizedItem[0]);
  72389. merge(normalizedItem[2], normalizedItem[1]);
  72390. return normalizedItem;
  72391. };
  72392. function isInifinity(val) {
  72393. return !isNaN(val) && !isFinite(val);
  72394. } // If a markLine has one dim
  72395. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  72396. var otherDimIndex = 1 - dimIndex;
  72397. var dimName = coordSys.dimensions[dimIndex];
  72398. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  72399. }
  72400. function markLineFilter(coordSys, item) {
  72401. if (coordSys.type === 'cartesian2d') {
  72402. var fromCoord = item[0].coord;
  72403. var toCoord = item[1].coord; // In case
  72404. // {
  72405. // markLine: {
  72406. // data: [{ yAxis: 2 }]
  72407. // }
  72408. // }
  72409. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  72410. return true;
  72411. }
  72412. }
  72413. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  72414. }
  72415. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  72416. var coordSys = seriesModel.coordinateSystem;
  72417. var itemModel = data.getItemModel(idx);
  72418. var point;
  72419. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  72420. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  72421. if (!isNaN(xPx) && !isNaN(yPx)) {
  72422. point = [xPx, yPx];
  72423. } else {
  72424. // Chart like bar may have there own marker positioning logic
  72425. if (seriesModel.getMarkerPosition) {
  72426. // Use the getMarkerPoisition
  72427. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  72428. } else {
  72429. var dims = coordSys.dimensions;
  72430. var x = data.get(dims[0], idx);
  72431. var y = data.get(dims[1], idx);
  72432. point = coordSys.dataToPoint([x, y]);
  72433. } // Expand line to the edge of grid if value on one axis is Inifnity
  72434. // In case
  72435. // markLine: {
  72436. // data: [{
  72437. // yAxis: 2
  72438. // // or
  72439. // type: 'average'
  72440. // }]
  72441. // }
  72442. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  72443. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  72444. var xAxis = coordSys.getAxis('x');
  72445. var yAxis = coordSys.getAxis('y');
  72446. var dims = coordSys.dimensions;
  72447. if (isInifinity(data.get(dims[0], idx))) {
  72448. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  72449. } else if (isInifinity(data.get(dims[1], idx))) {
  72450. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  72451. }
  72452. } // Use x, y if has any
  72453. if (!isNaN(xPx)) {
  72454. point[0] = xPx;
  72455. }
  72456. if (!isNaN(yPx)) {
  72457. point[1] = yPx;
  72458. }
  72459. }
  72460. data.setItemLayout(idx, point);
  72461. }
  72462. var MarkLineView =
  72463. /** @class */
  72464. function (_super) {
  72465. __extends(MarkLineView, _super);
  72466. function MarkLineView() {
  72467. var _this = _super !== null && _super.apply(this, arguments) || this;
  72468. _this.type = MarkLineView.type;
  72469. return _this;
  72470. }
  72471. MarkLineView.prototype.updateTransform = function (markLineModel, ecModel, api) {
  72472. ecModel.eachSeries(function (seriesModel) {
  72473. var mlModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markLine');
  72474. if (mlModel) {
  72475. var mlData_1 = mlModel.getData();
  72476. var fromData_1 = inner$k(mlModel).from;
  72477. var toData_1 = inner$k(mlModel).to; // Update visual and layout of from symbol and to symbol
  72478. fromData_1.each(function (idx) {
  72479. updateSingleMarkerEndLayout(fromData_1, idx, true, seriesModel, api);
  72480. updateSingleMarkerEndLayout(toData_1, idx, false, seriesModel, api);
  72481. }); // Update layout of line
  72482. mlData_1.each(function (idx) {
  72483. mlData_1.setItemLayout(idx, [fromData_1.getItemLayout(idx), toData_1.getItemLayout(idx)]);
  72484. });
  72485. this.markerGroupMap.get(seriesModel.id).updateLayout();
  72486. }
  72487. }, this);
  72488. };
  72489. MarkLineView.prototype.renderSeries = function (seriesModel, mlModel, ecModel, api) {
  72490. var coordSys = seriesModel.coordinateSystem;
  72491. var seriesId = seriesModel.id;
  72492. var seriesData = seriesModel.getData();
  72493. var lineDrawMap = this.markerGroupMap;
  72494. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  72495. this.group.add(lineDraw.group);
  72496. var mlData = createList$2(coordSys, seriesModel, mlModel);
  72497. var fromData = mlData.from;
  72498. var toData = mlData.to;
  72499. var lineData = mlData.line;
  72500. inner$k(mlModel).from = fromData;
  72501. inner$k(mlModel).to = toData; // Line data for tooltip and formatter
  72502. mlModel.setData(lineData);
  72503. var symbolType = mlModel.get('symbol');
  72504. var symbolSize = mlModel.get('symbolSize');
  72505. if (!isArray(symbolType)) {
  72506. symbolType = [symbolType, symbolType];
  72507. }
  72508. if (!isArray(symbolSize)) {
  72509. symbolSize = [symbolSize, symbolSize];
  72510. } // Update visual and layout of from symbol and to symbol
  72511. mlData.from.each(function (idx) {
  72512. updateDataVisualAndLayout(fromData, idx, true);
  72513. updateDataVisualAndLayout(toData, idx, false);
  72514. }); // Update visual and layout of line
  72515. lineData.each(function (idx) {
  72516. var lineStyle = lineData.getItemModel(idx).getModel('lineStyle').getLineStyle(); // lineData.setItemVisual(idx, {
  72517. // color: lineColor || fromData.getItemVisual(idx, 'color')
  72518. // });
  72519. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  72520. if (lineStyle.stroke == null) {
  72521. lineStyle.stroke = fromData.getItemVisual(idx, 'style').fill;
  72522. }
  72523. lineData.setItemVisual(idx, {
  72524. fromSymbolRotate: fromData.getItemVisual(idx, 'symbolRotate'),
  72525. fromSymbolSize: fromData.getItemVisual(idx, 'symbolSize'),
  72526. fromSymbol: fromData.getItemVisual(idx, 'symbol'),
  72527. toSymbolRotate: toData.getItemVisual(idx, 'symbolRotate'),
  72528. toSymbolSize: toData.getItemVisual(idx, 'symbolSize'),
  72529. toSymbol: toData.getItemVisual(idx, 'symbol'),
  72530. style: lineStyle
  72531. });
  72532. });
  72533. lineDraw.updateData(lineData); // Set host model for tooltip
  72534. // FIXME
  72535. mlData.line.eachItemGraphicEl(function (el, idx) {
  72536. el.traverse(function (child) {
  72537. getECData(child).dataModel = mlModel;
  72538. });
  72539. });
  72540. function updateDataVisualAndLayout(data, idx, isFrom) {
  72541. var itemModel = data.getItemModel(idx);
  72542. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  72543. var style = itemModel.getModel('itemStyle').getItemStyle();
  72544. if (style.fill == null) {
  72545. style.fill = getVisualFromData(seriesData, 'color');
  72546. }
  72547. data.setItemVisual(idx, {
  72548. symbolRotate: itemModel.get('symbolRotate'),
  72549. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  72550. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  72551. style: style
  72552. });
  72553. }
  72554. this.markKeep(lineDraw);
  72555. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  72556. };
  72557. MarkLineView.type = 'markLine';
  72558. return MarkLineView;
  72559. }(MarkerView);
  72560. function createList$2(coordSys, seriesModel, mlModel) {
  72561. var coordDimsInfos;
  72562. if (coordSys) {
  72563. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72564. 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
  72565. return defaults({
  72566. name: coordDim
  72567. }, info);
  72568. });
  72569. } else {
  72570. coordDimsInfos = [{
  72571. name: 'value',
  72572. type: 'float'
  72573. }];
  72574. }
  72575. var fromData = new List(coordDimsInfos, mlModel);
  72576. var toData = new List(coordDimsInfos, mlModel); // No dimensions
  72577. var lineData = new List([], mlModel);
  72578. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  72579. if (coordSys) {
  72580. optData = filter(optData, curry(markLineFilter, coordSys));
  72581. }
  72582. var dimValueGetter$1 = coordSys ? dimValueGetter : function (item) {
  72583. return item.value;
  72584. };
  72585. fromData.initData(map(optData, function (item) {
  72586. return item[0];
  72587. }), null, dimValueGetter$1);
  72588. toData.initData(map(optData, function (item) {
  72589. return item[1];
  72590. }), null, dimValueGetter$1);
  72591. lineData.initData(map(optData, function (item) {
  72592. return item[2];
  72593. }));
  72594. lineData.hasItemOption = true;
  72595. return {
  72596. from: fromData,
  72597. to: toData,
  72598. line: lineData
  72599. };
  72600. }
  72601. function install$F(registers) {
  72602. registers.registerComponentModel(MarkLineModel);
  72603. registers.registerComponentView(MarkLineView);
  72604. registers.registerPreprocessor(function (opt) {
  72605. // Make sure markLine component is enabled
  72606. opt.markLine = opt.markLine || {};
  72607. });
  72608. }
  72609. var MarkAreaModel =
  72610. /** @class */
  72611. function (_super) {
  72612. __extends(MarkAreaModel, _super);
  72613. function MarkAreaModel() {
  72614. var _this = _super !== null && _super.apply(this, arguments) || this;
  72615. _this.type = MarkAreaModel.type;
  72616. return _this;
  72617. }
  72618. MarkAreaModel.prototype.createMarkerModelFromSeries = function (markerOpt, masterMarkerModel, ecModel) {
  72619. return new MarkAreaModel(markerOpt, masterMarkerModel, ecModel);
  72620. };
  72621. MarkAreaModel.type = 'markArea';
  72622. MarkAreaModel.defaultOption = {
  72623. zlevel: 0,
  72624. // PENDING
  72625. z: 1,
  72626. tooltip: {
  72627. trigger: 'item'
  72628. },
  72629. // markArea should fixed on the coordinate system
  72630. animation: false,
  72631. label: {
  72632. show: true,
  72633. position: 'top'
  72634. },
  72635. itemStyle: {
  72636. // color and borderColor default to use color from series
  72637. // color: 'auto'
  72638. // borderColor: 'auto'
  72639. borderWidth: 0
  72640. },
  72641. emphasis: {
  72642. label: {
  72643. show: true,
  72644. position: 'top'
  72645. }
  72646. }
  72647. };
  72648. return MarkAreaModel;
  72649. }(MarkerModel);
  72650. var inner$l = makeInner();
  72651. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  72652. var lt = dataTransform(seriesModel, item[0]);
  72653. var rb = dataTransform(seriesModel, item[1]); // FIXME make sure lt is less than rb
  72654. var ltCoord = lt.coord;
  72655. var rbCoord = rb.coord;
  72656. ltCoord[0] = retrieve(ltCoord[0], -Infinity);
  72657. ltCoord[1] = retrieve(ltCoord[1], -Infinity);
  72658. rbCoord[0] = retrieve(rbCoord[0], Infinity);
  72659. rbCoord[1] = retrieve(rbCoord[1], Infinity); // Merge option into one
  72660. var result = mergeAll([{}, lt, rb]);
  72661. result.coord = [lt.coord, rb.coord];
  72662. result.x0 = lt.x;
  72663. result.y0 = lt.y;
  72664. result.x1 = rb.x;
  72665. result.y1 = rb.y;
  72666. return result;
  72667. };
  72668. function isInifinity$1(val) {
  72669. return !isNaN(val) && !isFinite(val);
  72670. } // If a markArea has one dim
  72671. function ifMarkAreaHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  72672. var otherDimIndex = 1 - dimIndex;
  72673. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  72674. }
  72675. function markAreaFilter(coordSys, item) {
  72676. var fromCoord = item.coord[0];
  72677. var toCoord = item.coord[1];
  72678. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  72679. // In case
  72680. // {
  72681. // markArea: {
  72682. // data: [{ yAxis: 2 }]
  72683. // }
  72684. // }
  72685. if (fromCoord && toCoord && (ifMarkAreaHasOnlyDim(1, fromCoord, toCoord) || ifMarkAreaHasOnlyDim(0, fromCoord, toCoord))) {
  72686. return true;
  72687. }
  72688. }
  72689. return dataFilter$1(coordSys, {
  72690. coord: fromCoord,
  72691. x: item.x0,
  72692. y: item.y0
  72693. }) || dataFilter$1(coordSys, {
  72694. coord: toCoord,
  72695. x: item.x1,
  72696. y: item.y1
  72697. });
  72698. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  72699. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  72700. var coordSys = seriesModel.coordinateSystem;
  72701. var itemModel = data.getItemModel(idx);
  72702. var point;
  72703. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  72704. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  72705. if (!isNaN(xPx) && !isNaN(yPx)) {
  72706. point = [xPx, yPx];
  72707. } else {
  72708. // Chart like bar may have there own marker positioning logic
  72709. if (seriesModel.getMarkerPosition) {
  72710. // Use the getMarkerPoisition
  72711. point = seriesModel.getMarkerPosition(data.getValues(dims, idx));
  72712. } else {
  72713. var x = data.get(dims[0], idx);
  72714. var y = data.get(dims[1], idx);
  72715. var pt = [x, y];
  72716. coordSys.clampData && coordSys.clampData(pt, pt);
  72717. point = coordSys.dataToPoint(pt, true);
  72718. }
  72719. if (isCoordinateSystemType(coordSys, 'cartesian2d')) {
  72720. // TODO: TYPE ts@4.1 may still infer it as Axis instead of Axis2D. Not sure if it's a bug
  72721. var xAxis = coordSys.getAxis('x');
  72722. var yAxis = coordSys.getAxis('y');
  72723. var x = data.get(dims[0], idx);
  72724. var y = data.get(dims[1], idx);
  72725. if (isInifinity$1(x)) {
  72726. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  72727. } else if (isInifinity$1(y)) {
  72728. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  72729. }
  72730. } // Use x, y if has any
  72731. if (!isNaN(xPx)) {
  72732. point[0] = xPx;
  72733. }
  72734. if (!isNaN(yPx)) {
  72735. point[1] = yPx;
  72736. }
  72737. }
  72738. return point;
  72739. }
  72740. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  72741. var MarkAreaView =
  72742. /** @class */
  72743. function (_super) {
  72744. __extends(MarkAreaView, _super);
  72745. function MarkAreaView() {
  72746. var _this = _super !== null && _super.apply(this, arguments) || this;
  72747. _this.type = MarkAreaView.type;
  72748. return _this;
  72749. }
  72750. MarkAreaView.prototype.updateTransform = function (markAreaModel, ecModel, api) {
  72751. ecModel.eachSeries(function (seriesModel) {
  72752. var maModel = MarkerModel.getMarkerModelFromSeries(seriesModel, 'markArea');
  72753. if (maModel) {
  72754. var areaData_1 = maModel.getData();
  72755. areaData_1.each(function (idx) {
  72756. var points = map(dimPermutations, function (dim) {
  72757. return getSingleMarkerEndPoint(areaData_1, idx, dim, seriesModel, api);
  72758. }); // Layout
  72759. areaData_1.setItemLayout(idx, points);
  72760. var el = areaData_1.getItemGraphicEl(idx);
  72761. el.setShape('points', points);
  72762. });
  72763. }
  72764. }, this);
  72765. };
  72766. MarkAreaView.prototype.renderSeries = function (seriesModel, maModel, ecModel, api) {
  72767. var coordSys = seriesModel.coordinateSystem;
  72768. var seriesId = seriesModel.id;
  72769. var seriesData = seriesModel.getData();
  72770. var areaGroupMap = this.markerGroupMap;
  72771. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  72772. group: new Group()
  72773. });
  72774. this.group.add(polygonGroup.group);
  72775. this.markKeep(polygonGroup);
  72776. var areaData = createList$3(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  72777. maModel.setData(areaData); // Update visual and layout of line
  72778. areaData.each(function (idx) {
  72779. // Layout
  72780. var points = map(dimPermutations, function (dim) {
  72781. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72782. }); // If none of the area is inside coordSys, allClipped is set to be true
  72783. // in layout so that label will not be displayed. See #12591
  72784. var allClipped = true;
  72785. each(dimPermutations, function (dim) {
  72786. if (!allClipped) {
  72787. return;
  72788. }
  72789. var xValue = areaData.get(dim[0], idx);
  72790. var yValue = areaData.get(dim[1], idx); // If is infinity, the axis should be considered not clipped
  72791. if ((isInifinity$1(xValue) || coordSys.getAxis('x').containData(xValue)) && (isInifinity$1(yValue) || coordSys.getAxis('y').containData(yValue))) {
  72792. allClipped = false;
  72793. }
  72794. });
  72795. areaData.setItemLayout(idx, {
  72796. points: points,
  72797. allClipped: allClipped
  72798. });
  72799. var style = areaData.getItemModel(idx).getModel('itemStyle').getItemStyle();
  72800. var color$1 = getVisualFromData(seriesData, 'color');
  72801. if (!style.fill) {
  72802. style.fill = color$1;
  72803. if (typeof style.fill === 'string') {
  72804. style.fill = modifyAlpha(style.fill, 0.4);
  72805. }
  72806. }
  72807. if (!style.stroke) {
  72808. style.stroke = color$1;
  72809. } // Visual
  72810. areaData.setItemVisual(idx, 'style', style);
  72811. });
  72812. areaData.diff(inner$l(polygonGroup).data).add(function (idx) {
  72813. var layout = areaData.getItemLayout(idx);
  72814. if (!layout.allClipped) {
  72815. var polygon = new Polygon({
  72816. shape: {
  72817. points: layout.points
  72818. }
  72819. });
  72820. areaData.setItemGraphicEl(idx, polygon);
  72821. polygonGroup.group.add(polygon);
  72822. }
  72823. }).update(function (newIdx, oldIdx) {
  72824. var polygon = inner$l(polygonGroup).data.getItemGraphicEl(oldIdx);
  72825. var layout = areaData.getItemLayout(newIdx);
  72826. if (!layout.allClipped) {
  72827. if (polygon) {
  72828. updateProps(polygon, {
  72829. shape: {
  72830. points: layout.points
  72831. }
  72832. }, maModel, newIdx);
  72833. } else {
  72834. polygon = new Polygon({
  72835. shape: {
  72836. points: layout.points
  72837. }
  72838. });
  72839. }
  72840. areaData.setItemGraphicEl(newIdx, polygon);
  72841. polygonGroup.group.add(polygon);
  72842. } else if (polygon) {
  72843. polygonGroup.group.remove(polygon);
  72844. }
  72845. }).remove(function (idx) {
  72846. var polygon = inner$l(polygonGroup).data.getItemGraphicEl(idx);
  72847. polygonGroup.group.remove(polygon);
  72848. }).execute();
  72849. areaData.eachItemGraphicEl(function (polygon, idx) {
  72850. var itemModel = areaData.getItemModel(idx);
  72851. var style = areaData.getItemVisual(idx, 'style');
  72852. polygon.useStyle(areaData.getItemVisual(idx, 'style'));
  72853. setLabelStyle(polygon, getLabelStatesModels(itemModel), {
  72854. labelFetcher: maModel,
  72855. labelDataIndex: idx,
  72856. defaultText: areaData.getName(idx) || '',
  72857. inheritColor: typeof style.fill === 'string' ? modifyAlpha(style.fill, 1) : '#000'
  72858. });
  72859. setStatesStylesFromModel(polygon, itemModel);
  72860. enableHoverEmphasis(polygon);
  72861. getECData(polygon).dataModel = maModel;
  72862. });
  72863. inner$l(polygonGroup).data = areaData;
  72864. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  72865. };
  72866. MarkAreaView.type = 'markArea';
  72867. return MarkAreaView;
  72868. }(MarkerView);
  72869. function createList$3(coordSys, seriesModel, maModel) {
  72870. var coordDimsInfos;
  72871. var areaData;
  72872. var dims = ['x0', 'y0', 'x1', 'y1'];
  72873. if (coordSys) {
  72874. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72875. var data = seriesModel.getData();
  72876. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  72877. return defaults({
  72878. name: coordDim
  72879. }, info);
  72880. });
  72881. areaData = new List(map(dims, function (dim, idx) {
  72882. return {
  72883. name: dim,
  72884. type: coordDimsInfos[idx % 2].type
  72885. };
  72886. }), maModel);
  72887. } else {
  72888. coordDimsInfos = [{
  72889. name: 'value',
  72890. type: 'float'
  72891. }];
  72892. areaData = new List(coordDimsInfos, maModel);
  72893. }
  72894. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  72895. if (coordSys) {
  72896. optData = filter(optData, curry(markAreaFilter, coordSys));
  72897. }
  72898. var dimValueGetter = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  72899. // TODO should convert to ParsedValue?
  72900. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  72901. } : function (item) {
  72902. return item.value;
  72903. };
  72904. areaData.initData(optData, null, dimValueGetter);
  72905. areaData.hasItemOption = true;
  72906. return areaData;
  72907. }
  72908. function install$G(registers) {
  72909. registers.registerComponentModel(MarkAreaModel);
  72910. registers.registerComponentView(MarkAreaView);
  72911. registers.registerPreprocessor(function (opt) {
  72912. // Make sure markArea component is enabled
  72913. opt.markArea = opt.markArea || {};
  72914. });
  72915. }
  72916. var getDefaultSelectorOptions = function (ecModel, type) {
  72917. if (type === 'all') {
  72918. return {
  72919. type: 'all',
  72920. title: ecModel.getLocale(['legend', 'selector', 'all'])
  72921. };
  72922. } else if (type === 'inverse') {
  72923. return {
  72924. type: 'inverse',
  72925. title: ecModel.getLocale(['legend', 'selector', 'inverse'])
  72926. };
  72927. }
  72928. };
  72929. var LegendModel =
  72930. /** @class */
  72931. function (_super) {
  72932. __extends(LegendModel, _super);
  72933. function LegendModel() {
  72934. var _this = _super !== null && _super.apply(this, arguments) || this;
  72935. _this.type = LegendModel.type;
  72936. _this.layoutMode = {
  72937. type: 'box',
  72938. // legend.width/height are maxWidth/maxHeight actually,
  72939. // whereas realy width/height is calculated by its content.
  72940. // (Setting {left: 10, right: 10} does not make sense).
  72941. // So consider the case:
  72942. // `setOption({legend: {left: 10});`
  72943. // then `setOption({legend: {right: 10});`
  72944. // The previous `left` should be cleared by setting `ignoreSize`.
  72945. ignoreSize: true
  72946. };
  72947. return _this;
  72948. }
  72949. LegendModel.prototype.init = function (option, parentModel, ecModel) {
  72950. this.mergeDefaultAndTheme(option, ecModel);
  72951. option.selected = option.selected || {};
  72952. this._updateSelector(option);
  72953. };
  72954. LegendModel.prototype.mergeOption = function (option, ecModel) {
  72955. _super.prototype.mergeOption.call(this, option, ecModel);
  72956. this._updateSelector(option);
  72957. };
  72958. LegendModel.prototype._updateSelector = function (option) {
  72959. var selector = option.selector;
  72960. var ecModel = this.ecModel;
  72961. if (selector === true) {
  72962. selector = option.selector = ['all', 'inverse'];
  72963. }
  72964. if (isArray(selector)) {
  72965. each(selector, function (item, index) {
  72966. isString(item) && (item = {
  72967. type: item
  72968. });
  72969. selector[index] = merge(item, getDefaultSelectorOptions(ecModel, item.type));
  72970. });
  72971. }
  72972. };
  72973. LegendModel.prototype.optionUpdated = function () {
  72974. this._updateData(this.ecModel);
  72975. var legendData = this._data; // If selectedMode is single, try to select one
  72976. if (legendData[0] && this.get('selectedMode') === 'single') {
  72977. var hasSelected = false; // If has any selected in option.selected
  72978. for (var i = 0; i < legendData.length; i++) {
  72979. var name_1 = legendData[i].get('name');
  72980. if (this.isSelected(name_1)) {
  72981. // Force to unselect others
  72982. this.select(name_1);
  72983. hasSelected = true;
  72984. break;
  72985. }
  72986. } // Try select the first if selectedMode is single
  72987. !hasSelected && this.select(legendData[0].get('name'));
  72988. }
  72989. };
  72990. LegendModel.prototype._updateData = function (ecModel) {
  72991. var potentialData = [];
  72992. var availableNames = [];
  72993. ecModel.eachRawSeries(function (seriesModel) {
  72994. var seriesName = seriesModel.name;
  72995. availableNames.push(seriesName);
  72996. var isPotential;
  72997. if (seriesModel.legendVisualProvider) {
  72998. var provider = seriesModel.legendVisualProvider;
  72999. var names = provider.getAllNames();
  73000. if (!ecModel.isSeriesFiltered(seriesModel)) {
  73001. availableNames = availableNames.concat(names);
  73002. }
  73003. if (names.length) {
  73004. potentialData = potentialData.concat(names);
  73005. } else {
  73006. isPotential = true;
  73007. }
  73008. } else {
  73009. isPotential = true;
  73010. }
  73011. if (isPotential && isNameSpecified(seriesModel)) {
  73012. potentialData.push(seriesModel.name);
  73013. }
  73014. });
  73015. /**
  73016. * @type {Array.<string>}
  73017. * @private
  73018. */
  73019. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  73020. // which is convinient for user preparing option.
  73021. var rawData = this.get('data') || potentialData;
  73022. var legendData = map(rawData, function (dataItem) {
  73023. // Can be string or number
  73024. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  73025. dataItem = {
  73026. name: dataItem
  73027. };
  73028. }
  73029. return new Model(dataItem, this, this.ecModel);
  73030. }, this);
  73031. /**
  73032. * @type {Array.<module:echarts/model/Model>}
  73033. * @private
  73034. */
  73035. this._data = legendData;
  73036. };
  73037. LegendModel.prototype.getData = function () {
  73038. return this._data;
  73039. };
  73040. LegendModel.prototype.select = function (name) {
  73041. var selected = this.option.selected;
  73042. var selectedMode = this.get('selectedMode');
  73043. if (selectedMode === 'single') {
  73044. var data = this._data;
  73045. each(data, function (dataItem) {
  73046. selected[dataItem.get('name')] = false;
  73047. });
  73048. }
  73049. selected[name] = true;
  73050. };
  73051. LegendModel.prototype.unSelect = function (name) {
  73052. if (this.get('selectedMode') !== 'single') {
  73053. this.option.selected[name] = false;
  73054. }
  73055. };
  73056. LegendModel.prototype.toggleSelected = function (name) {
  73057. var selected = this.option.selected; // Default is true
  73058. if (!selected.hasOwnProperty(name)) {
  73059. selected[name] = true;
  73060. }
  73061. this[selected[name] ? 'unSelect' : 'select'](name);
  73062. };
  73063. LegendModel.prototype.allSelect = function () {
  73064. var data = this._data;
  73065. var selected = this.option.selected;
  73066. each(data, function (dataItem) {
  73067. selected[dataItem.get('name', true)] = true;
  73068. });
  73069. };
  73070. LegendModel.prototype.inverseSelect = function () {
  73071. var data = this._data;
  73072. var selected = this.option.selected;
  73073. each(data, function (dataItem) {
  73074. var name = dataItem.get('name', true); // Initially, default value is true
  73075. if (!selected.hasOwnProperty(name)) {
  73076. selected[name] = true;
  73077. }
  73078. selected[name] = !selected[name];
  73079. });
  73080. };
  73081. LegendModel.prototype.isSelected = function (name) {
  73082. var selected = this.option.selected;
  73083. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  73084. };
  73085. LegendModel.prototype.getOrient = function () {
  73086. return this.get('orient') === 'vertical' ? {
  73087. index: 1,
  73088. name: 'vertical'
  73089. } : {
  73090. index: 0,
  73091. name: 'horizontal'
  73092. };
  73093. };
  73094. LegendModel.type = 'legend.plain';
  73095. LegendModel.dependencies = ['series'];
  73096. LegendModel.defaultOption = {
  73097. zlevel: 0,
  73098. z: 4,
  73099. show: true,
  73100. orient: 'horizontal',
  73101. left: 'center',
  73102. // right: 'center',
  73103. top: 0,
  73104. // bottom: null,
  73105. align: 'auto',
  73106. backgroundColor: 'rgba(0,0,0,0)',
  73107. borderColor: '#ccc',
  73108. borderRadius: 0,
  73109. borderWidth: 0,
  73110. padding: 5,
  73111. itemGap: 10,
  73112. itemWidth: 25,
  73113. itemHeight: 14,
  73114. inactiveColor: '#ccc',
  73115. inactiveBorderColor: '#ccc',
  73116. itemStyle: {
  73117. borderWidth: 0
  73118. },
  73119. textStyle: {
  73120. color: '#333'
  73121. },
  73122. selectedMode: true,
  73123. selector: false,
  73124. selectorLabel: {
  73125. show: true,
  73126. borderRadius: 10,
  73127. padding: [3, 5, 3, 5],
  73128. fontSize: 12,
  73129. fontFamily: ' sans-serif',
  73130. color: '#666',
  73131. borderWidth: 1,
  73132. borderColor: '#666'
  73133. },
  73134. emphasis: {
  73135. selectorLabel: {
  73136. show: true,
  73137. color: '#eee',
  73138. backgroundColor: '#666'
  73139. }
  73140. },
  73141. selectorPosition: 'auto',
  73142. selectorItemGap: 7,
  73143. selectorButtonGap: 10,
  73144. tooltip: {
  73145. show: false
  73146. }
  73147. };
  73148. return LegendModel;
  73149. }(ComponentModel);
  73150. var curry$1 = curry;
  73151. var each$e = each;
  73152. var Group$2 = Group;
  73153. var LegendView =
  73154. /** @class */
  73155. function (_super) {
  73156. __extends(LegendView, _super);
  73157. function LegendView() {
  73158. var _this = _super !== null && _super.apply(this, arguments) || this;
  73159. _this.type = LegendView.type;
  73160. _this.newlineDisabled = false;
  73161. return _this;
  73162. }
  73163. LegendView.prototype.init = function () {
  73164. this.group.add(this._contentGroup = new Group$2());
  73165. this.group.add(this._selectorGroup = new Group$2());
  73166. this._isFirstRender = true;
  73167. };
  73168. /**
  73169. * @protected
  73170. */
  73171. LegendView.prototype.getContentGroup = function () {
  73172. return this._contentGroup;
  73173. };
  73174. /**
  73175. * @protected
  73176. */
  73177. LegendView.prototype.getSelectorGroup = function () {
  73178. return this._selectorGroup;
  73179. };
  73180. /**
  73181. * @override
  73182. */
  73183. LegendView.prototype.render = function (legendModel, ecModel, api) {
  73184. var isFirstRender = this._isFirstRender;
  73185. this._isFirstRender = false;
  73186. this.resetInner();
  73187. if (!legendModel.get('show', true)) {
  73188. return;
  73189. }
  73190. var itemAlign = legendModel.get('align');
  73191. var orient = legendModel.get('orient');
  73192. if (!itemAlign || itemAlign === 'auto') {
  73193. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  73194. } // selector has been normalized to an array in model
  73195. var selector = legendModel.get('selector', true);
  73196. var selectorPosition = legendModel.get('selectorPosition', true);
  73197. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  73198. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  73199. }
  73200. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  73201. var positionInfo = legendModel.getBoxLayoutParams();
  73202. var viewportSize = {
  73203. width: api.getWidth(),
  73204. height: api.getHeight()
  73205. };
  73206. var padding = legendModel.get('padding');
  73207. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  73208. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  73209. var layoutRect = getLayoutRect(defaults({
  73210. width: mainRect.width,
  73211. height: mainRect.height
  73212. }, positionInfo), viewportSize, padding);
  73213. this.group.x = layoutRect.x - mainRect.x;
  73214. this.group.y = layoutRect.y - mainRect.y;
  73215. this.group.markRedraw(); // Render background after group is layout.
  73216. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  73217. };
  73218. LegendView.prototype.resetInner = function () {
  73219. this.getContentGroup().removeAll();
  73220. this._backgroundEl && this.group.remove(this._backgroundEl);
  73221. this.getSelectorGroup().removeAll();
  73222. };
  73223. LegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  73224. var contentGroup = this.getContentGroup();
  73225. var legendDrawnMap = createHashMap();
  73226. var selectMode = legendModel.get('selectedMode');
  73227. var excludeSeriesId = [];
  73228. ecModel.eachRawSeries(function (seriesModel) {
  73229. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  73230. });
  73231. each$e(legendModel.getData(), function (itemModel, dataIndex) {
  73232. var name = itemModel.get('name'); // Use empty string or \n as a newline string
  73233. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  73234. var g = new Group$2(); // @ts-ignore
  73235. g.newline = true;
  73236. contentGroup.add(g);
  73237. return;
  73238. } // Representitive series.
  73239. var seriesModel = ecModel.getSeriesByName(name)[0];
  73240. if (legendDrawnMap.get(name)) {
  73241. // Have been drawed
  73242. return;
  73243. } // Legend to control series.
  73244. if (seriesModel) {
  73245. var data = seriesModel.getData();
  73246. var style = data.getVisual('style');
  73247. var color = style[data.getVisual('drawType')] || style.fill;
  73248. var borderColor = style.stroke;
  73249. var decal = style.decal; // Using rect symbol defaultly
  73250. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  73251. var symbolType = data.getVisual('symbol');
  73252. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, decal, selectMode);
  73253. 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));
  73254. legendDrawnMap.set(name, true);
  73255. } else {
  73256. // Legend to control data. In pie and funnel.
  73257. ecModel.eachRawSeries(function (seriesModel) {
  73258. // In case multiple series has same data name
  73259. if (legendDrawnMap.get(name)) {
  73260. return;
  73261. }
  73262. if (seriesModel.legendVisualProvider) {
  73263. var provider = seriesModel.legendVisualProvider;
  73264. if (!provider.containName(name)) {
  73265. return;
  73266. }
  73267. var idx = provider.indexOfName(name);
  73268. var style = provider.getItemVisual(idx, 'style');
  73269. var borderColor = style.stroke;
  73270. var decal = style.decal;
  73271. var color = style.fill;
  73272. var colorArr = parse(style.fill); // Color may be set to transparent in visualMap when data is out of range.
  73273. // Do not show nothing.
  73274. if (colorArr && colorArr[3] === 0) {
  73275. colorArr[3] = 0.2; // TODO color is set to 0, 0, 0, 0. Should show correct RGBA
  73276. color = stringify(colorArr, 'rgba');
  73277. }
  73278. var legendSymbolType = 'roundRect';
  73279. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, null, itemAlign, color, borderColor, decal, selectMode); // FIXME: consider different series has items with the same name.
  73280. itemGroup.on('click', curry$1(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  73281. // more than one pie series.
  73282. .on('mouseover', curry$1(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$1(dispatchDownplayAction, null, name, api, excludeSeriesId));
  73283. legendDrawnMap.set(name, true);
  73284. }
  73285. }, this);
  73286. }
  73287. if ("development" !== 'production') {
  73288. if (!legendDrawnMap.get(name)) {
  73289. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  73290. }
  73291. }
  73292. }, this);
  73293. if (selector) {
  73294. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  73295. }
  73296. };
  73297. LegendView.prototype._createSelector = function (selector, legendModel, api, orient, selectorPosition) {
  73298. var selectorGroup = this.getSelectorGroup();
  73299. each$e(selector, function createSelectorButton(selectorItem) {
  73300. var type = selectorItem.type;
  73301. var labelText = new ZRText({
  73302. style: {
  73303. x: 0,
  73304. y: 0,
  73305. align: 'center',
  73306. verticalAlign: 'middle'
  73307. },
  73308. onclick: function () {
  73309. api.dispatchAction({
  73310. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  73311. });
  73312. }
  73313. });
  73314. selectorGroup.add(labelText);
  73315. var labelModel = legendModel.getModel('selectorLabel');
  73316. var emphasisLabelModel = legendModel.getModel(['emphasis', 'selectorLabel']);
  73317. setLabelStyle(labelText, {
  73318. normal: labelModel,
  73319. emphasis: emphasisLabelModel
  73320. }, {
  73321. defaultText: selectorItem.title
  73322. });
  73323. enableHoverEmphasis(labelText);
  73324. });
  73325. };
  73326. LegendView.prototype._createItem = function (name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, decal, selectMode) {
  73327. var itemWidth = legendModel.get('itemWidth');
  73328. var itemHeight = legendModel.get('itemHeight');
  73329. var inactiveColor = legendModel.get('inactiveColor');
  73330. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  73331. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  73332. var legendModelItemStyle = legendModel.getModel('itemStyle');
  73333. var isSelected = legendModel.isSelected(name);
  73334. var itemGroup = new Group$2();
  73335. var textStyleModel = itemModel.getModel('textStyle');
  73336. var itemIcon = itemModel.get('icon');
  73337. var tooltipModel = itemModel.getModel('tooltip');
  73338. var legendGlobalTooltipModel = tooltipModel.parentModel; // Use user given icon first
  73339. legendSymbolType = itemIcon || legendSymbolType;
  73340. var legendSymbol = createSymbol(legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  73341. symbolKeepAspect == null ? true : symbolKeepAspect);
  73342. itemGroup.add(setSymbolStyle(legendSymbol, legendSymbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected)); // Compose symbols
  73343. // PENDING
  73344. if (!itemIcon && symbolType // At least show one symbol, can't be all none
  73345. && (symbolType !== legendSymbolType || symbolType === 'none')) {
  73346. var size = itemHeight * 0.8;
  73347. if (symbolType === 'none') {
  73348. symbolType = 'circle';
  73349. }
  73350. var legendSymbolCenter = createSymbol(symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  73351. symbolKeepAspect == null ? true : symbolKeepAspect); // Put symbol in the center
  73352. itemGroup.add(setSymbolStyle(legendSymbolCenter, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected));
  73353. }
  73354. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  73355. var textAlign = itemAlign;
  73356. var formatter = legendModel.get('formatter');
  73357. var content = name;
  73358. if (typeof formatter === 'string' && formatter) {
  73359. content = formatter.replace('{name}', name != null ? name : '');
  73360. } else if (typeof formatter === 'function') {
  73361. content = formatter(name);
  73362. }
  73363. itemGroup.add(new ZRText({
  73364. style: createTextStyle(textStyleModel, {
  73365. text: content,
  73366. x: textX,
  73367. y: itemHeight / 2,
  73368. fill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  73369. align: textAlign,
  73370. verticalAlign: 'middle'
  73371. })
  73372. })); // Add a invisible rect to increase the area of mouse hover
  73373. var hitRect = new Rect({
  73374. shape: itemGroup.getBoundingRect(),
  73375. invisible: true
  73376. });
  73377. if (tooltipModel.get('show')) {
  73378. var formatterParams = {
  73379. componentType: 'legend',
  73380. legendIndex: legendModel.componentIndex,
  73381. name: name,
  73382. $vars: ['name']
  73383. };
  73384. hitRect.tooltip = extend({
  73385. content: name,
  73386. // Defaul formatter
  73387. formatter: legendGlobalTooltipModel.get('formatter', true) || function (params) {
  73388. return params.name;
  73389. },
  73390. formatterParams: formatterParams
  73391. }, tooltipModel.option);
  73392. }
  73393. itemGroup.add(hitRect);
  73394. itemGroup.eachChild(function (child) {
  73395. child.silent = true;
  73396. });
  73397. hitRect.silent = !selectMode;
  73398. this.getContentGroup().add(itemGroup);
  73399. enableHoverEmphasis(itemGroup); // @ts-ignore
  73400. itemGroup.__legendDataIndex = dataIndex;
  73401. return itemGroup;
  73402. };
  73403. LegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  73404. var contentGroup = this.getContentGroup();
  73405. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  73406. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  73407. var contentRect = contentGroup.getBoundingRect();
  73408. var contentPos = [-contentRect.x, -contentRect.y];
  73409. selectorGroup.markRedraw();
  73410. contentGroup.markRedraw();
  73411. if (selector) {
  73412. // Place buttons in selectorGroup
  73413. box( // Buttons in selectorGroup always layout horizontally
  73414. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  73415. var selectorRect = selectorGroup.getBoundingRect();
  73416. var selectorPos = [-selectorRect.x, -selectorRect.y];
  73417. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  73418. var orientIdx = legendModel.getOrient().index;
  73419. var wh = orientIdx === 0 ? 'width' : 'height';
  73420. var hw = orientIdx === 0 ? 'height' : 'width';
  73421. var yx = orientIdx === 0 ? 'y' : 'x';
  73422. if (selectorPosition === 'end') {
  73423. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  73424. } else {
  73425. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  73426. } //Always align selector to content as 'middle'
  73427. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  73428. selectorGroup.x = selectorPos[0];
  73429. selectorGroup.y = selectorPos[1];
  73430. contentGroup.x = contentPos[0];
  73431. contentGroup.y = contentPos[1];
  73432. var mainRect = {
  73433. x: 0,
  73434. y: 0
  73435. };
  73436. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  73437. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  73438. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  73439. return mainRect;
  73440. } else {
  73441. contentGroup.x = contentPos[0];
  73442. contentGroup.y = contentPos[1];
  73443. return this.group.getBoundingRect();
  73444. }
  73445. };
  73446. /**
  73447. * @protected
  73448. */
  73449. LegendView.prototype.remove = function () {
  73450. this.getContentGroup().removeAll();
  73451. this._isFirstRender = true;
  73452. };
  73453. LegendView.type = 'legend.plain';
  73454. return LegendView;
  73455. }(ComponentView);
  73456. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, decal, isSelected) {
  73457. var itemStyle;
  73458. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  73459. itemStyle = legendModelItemStyle.getItemStyle();
  73460. symbol.style.stroke = borderColor;
  73461. symbol.style.decal = decal;
  73462. if (!isSelected) {
  73463. itemStyle.stroke = inactiveBorderColor;
  73464. }
  73465. } else {
  73466. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  73467. }
  73468. symbol.setStyle(itemStyle);
  73469. return symbol;
  73470. }
  73471. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  73472. // downplay before unselect
  73473. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  73474. api.dispatchAction({
  73475. type: 'legendToggleSelect',
  73476. name: seriesName != null ? seriesName : dataName
  73477. }); // highlight after select
  73478. // TODO higlight immediately may cause animation loss.
  73479. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  73480. }
  73481. function isUseHoverLayer(api) {
  73482. var list = api.getZr().storage.getDisplayList();
  73483. var emphasisState;
  73484. var i = 0;
  73485. var len = list.length;
  73486. while (i < len && !(emphasisState = list[i].states.emphasis)) {
  73487. i++;
  73488. }
  73489. return emphasisState && emphasisState.hoverLayer;
  73490. }
  73491. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  73492. // If element hover will move to a hoverLayer.
  73493. if (!isUseHoverLayer(api)) {
  73494. api.dispatchAction({
  73495. type: 'highlight',
  73496. seriesName: seriesName,
  73497. name: dataName,
  73498. excludeSeriesId: excludeSeriesId
  73499. });
  73500. }
  73501. }
  73502. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  73503. // If element hover will move to a hoverLayer.
  73504. if (!isUseHoverLayer(api)) {
  73505. api.dispatchAction({
  73506. type: 'downplay',
  73507. seriesName: seriesName,
  73508. name: dataName,
  73509. excludeSeriesId: excludeSeriesId
  73510. });
  73511. }
  73512. }
  73513. /*
  73514. * Licensed to the Apache Software Foundation (ASF) under one
  73515. * or more contributor license agreements. See the NOTICE file
  73516. * distributed with this work for additional information
  73517. * regarding copyright ownership. The ASF licenses this file
  73518. * to you under the Apache License, Version 2.0 (the
  73519. * "License"); you may not use this file except in compliance
  73520. * with the License. You may obtain a copy of the License at
  73521. *
  73522. * http://www.apache.org/licenses/LICENSE-2.0
  73523. *
  73524. * Unless required by applicable law or agreed to in writing,
  73525. * software distributed under the License is distributed on an
  73526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73527. * KIND, either express or implied. See the License for the
  73528. * specific language governing permissions and limitations
  73529. * under the License.
  73530. */
  73531. /**
  73532. * AUTO-GENERATED FILE. DO NOT MODIFY.
  73533. */
  73534. /*
  73535. * Licensed to the Apache Software Foundation (ASF) under one
  73536. * or more contributor license agreements. See the NOTICE file
  73537. * distributed with this work for additional information
  73538. * regarding copyright ownership. The ASF licenses this file
  73539. * to you under the Apache License, Version 2.0 (the
  73540. * "License"); you may not use this file except in compliance
  73541. * with the License. You may obtain a copy of the License at
  73542. *
  73543. * http://www.apache.org/licenses/LICENSE-2.0
  73544. *
  73545. * Unless required by applicable law or agreed to in writing,
  73546. * software distributed under the License is distributed on an
  73547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73548. * KIND, either express or implied. See the License for the
  73549. * specific language governing permissions and limitations
  73550. * under the License.
  73551. */
  73552. function legendFilter(ecModel) {
  73553. var legendModels = ecModel.findComponents({
  73554. mainType: 'legend'
  73555. });
  73556. if (legendModels && legendModels.length) {
  73557. ecModel.filterSeries(function (series) {
  73558. // If in any legend component the status is not selected.
  73559. // Because in legend series is assumed selected when it is not in the legend data.
  73560. for (var i = 0; i < legendModels.length; i++) {
  73561. if (!legendModels[i].isSelected(series.name)) {
  73562. return false;
  73563. }
  73564. }
  73565. return true;
  73566. });
  73567. }
  73568. }
  73569. function legendSelectActionHandler(methodName, payload, ecModel) {
  73570. var selectedMap = {};
  73571. var isToggleSelect = methodName === 'toggleSelected';
  73572. var isSelected; // Update all legend components
  73573. ecModel.eachComponent('legend', function (legendModel) {
  73574. if (isToggleSelect && isSelected != null) {
  73575. // Force other legend has same selected status
  73576. // Or the first is toggled to true and other are toggled to false
  73577. // In the case one legend has some item unSelected in option. And if other legend
  73578. // doesn't has the item, they will assume it is selected.
  73579. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  73580. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  73581. legendModel[methodName]();
  73582. } else {
  73583. legendModel[methodName](payload.name);
  73584. isSelected = legendModel.isSelected(payload.name);
  73585. }
  73586. var legendData = legendModel.getData();
  73587. each(legendData, function (model) {
  73588. var name = model.get('name'); // Wrap element
  73589. if (name === '\n' || name === '') {
  73590. return;
  73591. }
  73592. var isItemSelected = legendModel.isSelected(name);
  73593. if (selectedMap.hasOwnProperty(name)) {
  73594. // Unselected if any legend is unselected
  73595. selectedMap[name] = selectedMap[name] && isItemSelected;
  73596. } else {
  73597. selectedMap[name] = isItemSelected;
  73598. }
  73599. });
  73600. }); // Return the event explicitly
  73601. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  73602. selected: selectedMap
  73603. } : {
  73604. name: payload.name,
  73605. selected: selectedMap
  73606. };
  73607. }
  73608. function installLegendAction(registers) {
  73609. /**
  73610. * @event legendToggleSelect
  73611. * @type {Object}
  73612. * @property {string} type 'legendToggleSelect'
  73613. * @property {string} [from]
  73614. * @property {string} name Series name or data item name
  73615. */
  73616. registers.registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  73617. registers.registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  73618. registers.registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  73619. /**
  73620. * @event legendSelect
  73621. * @type {Object}
  73622. * @property {string} type 'legendSelect'
  73623. * @property {string} name Series name or data item name
  73624. */
  73625. registers.registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  73626. /**
  73627. * @event legendUnSelect
  73628. * @type {Object}
  73629. * @property {string} type 'legendUnSelect'
  73630. * @property {string} name Series name or data item name
  73631. */
  73632. registers.registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  73633. }
  73634. function install$H(registers) {
  73635. registers.registerComponentModel(LegendModel);
  73636. registers.registerComponentView(LegendView);
  73637. registers.registerProcessor(registers.PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  73638. registers.registerSubTypeDefaulter('legend', function () {
  73639. return 'plain';
  73640. });
  73641. installLegendAction(registers);
  73642. }
  73643. var ScrollableLegendModel =
  73644. /** @class */
  73645. function (_super) {
  73646. __extends(ScrollableLegendModel, _super);
  73647. function ScrollableLegendModel() {
  73648. var _this = _super !== null && _super.apply(this, arguments) || this;
  73649. _this.type = ScrollableLegendModel.type;
  73650. return _this;
  73651. }
  73652. /**
  73653. * @param {number} scrollDataIndex
  73654. */
  73655. ScrollableLegendModel.prototype.setScrollDataIndex = function (scrollDataIndex) {
  73656. this.option.scrollDataIndex = scrollDataIndex;
  73657. };
  73658. ScrollableLegendModel.prototype.init = function (option, parentModel, ecModel) {
  73659. var inputPositionParams = getLayoutParams(option);
  73660. _super.prototype.init.call(this, option, parentModel, ecModel);
  73661. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  73662. };
  73663. /**
  73664. * @override
  73665. */
  73666. ScrollableLegendModel.prototype.mergeOption = function (option, ecModel) {
  73667. _super.prototype.mergeOption.call(this, option, ecModel);
  73668. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  73669. };
  73670. ScrollableLegendModel.type = 'legend.scroll';
  73671. ScrollableLegendModel.defaultOption = inheritDefaultOption(LegendModel.defaultOption, {
  73672. scrollDataIndex: 0,
  73673. pageButtonItemGap: 5,
  73674. pageButtonGap: null,
  73675. pageButtonPosition: 'end',
  73676. pageFormatter: '{current}/{total}',
  73677. pageIcons: {
  73678. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  73679. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  73680. },
  73681. pageIconColor: '#2f4554',
  73682. pageIconInactiveColor: '#aaa',
  73683. pageIconSize: 15,
  73684. pageTextStyle: {
  73685. color: '#333'
  73686. },
  73687. animationDurationUpdate: 800
  73688. });
  73689. return ScrollableLegendModel;
  73690. }(LegendModel);
  73691. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  73692. var orient = legendModel.getOrient();
  73693. var ignoreSize = [1, 1];
  73694. ignoreSize[orient.index] = 0;
  73695. mergeLayoutParam(target, raw, {
  73696. type: 'box',
  73697. ignoreSize: !!ignoreSize
  73698. });
  73699. }
  73700. var Group$3 = Group;
  73701. var WH$1 = ['width', 'height'];
  73702. var XY$1 = ['x', 'y'];
  73703. var ScrollableLegendView =
  73704. /** @class */
  73705. function (_super) {
  73706. __extends(ScrollableLegendView, _super);
  73707. function ScrollableLegendView() {
  73708. var _this = _super !== null && _super.apply(this, arguments) || this;
  73709. _this.type = ScrollableLegendView.type;
  73710. _this.newlineDisabled = true;
  73711. _this._currentIndex = 0;
  73712. return _this;
  73713. }
  73714. ScrollableLegendView.prototype.init = function () {
  73715. _super.prototype.init.call(this);
  73716. this.group.add(this._containerGroup = new Group$3());
  73717. this._containerGroup.add(this.getContentGroup());
  73718. this.group.add(this._controllerGroup = new Group$3());
  73719. };
  73720. /**
  73721. * @override
  73722. */
  73723. ScrollableLegendView.prototype.resetInner = function () {
  73724. _super.prototype.resetInner.call(this);
  73725. this._controllerGroup.removeAll();
  73726. this._containerGroup.removeClipPath();
  73727. this._containerGroup.__rectSize = null;
  73728. };
  73729. /**
  73730. * @override
  73731. */
  73732. ScrollableLegendView.prototype.renderInner = function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  73733. var self = this; // Render content items.
  73734. _super.prototype.renderInner.call(this, itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  73735. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  73736. // e.g., '3/12345' should not overlap with the control arrow button.
  73737. var pageIconSize = legendModel.get('pageIconSize', true);
  73738. var pageIconSizeArr = isArray(pageIconSize) ? pageIconSize : [pageIconSize, pageIconSize];
  73739. createPageButton('pagePrev', 0);
  73740. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  73741. controllerGroup.add(new ZRText({
  73742. name: 'pageText',
  73743. style: {
  73744. // Placeholder to calculate a proper layout.
  73745. text: 'xx/xx',
  73746. fill: pageTextStyleModel.getTextColor(),
  73747. font: pageTextStyleModel.getFont(),
  73748. verticalAlign: 'middle',
  73749. align: 'center'
  73750. },
  73751. silent: true
  73752. }));
  73753. createPageButton('pageNext', 1);
  73754. function createPageButton(name, iconIdx) {
  73755. var pageDataIndexName = name + 'DataIndex';
  73756. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  73757. // Buttons will be created in each render, so we do not need
  73758. // to worry about avoiding using legendModel kept in scope.
  73759. onclick: bind(self._pageGo, self, pageDataIndexName, legendModel, api)
  73760. }, {
  73761. x: -pageIconSizeArr[0] / 2,
  73762. y: -pageIconSizeArr[1] / 2,
  73763. width: pageIconSizeArr[0],
  73764. height: pageIconSizeArr[1]
  73765. });
  73766. icon.name = name;
  73767. controllerGroup.add(icon);
  73768. }
  73769. };
  73770. /**
  73771. * @override
  73772. */
  73773. ScrollableLegendView.prototype.layoutInner = function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  73774. var selectorGroup = this.getSelectorGroup();
  73775. var orientIdx = legendModel.getOrient().index;
  73776. var wh = WH$1[orientIdx];
  73777. var xy = XY$1[orientIdx];
  73778. var hw = WH$1[1 - orientIdx];
  73779. var yx = XY$1[1 - orientIdx];
  73780. selector && box( // Buttons in selectorGroup always layout horizontally
  73781. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  73782. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  73783. var selectorRect = selectorGroup.getBoundingRect();
  73784. var selectorPos = [-selectorRect.x, -selectorRect.y];
  73785. var processMaxSize = clone(maxSize);
  73786. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  73787. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx, xy);
  73788. if (selector) {
  73789. if (selectorPosition === 'end') {
  73790. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  73791. } else {
  73792. var offset = selectorRect[wh] + selectorButtonGap;
  73793. selectorPos[orientIdx] -= offset;
  73794. mainRect[xy] -= offset;
  73795. }
  73796. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  73797. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  73798. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  73799. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  73800. selectorGroup.x = selectorPos[0];
  73801. selectorGroup.y = selectorPos[1];
  73802. selectorGroup.markRedraw();
  73803. }
  73804. return mainRect;
  73805. };
  73806. ScrollableLegendView.prototype._layoutContentAndController = function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx, xy) {
  73807. var contentGroup = this.getContentGroup();
  73808. var containerGroup = this._containerGroup;
  73809. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  73810. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  73811. box( // Buttons in controller are layout always horizontally.
  73812. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  73813. var contentRect = contentGroup.getBoundingRect();
  73814. var controllerRect = controllerGroup.getBoundingRect();
  73815. var showController = this._showController = contentRect[wh] > maxSize[wh]; // In case that the inner elements of contentGroup layout do not based on [0, 0]
  73816. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  73817. // If first rendering, `contentGroup.position` is [0, 0], which
  73818. // does not make sense and may cause unexepcted animation if adopted.
  73819. if (!isFirstRender) {
  73820. contentPos[orientIdx] = contentGroup[xy];
  73821. } // Layout container group based on 0.
  73822. var containerPos = [0, 0];
  73823. var controllerPos = [-controllerRect.x, -controllerRect.y];
  73824. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  73825. if (showController) {
  73826. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  73827. if (pageButtonPosition === 'end') {
  73828. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  73829. } // controller is on the left / top.
  73830. else {
  73831. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  73832. }
  73833. } // Always align controller to content as 'middle'.
  73834. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  73835. contentGroup.setPosition(contentPos);
  73836. containerGroup.setPosition(containerPos);
  73837. controllerGroup.setPosition(controllerPos); // Calculate `mainRect` and set `clipPath`.
  73838. // mainRect should not be calculated by `this.group.getBoundingRect()`
  73839. // for sake of the overflow.
  73840. var mainRect = {
  73841. x: 0,
  73842. y: 0
  73843. }; // Consider content may be overflow (should be clipped).
  73844. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  73845. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  73846. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  73847. containerGroup.__rectSize = maxSize[wh];
  73848. if (showController) {
  73849. var clipShape = {
  73850. x: 0,
  73851. y: 0
  73852. };
  73853. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  73854. clipShape[hw] = mainRect[hw];
  73855. containerGroup.setClipPath(new Rect({
  73856. shape: clipShape
  73857. })); // Consider content may be larger than container, container rect
  73858. // can not be obtained from `containerGroup.getBoundingRect()`.
  73859. containerGroup.__rectSize = clipShape[wh];
  73860. } else {
  73861. // Do not remove or ignore controller. Keep them set as placeholders.
  73862. controllerGroup.eachChild(function (child) {
  73863. child.attr({
  73864. invisible: true,
  73865. silent: true
  73866. });
  73867. });
  73868. } // Content translate animation.
  73869. var pageInfo = this._getPageInfo(legendModel);
  73870. pageInfo.pageIndex != null && updateProps(contentGroup, {
  73871. x: pageInfo.contentPosition[0],
  73872. y: pageInfo.contentPosition[1]
  73873. }, // When switch from "show controller" to "not show controller", view should be
  73874. // updated immediately without animation, otherwise causes weird effect.
  73875. showController ? legendModel : null);
  73876. this._updatePageInfoView(legendModel, pageInfo);
  73877. return mainRect;
  73878. };
  73879. ScrollableLegendView.prototype._pageGo = function (to, legendModel, api) {
  73880. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  73881. scrollDataIndex != null && api.dispatchAction({
  73882. type: 'legendScroll',
  73883. scrollDataIndex: scrollDataIndex,
  73884. legendId: legendModel.id
  73885. });
  73886. };
  73887. ScrollableLegendView.prototype._updatePageInfoView = function (legendModel, pageInfo) {
  73888. var controllerGroup = this._controllerGroup;
  73889. each(['pagePrev', 'pageNext'], function (name) {
  73890. var key = name + 'DataIndex';
  73891. var canJump = pageInfo[key] != null;
  73892. var icon = controllerGroup.childOfName(name);
  73893. if (icon) {
  73894. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  73895. icon.cursor = canJump ? 'pointer' : 'default';
  73896. }
  73897. });
  73898. var pageText = controllerGroup.childOfName('pageText');
  73899. var pageFormatter = legendModel.get('pageFormatter');
  73900. var pageIndex = pageInfo.pageIndex;
  73901. var current = pageIndex != null ? pageIndex + 1 : 0;
  73902. var total = pageInfo.pageCount;
  73903. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current == null ? '' : current + '').replace('{total}', total == null ? '' : total + '') : pageFormatter({
  73904. current: current,
  73905. total: total
  73906. }));
  73907. };
  73908. /**
  73909. * contentPosition: Array.<number>, null when data item not found.
  73910. * pageIndex: number, null when data item not found.
  73911. * pageCount: number, always be a number, can be 0.
  73912. * pagePrevDataIndex: number, null when no previous page.
  73913. * pageNextDataIndex: number, null when no next page.
  73914. * }
  73915. */
  73916. ScrollableLegendView.prototype._getPageInfo = function (legendModel) {
  73917. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  73918. var contentGroup = this.getContentGroup();
  73919. var containerRectSize = this._containerGroup.__rectSize;
  73920. var orientIdx = legendModel.getOrient().index;
  73921. var wh = WH$1[orientIdx];
  73922. var xy = XY$1[orientIdx];
  73923. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  73924. var children = contentGroup.children();
  73925. var targetItem = children[targetItemIndex];
  73926. var itemCount = children.length;
  73927. var pCount = !itemCount ? 0 : 1;
  73928. var result = {
  73929. contentPosition: [contentGroup.x, contentGroup.y],
  73930. pageCount: pCount,
  73931. pageIndex: pCount - 1,
  73932. pagePrevDataIndex: null,
  73933. pageNextDataIndex: null
  73934. };
  73935. if (!targetItem) {
  73936. return result;
  73937. }
  73938. var targetItemInfo = getItemInfo(targetItem);
  73939. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  73940. // (1) Always align based on the left/top most item.
  73941. // (2) It is user-friendly that the last item shown in the
  73942. // current window is shown at the begining of next window.
  73943. // Otherwise if half of the last item is cut by the window,
  73944. // it will have no chance to display entirely.
  73945. // (3) Consider that item size probably be different, we
  73946. // have calculate pageIndex by size rather than item index,
  73947. // and we can not get page index directly by division.
  73948. // (4) The window is to narrow to contain more than
  73949. // one item, we should make sure that the page can be fliped.
  73950. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  73951. currItemInfo = getItemInfo(children[i]);
  73952. if ( // Half of the last item is out of the window.
  73953. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  73954. // can be started at the current item or the last item.
  73955. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  73956. if (winEndItemInfo.i > winStartItemInfo.i) {
  73957. winStartItemInfo = winEndItemInfo;
  73958. } else {
  73959. // e.g., when page size is smaller than item size.
  73960. winStartItemInfo = currItemInfo;
  73961. }
  73962. if (winStartItemInfo) {
  73963. if (result.pageNextDataIndex == null) {
  73964. result.pageNextDataIndex = winStartItemInfo.i;
  73965. }
  73966. ++result.pageCount;
  73967. }
  73968. }
  73969. winEndItemInfo = currItemInfo;
  73970. }
  73971. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  73972. currItemInfo = getItemInfo(children[i]);
  73973. if ( // If the the end item does not intersect with the window started
  73974. // from the current item, a page can be settled.
  73975. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  73976. winStartItemInfo.i < winEndItemInfo.i) {
  73977. winEndItemInfo = winStartItemInfo;
  73978. if (result.pagePrevDataIndex == null) {
  73979. result.pagePrevDataIndex = winStartItemInfo.i;
  73980. }
  73981. ++result.pageCount;
  73982. ++result.pageIndex;
  73983. }
  73984. winStartItemInfo = currItemInfo;
  73985. }
  73986. return result;
  73987. function getItemInfo(el) {
  73988. if (el) {
  73989. var itemRect = el.getBoundingRect();
  73990. var start = itemRect[xy] + el[xy];
  73991. return {
  73992. s: start,
  73993. e: start + itemRect[wh],
  73994. i: el.__legendDataIndex
  73995. };
  73996. }
  73997. }
  73998. function intersect(itemInfo, winStart) {
  73999. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  74000. }
  74001. };
  74002. ScrollableLegendView.prototype._findTargetItemIndex = function (targetDataIndex) {
  74003. if (!this._showController) {
  74004. return 0;
  74005. }
  74006. var index;
  74007. var contentGroup = this.getContentGroup();
  74008. var defaultIndex;
  74009. contentGroup.eachChild(function (child, idx) {
  74010. var legendDataIdx = child.__legendDataIndex; // FIXME
  74011. // If the given targetDataIndex (from model) is illegal,
  74012. // we use defaultIndex. But the index on the legend model and
  74013. // action payload is still illegal. That case will not be
  74014. // changed until some scenario requires.
  74015. if (defaultIndex == null && legendDataIdx != null) {
  74016. defaultIndex = idx;
  74017. }
  74018. if (legendDataIdx === targetDataIndex) {
  74019. index = idx;
  74020. }
  74021. });
  74022. return index != null ? index : defaultIndex;
  74023. };
  74024. ScrollableLegendView.type = 'legend.scroll';
  74025. return ScrollableLegendView;
  74026. }(LegendView);
  74027. /*
  74028. * Licensed to the Apache Software Foundation (ASF) under one
  74029. * or more contributor license agreements. See the NOTICE file
  74030. * distributed with this work for additional information
  74031. * regarding copyright ownership. The ASF licenses this file
  74032. * to you under the Apache License, Version 2.0 (the
  74033. * "License"); you may not use this file except in compliance
  74034. * with the License. You may obtain a copy of the License at
  74035. *
  74036. * http://www.apache.org/licenses/LICENSE-2.0
  74037. *
  74038. * Unless required by applicable law or agreed to in writing,
  74039. * software distributed under the License is distributed on an
  74040. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74041. * KIND, either express or implied. See the License for the
  74042. * specific language governing permissions and limitations
  74043. * under the License.
  74044. */
  74045. /**
  74046. * AUTO-GENERATED FILE. DO NOT MODIFY.
  74047. */
  74048. /*
  74049. * Licensed to the Apache Software Foundation (ASF) under one
  74050. * or more contributor license agreements. See the NOTICE file
  74051. * distributed with this work for additional information
  74052. * regarding copyright ownership. The ASF licenses this file
  74053. * to you under the Apache License, Version 2.0 (the
  74054. * "License"); you may not use this file except in compliance
  74055. * with the License. You may obtain a copy of the License at
  74056. *
  74057. * http://www.apache.org/licenses/LICENSE-2.0
  74058. *
  74059. * Unless required by applicable law or agreed to in writing,
  74060. * software distributed under the License is distributed on an
  74061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74062. * KIND, either express or implied. See the License for the
  74063. * specific language governing permissions and limitations
  74064. * under the License.
  74065. */
  74066. function installScrollableLegendAction(registers) {
  74067. /**
  74068. * @event legendScroll
  74069. * @type {Object}
  74070. * @property {string} type 'legendScroll'
  74071. * @property {string} scrollDataIndex
  74072. */
  74073. registers.registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  74074. var scrollDataIndex = payload.scrollDataIndex;
  74075. scrollDataIndex != null && ecModel.eachComponent({
  74076. mainType: 'legend',
  74077. subType: 'scroll',
  74078. query: payload
  74079. }, function (legendModel) {
  74080. legendModel.setScrollDataIndex(scrollDataIndex);
  74081. });
  74082. });
  74083. }
  74084. function install$I(registers) {
  74085. use(install$H);
  74086. registers.registerComponentModel(ScrollableLegendModel);
  74087. registers.registerComponentView(ScrollableLegendView);
  74088. installScrollableLegendAction(registers);
  74089. }
  74090. function install$J(registers) {
  74091. use(install$H);
  74092. use(install$I);
  74093. }
  74094. var InsideZoomModel =
  74095. /** @class */
  74096. function (_super) {
  74097. __extends(InsideZoomModel, _super);
  74098. function InsideZoomModel() {
  74099. var _this = _super !== null && _super.apply(this, arguments) || this;
  74100. _this.type = InsideZoomModel.type;
  74101. return _this;
  74102. }
  74103. InsideZoomModel.type = 'dataZoom.inside';
  74104. InsideZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  74105. disabled: false,
  74106. zoomLock: false,
  74107. zoomOnMouseWheel: true,
  74108. moveOnMouseMove: true,
  74109. moveOnMouseWheel: false,
  74110. preventDefaultMouseMove: true
  74111. });
  74112. return InsideZoomModel;
  74113. }(DataZoomModel);
  74114. var inner$m = makeInner();
  74115. function setViewInfoToCoordSysRecord(api, dataZoomModel, getRange) {
  74116. inner$m(api).coordSysRecordMap.each(function (coordSysRecord) {
  74117. var dzInfo = coordSysRecord.dataZoomInfoMap.get(dataZoomModel.uid);
  74118. if (dzInfo) {
  74119. dzInfo.getRange = getRange;
  74120. }
  74121. });
  74122. }
  74123. function disposeCoordSysRecordIfNeeded(api, dataZoomModel) {
  74124. var coordSysRecordMap = inner$m(api).coordSysRecordMap;
  74125. var coordSysKeyArr = coordSysRecordMap.keys();
  74126. for (var i = 0; i < coordSysKeyArr.length; i++) {
  74127. var coordSysKey = coordSysKeyArr[i];
  74128. var coordSysRecord = coordSysRecordMap.get(coordSysKey);
  74129. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  74130. if (dataZoomInfoMap) {
  74131. var dzUid = dataZoomModel.uid;
  74132. var dzInfo = dataZoomInfoMap.get(dzUid);
  74133. if (dzInfo) {
  74134. dataZoomInfoMap.removeKey(dzUid);
  74135. if (!dataZoomInfoMap.keys().length) {
  74136. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  74137. }
  74138. }
  74139. }
  74140. }
  74141. }
  74142. function disposeCoordSysRecord(coordSysRecordMap, coordSysRecord) {
  74143. if (coordSysRecord) {
  74144. coordSysRecordMap.removeKey(coordSysRecord.model.uid);
  74145. var controller = coordSysRecord.controller;
  74146. controller && controller.dispose();
  74147. }
  74148. }
  74149. function createCoordSysRecord(api, coordSysModel) {
  74150. // These init props will never change after record created.
  74151. var coordSysRecord = {
  74152. model: coordSysModel,
  74153. containsPoint: curry(containsPoint, coordSysModel),
  74154. dispatchAction: curry(dispatchAction$1, api),
  74155. dataZoomInfoMap: null,
  74156. controller: null
  74157. }; // Must not do anything depends on coordSysRecord outside the event handler here,
  74158. // because coordSysRecord not completed yet.
  74159. var controller = coordSysRecord.controller = new RoamController(api.getZr());
  74160. each(['pan', 'zoom', 'scrollMove'], function (eventName) {
  74161. controller.on(eventName, function (event) {
  74162. var batch = [];
  74163. coordSysRecord.dataZoomInfoMap.each(function (dzInfo) {
  74164. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  74165. // moveOnMouseWheel, ...) enabled.
  74166. if (!event.isAvailableBehavior(dzInfo.model.option)) {
  74167. return;
  74168. }
  74169. var method = (dzInfo.getRange || {})[eventName];
  74170. var range = method && method(dzInfo.dzReferCoordSysInfo, coordSysRecord.model.mainType, coordSysRecord.controller, event);
  74171. !dzInfo.model.get('disabled', true) && range && batch.push({
  74172. dataZoomId: dzInfo.model.id,
  74173. start: range[0],
  74174. end: range[1]
  74175. });
  74176. });
  74177. batch.length && coordSysRecord.dispatchAction(batch);
  74178. });
  74179. });
  74180. return coordSysRecord;
  74181. }
  74182. /**
  74183. * This action will be throttled.
  74184. */
  74185. function dispatchAction$1(api, batch) {
  74186. api.dispatchAction({
  74187. type: 'dataZoom',
  74188. animation: {
  74189. easing: 'cubicOut',
  74190. duration: 100
  74191. },
  74192. batch: batch
  74193. });
  74194. }
  74195. function containsPoint(coordSysModel, e, x, y) {
  74196. return coordSysModel.coordinateSystem.containPoint([x, y]);
  74197. }
  74198. /**
  74199. * Merge roamController settings when multiple dataZooms share one roamController.
  74200. */
  74201. function mergeControllerParams(dataZoomInfoMap) {
  74202. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  74203. // as string, it is probably revert to reserved word by compress tool. See #7411.
  74204. var prefix = 'type_';
  74205. var typePriority = {
  74206. 'type_true': 2,
  74207. 'type_move': 1,
  74208. 'type_false': 0,
  74209. 'type_undefined': -1
  74210. };
  74211. var preventDefaultMouseMove = true;
  74212. dataZoomInfoMap.each(function (dataZoomInfo) {
  74213. var dataZoomModel = dataZoomInfo.model;
  74214. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  74215. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  74216. controlType = oneType;
  74217. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  74218. // users may be confused why it does not work when multiple insideZooms exist.
  74219. preventDefaultMouseMove = preventDefaultMouseMove && dataZoomModel.get('preventDefaultMouseMove', true);
  74220. });
  74221. return {
  74222. controlType: controlType,
  74223. opt: {
  74224. // RoamController will enable all of these functionalities,
  74225. // and the final behavior is determined by its event listener
  74226. // provided by each inside zoom.
  74227. zoomOnMouseWheel: true,
  74228. moveOnMouseMove: true,
  74229. moveOnMouseWheel: true,
  74230. preventDefaultMouseMove: !!preventDefaultMouseMove
  74231. }
  74232. };
  74233. }
  74234. function installDataZoomRoamProcessor(registers) {
  74235. registers.registerProcessor(registers.PRIORITY.PROCESSOR.FILTER, function (ecModel, api) {
  74236. var apiInner = inner$m(api);
  74237. var coordSysRecordMap = apiInner.coordSysRecordMap || (apiInner.coordSysRecordMap = createHashMap());
  74238. coordSysRecordMap.each(function (coordSysRecord) {
  74239. // `coordSysRecordMap` always exists (becuase it hold the `roam controller`, which should
  74240. // better not re-create each time), but clear `dataZoomInfoMap` each round of the workflow.
  74241. coordSysRecord.dataZoomInfoMap = null;
  74242. });
  74243. ecModel.eachComponent({
  74244. mainType: 'dataZoom',
  74245. subType: 'inside'
  74246. }, function (dataZoomModel) {
  74247. var dzReferCoordSysWrap = collectReferCoordSysModelInfo(dataZoomModel);
  74248. each(dzReferCoordSysWrap.infoList, function (dzCoordSysInfo) {
  74249. var coordSysUid = dzCoordSysInfo.model.uid;
  74250. var coordSysRecord = coordSysRecordMap.get(coordSysUid) || coordSysRecordMap.set(coordSysUid, createCoordSysRecord(api, dzCoordSysInfo.model));
  74251. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap || (coordSysRecord.dataZoomInfoMap = createHashMap()); // Notice these props might be changed each time for a single dataZoomModel.
  74252. dataZoomInfoMap.set(dataZoomModel.uid, {
  74253. dzReferCoordSysInfo: dzCoordSysInfo,
  74254. model: dataZoomModel,
  74255. getRange: null
  74256. });
  74257. });
  74258. }); // (1) Merge dataZoom settings for each coord sys and set to the roam controller.
  74259. // (2) Clear coord sys if not refered by any dataZoom.
  74260. coordSysRecordMap.each(function (coordSysRecord) {
  74261. var controller = coordSysRecord.controller;
  74262. var firstDzInfo;
  74263. var dataZoomInfoMap = coordSysRecord.dataZoomInfoMap;
  74264. if (dataZoomInfoMap) {
  74265. var firstDzKey = dataZoomInfoMap.keys()[0];
  74266. if (firstDzKey != null) {
  74267. firstDzInfo = dataZoomInfoMap.get(firstDzKey);
  74268. }
  74269. }
  74270. if (!firstDzInfo) {
  74271. disposeCoordSysRecord(coordSysRecordMap, coordSysRecord);
  74272. return;
  74273. }
  74274. var controllerParams = mergeControllerParams(dataZoomInfoMap);
  74275. controller.enable(controllerParams.controlType, controllerParams.opt);
  74276. controller.setPointerChecker(coordSysRecord.containsPoint);
  74277. createOrUpdate(coordSysRecord, 'dispatchAction', firstDzInfo.model.get('throttle', true), 'fixRate');
  74278. });
  74279. });
  74280. }
  74281. var InsideZoomView =
  74282. /** @class */
  74283. function (_super) {
  74284. __extends(InsideZoomView, _super);
  74285. function InsideZoomView() {
  74286. var _this = _super !== null && _super.apply(this, arguments) || this;
  74287. _this.type = 'dataZoom.inside';
  74288. return _this;
  74289. }
  74290. InsideZoomView.prototype.render = function (dataZoomModel, ecModel, api) {
  74291. _super.prototype.render.apply(this, arguments);
  74292. if (dataZoomModel.noTarget()) {
  74293. this._clear();
  74294. return;
  74295. } // Hence the `throttle` util ensures to preserve command order,
  74296. // here simply updating range all the time will not cause missing
  74297. // any of the the roam change.
  74298. this.range = dataZoomModel.getPercentRange(); // Reset controllers.
  74299. setViewInfoToCoordSysRecord(api, dataZoomModel, {
  74300. pan: bind(getRangeHandlers.pan, this),
  74301. zoom: bind(getRangeHandlers.zoom, this),
  74302. scrollMove: bind(getRangeHandlers.scrollMove, this)
  74303. });
  74304. };
  74305. InsideZoomView.prototype.dispose = function () {
  74306. this._clear();
  74307. _super.prototype.dispose.apply(this, arguments);
  74308. };
  74309. InsideZoomView.prototype._clear = function () {
  74310. disposeCoordSysRecordIfNeeded(this.api, this.dataZoomModel);
  74311. this.range = null;
  74312. };
  74313. InsideZoomView.type = 'dataZoom.inside';
  74314. return InsideZoomView;
  74315. }(DataZoomView);
  74316. var getRangeHandlers = {
  74317. zoom: function (coordSysInfo, coordSysMainType, controller, e) {
  74318. var lastRange = this.range;
  74319. var range = lastRange.slice(); // Calculate transform by the first axis.
  74320. var axisModel = coordSysInfo.axisModels[0];
  74321. if (!axisModel) {
  74322. return;
  74323. }
  74324. var directionInfo = getDirectionInfo[coordSysMainType](null, [e.originX, e.originY], axisModel, controller, coordSysInfo);
  74325. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  74326. var scale = Math.max(1 / e.scale, 0);
  74327. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  74328. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  74329. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  74330. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  74331. this.range = range;
  74332. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  74333. return range;
  74334. }
  74335. },
  74336. pan: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  74337. var directionInfo = getDirectionInfo[coordSysMainType]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordSysInfo);
  74338. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  74339. }),
  74340. scrollMove: makeMover(function (range, axisModel, coordSysInfo, coordSysMainType, controller, e) {
  74341. var directionInfo = getDirectionInfo[coordSysMainType]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordSysInfo);
  74342. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  74343. })
  74344. };
  74345. function makeMover(getPercentDelta) {
  74346. return function (coordSysInfo, coordSysMainType, controller, e) {
  74347. var lastRange = this.range;
  74348. var range = lastRange.slice(); // Calculate transform by the first axis.
  74349. var axisModel = coordSysInfo.axisModels[0];
  74350. if (!axisModel) {
  74351. return;
  74352. }
  74353. var percentDelta = getPercentDelta(range, axisModel, coordSysInfo, coordSysMainType, controller, e);
  74354. sliderMove(percentDelta, range, [0, 100], 'all');
  74355. this.range = range;
  74356. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  74357. return range;
  74358. }
  74359. };
  74360. }
  74361. var getDirectionInfo = {
  74362. grid: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  74363. var axis = axisModel.axis;
  74364. var ret = {};
  74365. var rect = coordSysInfo.model.coordinateSystem.getRect();
  74366. oldPoint = oldPoint || [0, 0];
  74367. if (axis.dim === 'x') {
  74368. ret.pixel = newPoint[0] - oldPoint[0];
  74369. ret.pixelLength = rect.width;
  74370. ret.pixelStart = rect.x;
  74371. ret.signal = axis.inverse ? 1 : -1;
  74372. } else {
  74373. // axis.dim === 'y'
  74374. ret.pixel = newPoint[1] - oldPoint[1];
  74375. ret.pixelLength = rect.height;
  74376. ret.pixelStart = rect.y;
  74377. ret.signal = axis.inverse ? -1 : 1;
  74378. }
  74379. return ret;
  74380. },
  74381. polar: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  74382. var axis = axisModel.axis;
  74383. var ret = {};
  74384. var polar = coordSysInfo.model.coordinateSystem;
  74385. var radiusExtent = polar.getRadiusAxis().getExtent();
  74386. var angleExtent = polar.getAngleAxis().getExtent();
  74387. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  74388. newPoint = polar.pointToCoord(newPoint);
  74389. if (axisModel.mainType === 'radiusAxis') {
  74390. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  74391. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  74392. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  74393. ret.pixelStart = radiusExtent[0];
  74394. ret.signal = axis.inverse ? 1 : -1;
  74395. } else {
  74396. // 'angleAxis'
  74397. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  74398. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  74399. ret.pixelLength = angleExtent[1] - angleExtent[0];
  74400. ret.pixelStart = angleExtent[0];
  74401. ret.signal = axis.inverse ? -1 : 1;
  74402. }
  74403. return ret;
  74404. },
  74405. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordSysInfo) {
  74406. var axis = axisModel.axis;
  74407. var rect = coordSysInfo.model.coordinateSystem.getRect();
  74408. var ret = {};
  74409. oldPoint = oldPoint || [0, 0];
  74410. if (axis.orient === 'horizontal') {
  74411. ret.pixel = newPoint[0] - oldPoint[0];
  74412. ret.pixelLength = rect.width;
  74413. ret.pixelStart = rect.x;
  74414. ret.signal = axis.inverse ? 1 : -1;
  74415. } else {
  74416. // 'vertical'
  74417. ret.pixel = newPoint[1] - oldPoint[1];
  74418. ret.pixelLength = rect.height;
  74419. ret.pixelStart = rect.y;
  74420. ret.signal = axis.inverse ? -1 : 1;
  74421. }
  74422. return ret;
  74423. }
  74424. };
  74425. function install$K(registers) {
  74426. installCommon(registers);
  74427. registers.registerComponentModel(InsideZoomModel);
  74428. registers.registerComponentView(InsideZoomView);
  74429. installDataZoomRoamProcessor(registers);
  74430. }
  74431. var SliderZoomModel =
  74432. /** @class */
  74433. function (_super) {
  74434. __extends(SliderZoomModel, _super);
  74435. function SliderZoomModel() {
  74436. var _this = _super !== null && _super.apply(this, arguments) || this;
  74437. _this.type = SliderZoomModel.type;
  74438. return _this;
  74439. }
  74440. SliderZoomModel.type = 'dataZoom.slider';
  74441. SliderZoomModel.layoutMode = 'box';
  74442. SliderZoomModel.defaultOption = inheritDefaultOption(DataZoomModel.defaultOption, {
  74443. show: true,
  74444. // deault value can only be drived in view stage.
  74445. right: 'ph',
  74446. top: 'ph',
  74447. width: 'ph',
  74448. height: 'ph',
  74449. left: null,
  74450. bottom: null,
  74451. borderColor: '#d2dbee',
  74452. borderRadius: 3,
  74453. backgroundColor: 'rgba(47,69,84,0)',
  74454. // dataBackgroundColor: '#ddd',
  74455. dataBackground: {
  74456. lineStyle: {
  74457. color: '#d2dbee',
  74458. width: 0.5
  74459. },
  74460. areaStyle: {
  74461. color: '#d2dbee',
  74462. opacity: 0.2
  74463. }
  74464. },
  74465. selectedDataBackground: {
  74466. lineStyle: {
  74467. color: '#8fb0f7',
  74468. width: 0.5
  74469. },
  74470. areaStyle: {
  74471. color: '#8fb0f7',
  74472. opacity: 0.2
  74473. }
  74474. },
  74475. // Color of selected window.
  74476. fillerColor: 'rgba(135,175,274,0.2)',
  74477. 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',
  74478. // Percent of the slider height
  74479. handleSize: '100%',
  74480. handleStyle: {
  74481. color: '#fff',
  74482. borderColor: '#ACB8D1'
  74483. },
  74484. moveHandleSize: 7,
  74485. 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',
  74486. moveHandleStyle: {
  74487. color: '#D2DBEE',
  74488. opacity: 0.7
  74489. },
  74490. showDetail: true,
  74491. showDataShadow: 'auto',
  74492. realtime: true,
  74493. zoomLock: false,
  74494. textStyle: {
  74495. color: '#6E7079'
  74496. },
  74497. brushSelect: true,
  74498. brushStyle: {
  74499. color: 'rgba(135,175,274,0.15)'
  74500. },
  74501. emphasis: {
  74502. handleStyle: {
  74503. borderColor: '#8FB0F7'
  74504. },
  74505. moveHandleStyle: {
  74506. color: '#8FB0F7'
  74507. }
  74508. }
  74509. });
  74510. return SliderZoomModel;
  74511. }(DataZoomModel);
  74512. var Rect$2 = Rect; // Constants
  74513. var DEFAULT_LOCATION_EDGE_GAP = 7;
  74514. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  74515. var DEFAULT_FILLER_SIZE = 30;
  74516. var DEFAULT_MOVE_HANDLE_SIZE = 7;
  74517. var HORIZONTAL = 'horizontal';
  74518. var VERTICAL = 'vertical';
  74519. var LABEL_GAP = 5;
  74520. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  74521. var REALTIME_ANIMATION_CONFIG = {
  74522. easing: 'cubicOut',
  74523. duration: 100
  74524. };
  74525. var SliderZoomView =
  74526. /** @class */
  74527. function (_super) {
  74528. __extends(SliderZoomView, _super);
  74529. function SliderZoomView() {
  74530. var _this = _super !== null && _super.apply(this, arguments) || this;
  74531. _this.type = SliderZoomView.type;
  74532. _this._displayables = {};
  74533. return _this;
  74534. }
  74535. SliderZoomView.prototype.init = function (ecModel, api) {
  74536. this.api = api; // A unique handler for each dataZoom component
  74537. this._onBrush = bind(this._onBrush, this);
  74538. this._onBrushEnd = bind(this._onBrushEnd, this);
  74539. };
  74540. SliderZoomView.prototype.render = function (dataZoomModel, ecModel, api, payload) {
  74541. _super.prototype.render.apply(this, arguments);
  74542. createOrUpdate(this, '_dispatchZoomAction', dataZoomModel.get('throttle'), 'fixRate');
  74543. this._orient = dataZoomModel.getOrient();
  74544. if (dataZoomModel.get('show') === false) {
  74545. this.group.removeAll();
  74546. return;
  74547. }
  74548. if (dataZoomModel.noTarget()) {
  74549. this._clear();
  74550. this.group.removeAll();
  74551. return;
  74552. } // Notice: this._resetInterval() should not be executed when payload.type
  74553. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  74554. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  74555. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  74556. this._buildView();
  74557. }
  74558. this._updateView();
  74559. };
  74560. SliderZoomView.prototype.dispose = function () {
  74561. this._clear();
  74562. _super.prototype.dispose.apply(this, arguments);
  74563. };
  74564. SliderZoomView.prototype._clear = function () {
  74565. clear(this, '_dispatchZoomAction');
  74566. var zr = this.api.getZr();
  74567. zr.off('mousemove', this._onBrush);
  74568. zr.off('mouseup', this._onBrushEnd);
  74569. };
  74570. SliderZoomView.prototype._buildView = function () {
  74571. var thisGroup = this.group;
  74572. thisGroup.removeAll();
  74573. this._brushing = false;
  74574. this._displayables.brushRect = null;
  74575. this._resetLocation();
  74576. this._resetInterval();
  74577. var barGroup = this._displayables.sliderGroup = new Group();
  74578. this._renderBackground();
  74579. this._renderHandle();
  74580. this._renderDataShadow();
  74581. thisGroup.add(barGroup);
  74582. this._positionGroup();
  74583. };
  74584. SliderZoomView.prototype._resetLocation = function () {
  74585. var dataZoomModel = this.dataZoomModel;
  74586. var api = this.api;
  74587. var showMoveHandle = dataZoomModel.get('brushSelect');
  74588. var moveHandleSize = showMoveHandle ? DEFAULT_MOVE_HANDLE_SIZE : 0; // If some of x/y/width/height are not specified,
  74589. // auto-adapt according to target grid.
  74590. var coordRect = this._findCoordRect();
  74591. var ecSize = {
  74592. width: api.getWidth(),
  74593. height: api.getHeight()
  74594. }; // Default align by coordinate system rect.
  74595. var positionInfo = this._orient === HORIZONTAL ? {
  74596. // Why using 'right', because right should be used in vertical,
  74597. // and it is better to be consistent for dealing with position param merge.
  74598. right: ecSize.width - coordRect.x - coordRect.width,
  74599. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP - moveHandleSize,
  74600. width: coordRect.width,
  74601. height: DEFAULT_FILLER_SIZE
  74602. } : {
  74603. right: DEFAULT_LOCATION_EDGE_GAP,
  74604. top: coordRect.y,
  74605. width: DEFAULT_FILLER_SIZE,
  74606. height: coordRect.height
  74607. }; // Do not write back to option and replace value 'ph', because
  74608. // the 'ph' value should be recalculated when resize.
  74609. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  74610. each(['right', 'top', 'width', 'height'], function (name) {
  74611. if (layoutParams[name] === 'ph') {
  74612. layoutParams[name] = positionInfo[name];
  74613. }
  74614. });
  74615. var layoutRect = getLayoutRect(layoutParams, ecSize);
  74616. this._location = {
  74617. x: layoutRect.x,
  74618. y: layoutRect.y
  74619. };
  74620. this._size = [layoutRect.width, layoutRect.height];
  74621. this._orient === VERTICAL && this._size.reverse();
  74622. };
  74623. SliderZoomView.prototype._positionGroup = function () {
  74624. var thisGroup = this.group;
  74625. var location = this._location;
  74626. var orient = this._orient; // Just use the first axis to determine mapping.
  74627. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  74628. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  74629. var sliderGroup = this._displayables.sliderGroup;
  74630. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  74631. sliderGroup.attr(orient === HORIZONTAL && !inverse ? {
  74632. scaleY: otherAxisInverse ? 1 : -1,
  74633. scaleX: 1
  74634. } : orient === HORIZONTAL && inverse ? {
  74635. scaleY: otherAxisInverse ? 1 : -1,
  74636. scaleX: -1
  74637. } : orient === VERTICAL && !inverse ? {
  74638. scaleY: otherAxisInverse ? -1 : 1,
  74639. scaleX: 1,
  74640. rotation: Math.PI / 2
  74641. } // Dont use Math.PI, considering shadow direction.
  74642. : {
  74643. scaleY: otherAxisInverse ? -1 : 1,
  74644. scaleX: -1,
  74645. rotation: Math.PI / 2
  74646. }); // Position barGroup
  74647. var rect = thisGroup.getBoundingRect([sliderGroup]);
  74648. thisGroup.x = location.x - rect.x;
  74649. thisGroup.y = location.y - rect.y;
  74650. thisGroup.markRedraw();
  74651. };
  74652. SliderZoomView.prototype._getViewExtent = function () {
  74653. return [0, this._size[0]];
  74654. };
  74655. SliderZoomView.prototype._renderBackground = function () {
  74656. var dataZoomModel = this.dataZoomModel;
  74657. var size = this._size;
  74658. var barGroup = this._displayables.sliderGroup;
  74659. var brushSelect = dataZoomModel.get('brushSelect');
  74660. barGroup.add(new Rect$2({
  74661. silent: true,
  74662. shape: {
  74663. x: 0,
  74664. y: 0,
  74665. width: size[0],
  74666. height: size[1]
  74667. },
  74668. style: {
  74669. fill: dataZoomModel.get('backgroundColor')
  74670. },
  74671. z2: -40
  74672. })); // Click panel, over shadow, below handles.
  74673. var clickPanel = new Rect$2({
  74674. shape: {
  74675. x: 0,
  74676. y: 0,
  74677. width: size[0],
  74678. height: size[1]
  74679. },
  74680. style: {
  74681. fill: 'transparent'
  74682. },
  74683. z2: 0,
  74684. onclick: bind(this._onClickPanel, this)
  74685. });
  74686. var zr = this.api.getZr();
  74687. if (brushSelect) {
  74688. clickPanel.on('mousedown', this._onBrushStart, this);
  74689. clickPanel.cursor = 'crosshair';
  74690. zr.on('mousemove', this._onBrush);
  74691. zr.on('mouseup', this._onBrushEnd);
  74692. } else {
  74693. zr.off('mousemove', this._onBrush);
  74694. zr.off('mouseup', this._onBrushEnd);
  74695. }
  74696. barGroup.add(clickPanel);
  74697. };
  74698. SliderZoomView.prototype._renderDataShadow = function () {
  74699. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  74700. this._displayables.dataShadowSegs = [];
  74701. if (!info) {
  74702. return;
  74703. }
  74704. var size = this._size;
  74705. var seriesModel = info.series;
  74706. var data = seriesModel.getRawData();
  74707. var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
  74708. : info.otherDim;
  74709. if (otherDim == null) {
  74710. return;
  74711. }
  74712. var otherDataExtent = data.getDataExtent(otherDim); // Nice extent.
  74713. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  74714. otherDataExtent = [otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset];
  74715. var otherShadowExtent = [0, size[1]];
  74716. var thisShadowExtent = [0, size[0]];
  74717. var areaPoints = [[size[0], 0], [0, 0]];
  74718. var linePoints = [];
  74719. var step = thisShadowExtent[1] / (data.count() - 1);
  74720. var thisCoord = 0; // Optimize for large data shadow
  74721. var stride = Math.round(data.count() / size[0]);
  74722. var lastIsEmpty;
  74723. data.each([otherDim], function (value, index) {
  74724. if (stride > 0 && index % stride) {
  74725. thisCoord += step;
  74726. return;
  74727. } // FIXME
  74728. // Should consider axis.min/axis.max when drawing dataShadow.
  74729. // FIXME
  74730. // 应该使用统一的空判断?还是在list里进行空判断?
  74731. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  74732. var otherCoord = isEmpty ? 0 : linearMap(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value.
  74733. if (isEmpty && !lastIsEmpty && index) {
  74734. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  74735. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  74736. } else if (!isEmpty && lastIsEmpty) {
  74737. areaPoints.push([thisCoord, 0]);
  74738. linePoints.push([thisCoord, 0]);
  74739. }
  74740. areaPoints.push([thisCoord, otherCoord]);
  74741. linePoints.push([thisCoord, otherCoord]);
  74742. thisCoord += step;
  74743. lastIsEmpty = isEmpty;
  74744. });
  74745. var dataZoomModel = this.dataZoomModel;
  74746. function createDataShadowGroup(isSelectedArea) {
  74747. var model = dataZoomModel.getModel(isSelectedArea ? 'selectedDataBackground' : 'dataBackground');
  74748. var group = new Group();
  74749. var polygon = new Polygon({
  74750. shape: {
  74751. points: areaPoints
  74752. },
  74753. segmentIgnoreThreshold: 1,
  74754. style: model.getModel('areaStyle').getAreaStyle(),
  74755. silent: true,
  74756. z2: -20
  74757. });
  74758. var polyline = new Polyline({
  74759. shape: {
  74760. points: linePoints
  74761. },
  74762. segmentIgnoreThreshold: 1,
  74763. style: model.getModel('lineStyle').getLineStyle(),
  74764. silent: true,
  74765. z2: -19
  74766. });
  74767. group.add(polygon);
  74768. group.add(polyline);
  74769. return group;
  74770. } // let dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  74771. for (var i = 0; i < 3; i++) {
  74772. var group = createDataShadowGroup(i === 1);
  74773. this._displayables.sliderGroup.add(group);
  74774. this._displayables.dataShadowSegs.push(group);
  74775. }
  74776. };
  74777. SliderZoomView.prototype._prepareDataShadowInfo = function () {
  74778. var dataZoomModel = this.dataZoomModel;
  74779. var showDataShadow = dataZoomModel.get('showDataShadow');
  74780. if (showDataShadow === false) {
  74781. return;
  74782. } // Find a representative series.
  74783. var result;
  74784. var ecModel = this.ecModel;
  74785. dataZoomModel.eachTargetAxis(function (axisDim, axisIndex) {
  74786. var seriesModels = dataZoomModel.getAxisProxy(axisDim, axisIndex).getTargetSeriesModels();
  74787. each(seriesModels, function (seriesModel) {
  74788. if (result) {
  74789. return;
  74790. }
  74791. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  74792. return;
  74793. }
  74794. var thisAxis = ecModel.getComponent(getAxisMainType(axisDim), axisIndex).axis;
  74795. var otherDim = getOtherDim(axisDim);
  74796. var otherAxisInverse;
  74797. var coordSys = seriesModel.coordinateSystem;
  74798. if (otherDim != null && coordSys.getOtherAxis) {
  74799. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  74800. }
  74801. otherDim = seriesModel.getData().mapDimension(otherDim);
  74802. result = {
  74803. thisAxis: thisAxis,
  74804. series: seriesModel,
  74805. thisDim: axisDim,
  74806. otherDim: otherDim,
  74807. otherAxisInverse: otherAxisInverse
  74808. };
  74809. }, this);
  74810. }, this);
  74811. return result;
  74812. };
  74813. SliderZoomView.prototype._renderHandle = function () {
  74814. var thisGroup = this.group;
  74815. var displayables = this._displayables;
  74816. var handles = displayables.handles = [null, null];
  74817. var handleLabels = displayables.handleLabels = [null, null];
  74818. var sliderGroup = this._displayables.sliderGroup;
  74819. var size = this._size;
  74820. var dataZoomModel = this.dataZoomModel;
  74821. var api = this.api;
  74822. var borderRadius = dataZoomModel.get('borderRadius') || 0;
  74823. var brushSelect = dataZoomModel.get('brushSelect');
  74824. var filler = displayables.filler = new Rect$2({
  74825. silent: brushSelect,
  74826. style: {
  74827. fill: dataZoomModel.get('fillerColor')
  74828. },
  74829. textConfig: {
  74830. position: 'inside'
  74831. }
  74832. });
  74833. sliderGroup.add(filler); // Frame border.
  74834. sliderGroup.add(new Rect$2({
  74835. silent: true,
  74836. subPixelOptimize: true,
  74837. shape: {
  74838. x: 0,
  74839. y: 0,
  74840. width: size[0],
  74841. height: size[1],
  74842. r: borderRadius
  74843. },
  74844. style: {
  74845. stroke: dataZoomModel.get('dataBackgroundColor') // deprecated option
  74846. || dataZoomModel.get('borderColor'),
  74847. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  74848. fill: 'rgba(0,0,0,0)'
  74849. }
  74850. })); // Left and right handle to resize
  74851. each([0, 1], function (handleIndex) {
  74852. var iconStr = dataZoomModel.get('handleIcon');
  74853. if (!symbolBuildProxies[iconStr] && iconStr.indexOf('path://') < 0 && iconStr.indexOf('image://') < 0) {
  74854. // Compatitable with the old icon parsers. Which can use a path string without path://
  74855. iconStr = 'path://' + iconStr;
  74856. if ("development" !== 'production') {
  74857. deprecateLog('handleIcon now needs \'path://\' prefix when using a path string');
  74858. }
  74859. }
  74860. var path = createSymbol(iconStr, -1, 0, 2, 2, null, true);
  74861. path.attr({
  74862. cursor: getCursor(this._orient),
  74863. draggable: true,
  74864. drift: bind(this._onDragMove, this, handleIndex),
  74865. ondragend: bind(this._onDragEnd, this),
  74866. onmouseover: bind(this._showDataInfo, this, true),
  74867. onmouseout: bind(this._showDataInfo, this, false),
  74868. z2: 5
  74869. });
  74870. var bRect = path.getBoundingRect();
  74871. var handleSize = dataZoomModel.get('handleSize');
  74872. this._handleHeight = parsePercent$1(handleSize, this._size[1]);
  74873. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  74874. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  74875. path.style.strokeNoScale = true;
  74876. path.rectHover = true;
  74877. path.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  74878. enableHoverEmphasis(path);
  74879. var handleColor = dataZoomModel.get('handleColor'); // deprecated option
  74880. // Compatitable with previous version
  74881. if (handleColor != null) {
  74882. path.style.fill = handleColor;
  74883. }
  74884. sliderGroup.add(handles[handleIndex] = path);
  74885. var textStyleModel = dataZoomModel.getModel('textStyle');
  74886. thisGroup.add(handleLabels[handleIndex] = new ZRText({
  74887. silent: true,
  74888. invisible: true,
  74889. style: {
  74890. x: 0,
  74891. y: 0,
  74892. text: '',
  74893. verticalAlign: 'middle',
  74894. align: 'center',
  74895. fill: textStyleModel.getTextColor(),
  74896. font: textStyleModel.getFont()
  74897. },
  74898. z2: 10
  74899. }));
  74900. }, this); // Handle to move. Only visible when brushSelect is set true.
  74901. var actualMoveZone = filler;
  74902. if (brushSelect) {
  74903. var moveHandleHeight = parsePercent$1(dataZoomModel.get('moveHandleSize'), size[1]);
  74904. var moveHandle_1 = displayables.moveHandle = new Rect({
  74905. style: dataZoomModel.getModel('moveHandleStyle').getItemStyle(),
  74906. silent: true,
  74907. shape: {
  74908. r: [0, 0, 2, 2],
  74909. y: size[1] - 0.5,
  74910. height: moveHandleHeight
  74911. }
  74912. });
  74913. var iconSize = moveHandleHeight * 0.8;
  74914. var moveHandleIcon = displayables.moveHandleIcon = createSymbol(dataZoomModel.get('moveHandleIcon'), -iconSize / 2, -iconSize / 2, iconSize, iconSize, '#fff', true);
  74915. moveHandleIcon.silent = true;
  74916. moveHandleIcon.y = size[1] + moveHandleHeight / 2 - 0.5;
  74917. moveHandle_1.ensureState('emphasis').style = dataZoomModel.getModel(['emphasis', 'moveHandleStyle']).getItemStyle();
  74918. var moveZoneExpandSize = Math.min(size[1] / 2, Math.max(moveHandleHeight, 10));
  74919. actualMoveZone = displayables.moveZone = new Rect({
  74920. invisible: true,
  74921. shape: {
  74922. y: size[1] - moveZoneExpandSize,
  74923. height: moveHandleHeight + moveZoneExpandSize
  74924. }
  74925. });
  74926. actualMoveZone.on('mouseover', function () {
  74927. api.enterEmphasis(moveHandle_1);
  74928. }).on('mouseout', function () {
  74929. api.leaveEmphasis(moveHandle_1);
  74930. });
  74931. sliderGroup.add(moveHandle_1);
  74932. sliderGroup.add(moveHandleIcon);
  74933. sliderGroup.add(actualMoveZone);
  74934. }
  74935. actualMoveZone.attr({
  74936. draggable: true,
  74937. cursor: getCursor(this._orient),
  74938. drift: bind(this._onDragMove, this, 'all'),
  74939. ondragstart: bind(this._showDataInfo, this, true),
  74940. ondragend: bind(this._onDragEnd, this),
  74941. onmouseover: bind(this._showDataInfo, this, true),
  74942. onmouseout: bind(this._showDataInfo, this, false)
  74943. });
  74944. };
  74945. SliderZoomView.prototype._resetInterval = function () {
  74946. var range = this._range = this.dataZoomModel.getPercentRange();
  74947. var viewExtent = this._getViewExtent();
  74948. this._handleEnds = [linearMap(range[0], [0, 100], viewExtent, true), linearMap(range[1], [0, 100], viewExtent, true)];
  74949. };
  74950. SliderZoomView.prototype._updateInterval = function (handleIndex, delta) {
  74951. var dataZoomModel = this.dataZoomModel;
  74952. var handleEnds = this._handleEnds;
  74953. var viewExtend = this._getViewExtent();
  74954. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  74955. var percentExtent = [0, 100];
  74956. 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);
  74957. var lastRange = this._range;
  74958. var range = this._range = asc([linearMap(handleEnds[0], viewExtend, percentExtent, true), linearMap(handleEnds[1], viewExtend, percentExtent, true)]);
  74959. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  74960. };
  74961. SliderZoomView.prototype._updateView = function (nonRealtime) {
  74962. var displaybles = this._displayables;
  74963. var handleEnds = this._handleEnds;
  74964. var handleInterval = asc(handleEnds.slice());
  74965. var size = this._size;
  74966. each([0, 1], function (handleIndex) {
  74967. // Handles
  74968. var handle = displaybles.handles[handleIndex];
  74969. var handleHeight = this._handleHeight;
  74970. handle.attr({
  74971. scaleX: handleHeight / 2,
  74972. scaleY: handleHeight / 2,
  74973. // This is a trick, by adding an extra tiny offset to let the default handle's end point align to the drag window.
  74974. // NOTE: It may affect some custom shapes a bit. But we prefer to have better result by default.
  74975. x: handleEnds[handleIndex] + (handleIndex ? -1 : 1),
  74976. y: size[1] / 2 - handleHeight / 2
  74977. });
  74978. }, this); // Filler
  74979. displaybles.filler.setShape({
  74980. x: handleInterval[0],
  74981. y: 0,
  74982. width: handleInterval[1] - handleInterval[0],
  74983. height: size[1]
  74984. });
  74985. var viewExtent = {
  74986. x: handleInterval[0],
  74987. width: handleInterval[1] - handleInterval[0]
  74988. }; // Move handle
  74989. if (displaybles.moveHandle) {
  74990. displaybles.moveHandle.setShape(viewExtent);
  74991. displaybles.moveZone.setShape(viewExtent); // Force update path on the invisible object
  74992. displaybles.moveZone.getBoundingRect();
  74993. displaybles.moveHandleIcon && displaybles.moveHandleIcon.attr('x', viewExtent.x + viewExtent.width / 2);
  74994. } // update clip path of shadow.
  74995. var dataShadowSegs = displaybles.dataShadowSegs;
  74996. var segIntervals = [0, handleInterval[0], handleInterval[1], size[0]];
  74997. for (var i = 0; i < dataShadowSegs.length; i++) {
  74998. var segGroup = dataShadowSegs[i];
  74999. var clipPath = segGroup.getClipPath();
  75000. if (!clipPath) {
  75001. clipPath = new Rect();
  75002. segGroup.setClipPath(clipPath);
  75003. }
  75004. clipPath.setShape({
  75005. x: segIntervals[i],
  75006. y: 0,
  75007. width: segIntervals[i + 1] - segIntervals[i],
  75008. height: size[1]
  75009. });
  75010. }
  75011. this._updateDataInfo(nonRealtime);
  75012. };
  75013. SliderZoomView.prototype._updateDataInfo = function (nonRealtime) {
  75014. var dataZoomModel = this.dataZoomModel;
  75015. var displaybles = this._displayables;
  75016. var handleLabels = displaybles.handleLabels;
  75017. var orient = this._orient;
  75018. var labelTexts = ['', '']; // FIXME
  75019. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  75020. if (dataZoomModel.get('showDetail')) {
  75021. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  75022. if (axisProxy) {
  75023. var axis = axisProxy.getAxisModel().axis;
  75024. var range = this._range;
  75025. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  75026. ? axisProxy.calculateDataWindow({
  75027. start: range[0],
  75028. end: range[1]
  75029. }).valueWindow : axisProxy.getDataValueWindow();
  75030. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  75031. }
  75032. }
  75033. var orderedHandleEnds = asc(this._handleEnds.slice());
  75034. setLabel.call(this, 0);
  75035. setLabel.call(this, 1);
  75036. function setLabel(handleIndex) {
  75037. // Label
  75038. // Text should not transform by barGroup.
  75039. // Ignore handlers transform
  75040. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  75041. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  75042. var offset = this._handleWidth / 2 + LABEL_GAP;
  75043. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  75044. handleLabels[handleIndex].setStyle({
  75045. x: textPoint[0],
  75046. y: textPoint[1],
  75047. verticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  75048. align: orient === HORIZONTAL ? direction : 'center',
  75049. text: labelTexts[handleIndex]
  75050. });
  75051. }
  75052. };
  75053. SliderZoomView.prototype._formatLabel = function (value, axis) {
  75054. var dataZoomModel = this.dataZoomModel;
  75055. var labelFormatter = dataZoomModel.get('labelFormatter');
  75056. var labelPrecision = dataZoomModel.get('labelPrecision');
  75057. if (labelPrecision == null || labelPrecision === 'auto') {
  75058. labelPrecision = axis.getPixelPrecision();
  75059. }
  75060. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  75061. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel({
  75062. value: Math.round(value)
  75063. }) // param of toFixed should less then 20.
  75064. : value.toFixed(Math.min(labelPrecision, 20));
  75065. return isFunction(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  75066. };
  75067. /**
  75068. * @param showOrHide true: show, false: hide
  75069. */
  75070. SliderZoomView.prototype._showDataInfo = function (showOrHide) {
  75071. // Always show when drgging.
  75072. showOrHide = this._dragging || showOrHide;
  75073. var displayables = this._displayables;
  75074. var handleLabels = displayables.handleLabels;
  75075. handleLabels[0].attr('invisible', !showOrHide);
  75076. handleLabels[1].attr('invisible', !showOrHide); // Highlight move handle
  75077. displayables.moveHandle && this.api[showOrHide ? 'enterEmphasis' : 'leaveEmphasis'](displayables.moveHandle, 1);
  75078. };
  75079. SliderZoomView.prototype._onDragMove = function (handleIndex, dx, dy, event) {
  75080. this._dragging = true; // For mobile device, prevent screen slider on the button.
  75081. stop(event.event); // Transform dx, dy to bar coordination.
  75082. var barTransform = this._displayables.sliderGroup.getLocalTransform();
  75083. var vertex = applyTransform$1([dx, dy], barTransform, true);
  75084. var changed = this._updateInterval(handleIndex, vertex[0]);
  75085. var realtime = this.dataZoomModel.get('realtime');
  75086. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  75087. // which cause bad visual effect when progressive enabled.
  75088. changed && realtime && this._dispatchZoomAction(true);
  75089. };
  75090. SliderZoomView.prototype._onDragEnd = function () {
  75091. this._dragging = false;
  75092. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  75093. // drag end will cause the whole view rerender, which is unnecessary.
  75094. var realtime = this.dataZoomModel.get('realtime');
  75095. !realtime && this._dispatchZoomAction(false);
  75096. };
  75097. SliderZoomView.prototype._onClickPanel = function (e) {
  75098. var size = this._size;
  75099. var localPoint = this._displayables.sliderGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  75100. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  75101. return;
  75102. }
  75103. var handleEnds = this._handleEnds;
  75104. var center = (handleEnds[0] + handleEnds[1]) / 2;
  75105. var changed = this._updateInterval('all', localPoint[0] - center);
  75106. this._updateView();
  75107. changed && this._dispatchZoomAction(false);
  75108. };
  75109. SliderZoomView.prototype._onBrushStart = function (e) {
  75110. var x = e.offsetX;
  75111. var y = e.offsetY;
  75112. this._brushStart = new Point(x, y);
  75113. this._brushing = true;
  75114. this._brushStartTime = +new Date(); // this._updateBrushRect(x, y);
  75115. };
  75116. SliderZoomView.prototype._onBrushEnd = function (e) {
  75117. if (!this._brushing) {
  75118. return;
  75119. }
  75120. var brushRect = this._displayables.brushRect;
  75121. this._brushing = false;
  75122. if (!brushRect) {
  75123. return;
  75124. }
  75125. brushRect.attr('ignore', true);
  75126. var brushShape = brushRect.shape;
  75127. var brushEndTime = +new Date(); // console.log(brushEndTime - this._brushStartTime);
  75128. if (brushEndTime - this._brushStartTime < 200 && Math.abs(brushShape.width) < 5) {
  75129. // Will treat it as a click
  75130. return;
  75131. }
  75132. var viewExtend = this._getViewExtent();
  75133. var percentExtent = [0, 100];
  75134. this._range = asc([linearMap(brushShape.x, viewExtend, percentExtent, true), linearMap(brushShape.x + brushShape.width, viewExtend, percentExtent, true)]);
  75135. this._handleEnds = [brushShape.x, brushShape.x + brushShape.width];
  75136. this._updateView();
  75137. this._dispatchZoomAction(false);
  75138. };
  75139. SliderZoomView.prototype._onBrush = function (e) {
  75140. if (this._brushing) {
  75141. // For mobile device, prevent screen slider on the button.
  75142. stop(e.event);
  75143. this._updateBrushRect(e.offsetX, e.offsetY);
  75144. }
  75145. };
  75146. SliderZoomView.prototype._updateBrushRect = function (mouseX, mouseY) {
  75147. var displayables = this._displayables;
  75148. var dataZoomModel = this.dataZoomModel;
  75149. var brushRect = displayables.brushRect;
  75150. if (!brushRect) {
  75151. brushRect = displayables.brushRect = new Rect$2({
  75152. silent: true,
  75153. style: dataZoomModel.getModel('brushStyle').getItemStyle()
  75154. });
  75155. displayables.sliderGroup.add(brushRect);
  75156. }
  75157. brushRect.attr('ignore', false);
  75158. var brushStart = this._brushStart;
  75159. var sliderGroup = this._displayables.sliderGroup;
  75160. var endPoint = sliderGroup.transformCoordToLocal(mouseX, mouseY);
  75161. var startPoint = sliderGroup.transformCoordToLocal(brushStart.x, brushStart.y);
  75162. var size = this._size;
  75163. endPoint[0] = Math.max(Math.min(size[0], endPoint[0]), 0);
  75164. brushRect.setShape({
  75165. x: startPoint[0],
  75166. y: 0,
  75167. width: endPoint[0] - startPoint[0],
  75168. height: size[1]
  75169. });
  75170. };
  75171. /**
  75172. * This action will be throttled.
  75173. */
  75174. SliderZoomView.prototype._dispatchZoomAction = function (realtime) {
  75175. var range = this._range;
  75176. this.api.dispatchAction({
  75177. type: 'dataZoom',
  75178. from: this.uid,
  75179. dataZoomId: this.dataZoomModel.id,
  75180. animation: realtime ? REALTIME_ANIMATION_CONFIG : null,
  75181. start: range[0],
  75182. end: range[1]
  75183. });
  75184. };
  75185. SliderZoomView.prototype._findCoordRect = function () {
  75186. // Find the grid coresponding to the first axis referred by dataZoom.
  75187. var rect;
  75188. var coordSysInfoList = collectReferCoordSysModelInfo(this.dataZoomModel).infoList;
  75189. if (!rect && coordSysInfoList.length) {
  75190. var coordSys = coordSysInfoList[0].model.coordinateSystem;
  75191. rect = coordSys.getRect && coordSys.getRect();
  75192. }
  75193. if (!rect) {
  75194. var width = this.api.getWidth();
  75195. var height = this.api.getHeight();
  75196. rect = {
  75197. x: width * 0.2,
  75198. y: height * 0.2,
  75199. width: width * 0.6,
  75200. height: height * 0.6
  75201. };
  75202. }
  75203. return rect;
  75204. };
  75205. SliderZoomView.type = 'dataZoom.slider';
  75206. return SliderZoomView;
  75207. }(DataZoomView);
  75208. function getOtherDim(thisDim) {
  75209. // FIXME
  75210. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  75211. var map = {
  75212. x: 'y',
  75213. y: 'x',
  75214. radius: 'angle',
  75215. angle: 'radius'
  75216. };
  75217. return map[thisDim];
  75218. }
  75219. function getCursor(orient) {
  75220. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  75221. }
  75222. function install$L(registers) {
  75223. registers.registerComponentModel(SliderZoomModel);
  75224. registers.registerComponentView(SliderZoomView);
  75225. installCommon(registers);
  75226. }
  75227. function install$M(registers) {
  75228. use(install$K);
  75229. use(install$L); // Do not install './dataZoomSelect',
  75230. // since it only work for toolbox dataZoom.
  75231. }
  75232. var visualDefault = {
  75233. /**
  75234. * @public
  75235. */
  75236. get: function (visualType, key, isCategory) {
  75237. var value = clone((defaultOption$1[visualType] || {})[key]);
  75238. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  75239. }
  75240. };
  75241. var defaultOption$1 = {
  75242. color: {
  75243. active: ['#006edd', '#e0ffff'],
  75244. inactive: ['rgba(0,0,0,0)']
  75245. },
  75246. colorHue: {
  75247. active: [0, 360],
  75248. inactive: [0, 0]
  75249. },
  75250. colorSaturation: {
  75251. active: [0.3, 1],
  75252. inactive: [0, 0]
  75253. },
  75254. colorLightness: {
  75255. active: [0.9, 0.5],
  75256. inactive: [0, 0]
  75257. },
  75258. colorAlpha: {
  75259. active: [0.3, 1],
  75260. inactive: [0, 0]
  75261. },
  75262. opacity: {
  75263. active: [0.3, 1],
  75264. inactive: [0, 0]
  75265. },
  75266. symbol: {
  75267. active: ['circle', 'roundRect', 'diamond'],
  75268. inactive: ['none']
  75269. },
  75270. symbolSize: {
  75271. active: [10, 50],
  75272. inactive: [0, 0]
  75273. }
  75274. };
  75275. var mapVisual$1 = VisualMapping.mapVisual;
  75276. var eachVisual = VisualMapping.eachVisual;
  75277. var isArray$1 = isArray;
  75278. var each$f = each;
  75279. var asc$2 = asc;
  75280. var linearMap$1 = linearMap;
  75281. var VisualMapModel =
  75282. /** @class */
  75283. function (_super) {
  75284. __extends(VisualMapModel, _super);
  75285. function VisualMapModel() {
  75286. var _this = _super !== null && _super.apply(this, arguments) || this;
  75287. _this.type = VisualMapModel.type;
  75288. _this.stateList = ['inRange', 'outOfRange'];
  75289. _this.replacableOptionKeys = ['inRange', 'outOfRange', 'target', 'controller', 'color'];
  75290. _this.layoutMode = {
  75291. type: 'box',
  75292. ignoreSize: true
  75293. };
  75294. /**
  75295. * [lowerBound, upperBound]
  75296. */
  75297. _this.dataBound = [-Infinity, Infinity];
  75298. _this.targetVisuals = {};
  75299. _this.controllerVisuals = {};
  75300. return _this;
  75301. }
  75302. VisualMapModel.prototype.init = function (option, parentModel, ecModel) {
  75303. this.mergeDefaultAndTheme(option, ecModel);
  75304. };
  75305. /**
  75306. * @protected
  75307. */
  75308. VisualMapModel.prototype.optionUpdated = function (newOption, isInit) {
  75309. var thisOption = this.option; // FIXME
  75310. // necessary?
  75311. // Disable realtime view update if canvas is not supported.
  75312. if (!env.canvasSupported) {
  75313. thisOption.realtime = false;
  75314. }
  75315. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  75316. this.textStyleModel = this.getModel('textStyle');
  75317. this.resetItemSize();
  75318. this.completeVisualOption();
  75319. };
  75320. /**
  75321. * @protected
  75322. */
  75323. VisualMapModel.prototype.resetVisual = function (supplementVisualOption) {
  75324. var stateList = this.stateList;
  75325. supplementVisualOption = bind(supplementVisualOption, this);
  75326. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  75327. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  75328. };
  75329. /**
  75330. * @protected
  75331. * @return {Array.<number>} An array of series indices.
  75332. */
  75333. VisualMapModel.prototype.getTargetSeriesIndices = function () {
  75334. var optionSeriesIndex = this.option.seriesIndex;
  75335. var seriesIndices = [];
  75336. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  75337. this.ecModel.eachSeries(function (seriesModel, index) {
  75338. seriesIndices.push(index);
  75339. });
  75340. } else {
  75341. seriesIndices = normalizeToArray(optionSeriesIndex);
  75342. }
  75343. return seriesIndices;
  75344. };
  75345. /**
  75346. * @public
  75347. */
  75348. VisualMapModel.prototype.eachTargetSeries = function (callback, context) {
  75349. each(this.getTargetSeriesIndices(), function (seriesIndex) {
  75350. var seriesModel = this.ecModel.getSeriesByIndex(seriesIndex);
  75351. if (seriesModel) {
  75352. callback.call(context, seriesModel);
  75353. }
  75354. }, this);
  75355. };
  75356. /**
  75357. * @pubilc
  75358. */
  75359. VisualMapModel.prototype.isTargetSeries = function (seriesModel) {
  75360. var is = false;
  75361. this.eachTargetSeries(function (model) {
  75362. model === seriesModel && (is = true);
  75363. });
  75364. return is;
  75365. };
  75366. /**
  75367. * @example
  75368. * this.formatValueText(someVal); // format single numeric value to text.
  75369. * this.formatValueText(someVal, true); // format single category value to text.
  75370. * this.formatValueText([min, max]); // format numeric min-max to text.
  75371. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  75372. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  75373. *
  75374. * @param value Real value, or this.dataBound[0 or 1].
  75375. * @param isCategory Only available when value is number.
  75376. * @param edgeSymbols Open-close symbol when value is interval.
  75377. * @protected
  75378. */
  75379. VisualMapModel.prototype.formatValueText = function (value, isCategory, edgeSymbols) {
  75380. var option = this.option;
  75381. var precision = option.precision;
  75382. var dataBound = this.dataBound;
  75383. var formatter = option.formatter;
  75384. var isMinMax;
  75385. edgeSymbols = edgeSymbols || ['<', '>'];
  75386. if (isArray(value)) {
  75387. value = value.slice();
  75388. isMinMax = true;
  75389. }
  75390. var textValue = isCategory ? value // Value is string when isCategory
  75391. : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  75392. if (isString(formatter)) {
  75393. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  75394. } else if (isFunction(formatter)) {
  75395. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  75396. }
  75397. if (isMinMax) {
  75398. if (value[0] === dataBound[0]) {
  75399. return edgeSymbols[0] + ' ' + textValue[1];
  75400. } else if (value[1] === dataBound[1]) {
  75401. return edgeSymbols[1] + ' ' + textValue[0];
  75402. } else {
  75403. return textValue[0] + ' - ' + textValue[1];
  75404. }
  75405. } else {
  75406. // Format single value (includes category case).
  75407. return textValue;
  75408. }
  75409. function toFixed(val) {
  75410. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  75411. }
  75412. };
  75413. /**
  75414. * @protected
  75415. */
  75416. VisualMapModel.prototype.resetExtent = function () {
  75417. var thisOption = this.option; // Can not calculate data extent by data here.
  75418. // Because series and data may be modified in processing stage.
  75419. // So we do not support the feature "auto min/max".
  75420. var extent = asc$2([thisOption.min, thisOption.max]);
  75421. this._dataExtent = extent;
  75422. };
  75423. /**
  75424. * Return Concrete dimention. If return null/undefined, no dimension used.
  75425. */
  75426. VisualMapModel.prototype.getDataDimension = function (list) {
  75427. var optDim = this.option.dimension;
  75428. var listDimensions = list.dimensions;
  75429. if (optDim == null && !listDimensions.length) {
  75430. return;
  75431. }
  75432. if (optDim != null) {
  75433. return list.getDimension(optDim);
  75434. }
  75435. var dimNames = list.dimensions;
  75436. for (var i = dimNames.length - 1; i >= 0; i--) {
  75437. var dimName = dimNames[i];
  75438. var dimInfo = list.getDimensionInfo(dimName);
  75439. if (!dimInfo.isCalculationCoord) {
  75440. return dimName;
  75441. }
  75442. }
  75443. };
  75444. VisualMapModel.prototype.getExtent = function () {
  75445. return this._dataExtent.slice();
  75446. };
  75447. VisualMapModel.prototype.completeVisualOption = function () {
  75448. var ecModel = this.ecModel;
  75449. var thisOption = this.option;
  75450. var base = {
  75451. inRange: thisOption.inRange,
  75452. outOfRange: thisOption.outOfRange
  75453. };
  75454. var target = thisOption.target || (thisOption.target = {});
  75455. var controller = thisOption.controller || (thisOption.controller = {});
  75456. merge(target, base); // Do not override
  75457. merge(controller, base); // Do not override
  75458. var isCategory = this.isCategory();
  75459. completeSingle.call(this, target);
  75460. completeSingle.call(this, controller);
  75461. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  75462. completeController.call(this, controller);
  75463. function completeSingle(base) {
  75464. // Compatible with ec2 dataRange.color.
  75465. // The mapping order of dataRange.color is: [high value, ..., low value]
  75466. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  75467. // Notice: ec2 has no inverse.
  75468. if (isArray$1(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  75469. // So adding color only when no inRange defined.
  75470. && !base.inRange) {
  75471. base.inRange = {
  75472. color: thisOption.color.slice().reverse()
  75473. };
  75474. } // Compatible with previous logic, always give a defautl color, otherwise
  75475. // simple config with no inRange and outOfRange will not work.
  75476. // Originally we use visualMap.color as the default color, but setOption at
  75477. // the second time the default color will be erased. So we change to use
  75478. // constant DEFAULT_COLOR.
  75479. // If user do not want the default color, set inRange: {color: null}.
  75480. base.inRange = base.inRange || {
  75481. color: ecModel.get('gradientColor')
  75482. };
  75483. }
  75484. function completeInactive(base, stateExist, stateAbsent) {
  75485. var optExist = base[stateExist];
  75486. var optAbsent = base[stateAbsent];
  75487. if (optExist && !optAbsent) {
  75488. optAbsent = base[stateAbsent] = {};
  75489. each$f(optExist, function (visualData, visualType) {
  75490. if (!VisualMapping.isValidType(visualType)) {
  75491. return;
  75492. }
  75493. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  75494. if (defa != null) {
  75495. optAbsent[visualType] = defa; // Compatibable with ec2:
  75496. // Only inactive color to rgba(0,0,0,0) can not
  75497. // make label transparent, so use opacity also.
  75498. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  75499. optAbsent.opacity = [0, 0];
  75500. }
  75501. }
  75502. });
  75503. }
  75504. }
  75505. function completeController(controller) {
  75506. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  75507. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  75508. var inactiveColor = this.get('inactiveColor');
  75509. each$f(this.stateList, function (state) {
  75510. var itemSize = this.itemSize;
  75511. var visuals = controller[state]; // Set inactive color for controller if no other color
  75512. // attr (like colorAlpha) specified.
  75513. if (!visuals) {
  75514. visuals = controller[state] = {
  75515. color: isCategory ? inactiveColor : [inactiveColor]
  75516. };
  75517. } // Consistent symbol and symbolSize if not specified.
  75518. if (visuals.symbol == null) {
  75519. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? 'roundRect' : ['roundRect']);
  75520. }
  75521. if (visuals.symbolSize == null) {
  75522. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  75523. } // Filter square and none.
  75524. visuals.symbol = mapVisual$1(visuals.symbol, function (symbol) {
  75525. return symbol === 'none' || symbol === 'square' ? 'roundRect' : symbol;
  75526. }); // Normalize symbolSize
  75527. var symbolSize = visuals.symbolSize;
  75528. if (symbolSize != null) {
  75529. var max_1 = -Infinity; // symbolSize can be object when categories defined.
  75530. eachVisual(symbolSize, function (value) {
  75531. value > max_1 && (max_1 = value);
  75532. });
  75533. visuals.symbolSize = mapVisual$1(symbolSize, function (value) {
  75534. return linearMap$1(value, [0, max_1], [0, itemSize[0]], true);
  75535. });
  75536. }
  75537. }, this);
  75538. }
  75539. };
  75540. VisualMapModel.prototype.resetItemSize = function () {
  75541. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  75542. };
  75543. VisualMapModel.prototype.isCategory = function () {
  75544. return !!this.option.categories;
  75545. };
  75546. /**
  75547. * @public
  75548. * @abstract
  75549. */
  75550. VisualMapModel.prototype.setSelected = function (selected) {};
  75551. VisualMapModel.prototype.getSelected = function () {
  75552. return null;
  75553. };
  75554. /**
  75555. * @public
  75556. * @abstract
  75557. */
  75558. VisualMapModel.prototype.getValueState = function (value) {
  75559. return null;
  75560. };
  75561. /**
  75562. * FIXME
  75563. * Do not publish to thirt-part-dev temporarily
  75564. * util the interface is stable. (Should it return
  75565. * a function but not visual meta?)
  75566. *
  75567. * @pubilc
  75568. * @abstract
  75569. * @param getColorVisual
  75570. * params: value, valueState
  75571. * return: color
  75572. * @return {Object} visualMeta
  75573. * should includes {stops, outerColors}
  75574. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  75575. */
  75576. VisualMapModel.prototype.getVisualMeta = function (getColorVisual) {
  75577. return null;
  75578. };
  75579. VisualMapModel.type = 'visualMap';
  75580. VisualMapModel.dependencies = ['series'];
  75581. VisualMapModel.defaultOption = {
  75582. show: true,
  75583. zlevel: 0,
  75584. z: 4,
  75585. seriesIndex: 'all',
  75586. min: 0,
  75587. max: 200,
  75588. left: 0,
  75589. right: null,
  75590. top: null,
  75591. bottom: 0,
  75592. itemWidth: null,
  75593. itemHeight: null,
  75594. inverse: false,
  75595. orient: 'vertical',
  75596. backgroundColor: 'rgba(0,0,0,0)',
  75597. borderColor: '#ccc',
  75598. contentColor: '#5793f3',
  75599. inactiveColor: '#aaa',
  75600. borderWidth: 0,
  75601. padding: 5,
  75602. // 接受数组分别设定上右下左边距,同css
  75603. textGap: 10,
  75604. precision: 0,
  75605. textStyle: {
  75606. color: '#333' // 值域文字颜色
  75607. }
  75608. };
  75609. return VisualMapModel;
  75610. }(ComponentModel);
  75611. var DEFAULT_BAR_BOUND = [20, 140];
  75612. var ContinuousModel =
  75613. /** @class */
  75614. function (_super) {
  75615. __extends(ContinuousModel, _super);
  75616. function ContinuousModel() {
  75617. var _this = _super !== null && _super.apply(this, arguments) || this;
  75618. _this.type = ContinuousModel.type;
  75619. return _this;
  75620. }
  75621. /**
  75622. * @override
  75623. */
  75624. ContinuousModel.prototype.optionUpdated = function (newOption, isInit) {
  75625. _super.prototype.optionUpdated.apply(this, arguments);
  75626. this.resetExtent();
  75627. this.resetVisual(function (mappingOption) {
  75628. mappingOption.mappingMethod = 'linear';
  75629. mappingOption.dataExtent = this.getExtent();
  75630. });
  75631. this._resetRange();
  75632. };
  75633. /**
  75634. * @protected
  75635. * @override
  75636. */
  75637. ContinuousModel.prototype.resetItemSize = function () {
  75638. _super.prototype.resetItemSize.apply(this, arguments);
  75639. var itemSize = this.itemSize;
  75640. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  75641. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  75642. };
  75643. /**
  75644. * @private
  75645. */
  75646. ContinuousModel.prototype._resetRange = function () {
  75647. var dataExtent = this.getExtent();
  75648. var range = this.option.range;
  75649. if (!range || range.auto) {
  75650. // `range` should always be array (so we dont use other
  75651. // value like 'auto') for user-friend. (consider getOption).
  75652. dataExtent.auto = 1;
  75653. this.option.range = dataExtent;
  75654. } else if (isArray(range)) {
  75655. if (range[0] > range[1]) {
  75656. range.reverse();
  75657. }
  75658. range[0] = Math.max(range[0], dataExtent[0]);
  75659. range[1] = Math.min(range[1], dataExtent[1]);
  75660. }
  75661. };
  75662. /**
  75663. * @protected
  75664. * @override
  75665. */
  75666. ContinuousModel.prototype.completeVisualOption = function () {
  75667. _super.prototype.completeVisualOption.apply(this, arguments);
  75668. each(this.stateList, function (state) {
  75669. var symbolSize = this.option.controller[state].symbolSize;
  75670. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  75671. symbolSize[0] = symbolSize[1] / 3; // For good looking.
  75672. }
  75673. }, this);
  75674. };
  75675. /**
  75676. * @override
  75677. */
  75678. ContinuousModel.prototype.setSelected = function (selected) {
  75679. this.option.range = selected.slice();
  75680. this._resetRange();
  75681. };
  75682. /**
  75683. * @public
  75684. */
  75685. ContinuousModel.prototype.getSelected = function () {
  75686. var dataExtent = this.getExtent();
  75687. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  75688. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  75689. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  75690. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  75691. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  75692. return dataInterval;
  75693. };
  75694. /**
  75695. * @override
  75696. */
  75697. ContinuousModel.prototype.getValueState = function (value) {
  75698. var range = this.option.range;
  75699. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  75700. // range[1] is processed likewise.
  75701. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  75702. };
  75703. ContinuousModel.prototype.findTargetDataIndices = function (range) {
  75704. var result = [];
  75705. this.eachTargetSeries(function (seriesModel) {
  75706. var dataIndices = [];
  75707. var data = seriesModel.getData();
  75708. data.each(this.getDataDimension(data), function (value, dataIndex) {
  75709. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  75710. }, this);
  75711. result.push({
  75712. seriesId: seriesModel.id,
  75713. dataIndex: dataIndices
  75714. });
  75715. }, this);
  75716. return result;
  75717. };
  75718. /**
  75719. * @implement
  75720. */
  75721. ContinuousModel.prototype.getVisualMeta = function (getColorVisual) {
  75722. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  75723. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  75724. var stops = [];
  75725. function setStop(value, valueState) {
  75726. stops.push({
  75727. value: value,
  75728. color: getColorVisual(value, valueState)
  75729. });
  75730. } // Format to: outOfRange -- inRange -- outOfRange.
  75731. var iIdx = 0;
  75732. var oIdx = 0;
  75733. var iLen = iVals.length;
  75734. var oLen = oVals.length;
  75735. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  75736. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  75737. if (oVals[oIdx] < iVals[iIdx]) {
  75738. setStop(oVals[oIdx], 'outOfRange');
  75739. }
  75740. }
  75741. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  75742. // If range is full, value beyond min, max will be clamped.
  75743. // make a singularity
  75744. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  75745. setStop(iVals[iIdx], 'inRange');
  75746. }
  75747. for (var first = 1; oIdx < oLen; oIdx++) {
  75748. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  75749. // make a singularity
  75750. if (first) {
  75751. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  75752. first = 0;
  75753. }
  75754. setStop(oVals[oIdx], 'outOfRange');
  75755. }
  75756. }
  75757. var stopsLen = stops.length;
  75758. return {
  75759. stops: stops,
  75760. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  75761. };
  75762. };
  75763. ContinuousModel.type = 'visualMap.continuous';
  75764. ContinuousModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  75765. align: 'auto',
  75766. calculable: false,
  75767. hoverLink: true,
  75768. realtime: true,
  75769. 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',
  75770. handleSize: '120%',
  75771. handleStyle: {
  75772. borderColor: '#fff',
  75773. borderWidth: 1
  75774. },
  75775. indicatorIcon: 'circle',
  75776. indicatorSize: '50%',
  75777. indicatorStyle: {
  75778. borderColor: '#fff',
  75779. borderWidth: 2,
  75780. shadowBlur: 2,
  75781. shadowOffsetX: 1,
  75782. shadowOffsetY: 1,
  75783. shadowColor: 'rgba(0,0,0,0.2)'
  75784. } // emphasis: {
  75785. // handleStyle: {
  75786. // shadowBlur: 3,
  75787. // shadowOffsetX: 1,
  75788. // shadowOffsetY: 1,
  75789. // shadowColor: 'rgba(0,0,0,0.2)'
  75790. // }
  75791. // }
  75792. });
  75793. return ContinuousModel;
  75794. }(VisualMapModel);
  75795. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  75796. if (dataExtent[0] === dataExtent[1]) {
  75797. return dataExtent.slice();
  75798. } // When using colorHue mapping, it is not linear color any more.
  75799. // Moreover, canvas gradient seems not to be accurate linear.
  75800. // FIXME
  75801. // Should be arbitrary value 100? or based on pixel size?
  75802. var count = 200;
  75803. var step = (dataExtent[1] - dataExtent[0]) / count;
  75804. var value = dataExtent[0];
  75805. var stopValues = [];
  75806. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  75807. stopValues.push(value);
  75808. value += step;
  75809. }
  75810. stopValues.push(dataExtent[1]);
  75811. return stopValues;
  75812. }
  75813. var VisualMapView =
  75814. /** @class */
  75815. function (_super) {
  75816. __extends(VisualMapView, _super);
  75817. function VisualMapView() {
  75818. var _this = _super !== null && _super.apply(this, arguments) || this;
  75819. _this.type = VisualMapView.type;
  75820. _this.autoPositionValues = {
  75821. left: 1,
  75822. right: 1,
  75823. top: 1,
  75824. bottom: 1
  75825. };
  75826. return _this;
  75827. }
  75828. VisualMapView.prototype.init = function (ecModel, api) {
  75829. this.ecModel = ecModel;
  75830. this.api = api;
  75831. };
  75832. /**
  75833. * @protected
  75834. */
  75835. VisualMapView.prototype.render = function (visualMapModel, ecModel, api, payload // TODO: TYPE
  75836. ) {
  75837. this.visualMapModel = visualMapModel;
  75838. if (visualMapModel.get('show') === false) {
  75839. this.group.removeAll();
  75840. return;
  75841. }
  75842. this.doRender(visualMapModel, ecModel, api, payload);
  75843. };
  75844. /**
  75845. * @protected
  75846. */
  75847. VisualMapView.prototype.renderBackground = function (group) {
  75848. var visualMapModel = this.visualMapModel;
  75849. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  75850. var rect = group.getBoundingRect();
  75851. group.add(new Rect({
  75852. z2: -1,
  75853. silent: true,
  75854. shape: {
  75855. x: rect.x - padding[3],
  75856. y: rect.y - padding[0],
  75857. width: rect.width + padding[3] + padding[1],
  75858. height: rect.height + padding[0] + padding[2]
  75859. },
  75860. style: {
  75861. fill: visualMapModel.get('backgroundColor'),
  75862. stroke: visualMapModel.get('borderColor'),
  75863. lineWidth: visualMapModel.get('borderWidth')
  75864. }
  75865. }));
  75866. };
  75867. /**
  75868. * @protected
  75869. * @param targetValue can be Infinity or -Infinity
  75870. * @param visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  75871. * @param opts
  75872. * @param opts.forceState Specify state, instead of using getValueState method.
  75873. * @param opts.convertOpacityToAlpha For color gradient in controller widget.
  75874. * @return {*} Visual value.
  75875. */
  75876. VisualMapView.prototype.getControllerVisual = function (targetValue, visualCluster, opts) {
  75877. opts = opts || {};
  75878. var forceState = opts.forceState;
  75879. var visualMapModel = this.visualMapModel;
  75880. var visualObj = {}; // Default values.
  75881. if (visualCluster === 'symbol') {
  75882. visualObj.symbol = visualMapModel.get('itemSymbol');
  75883. }
  75884. if (visualCluster === 'color') {
  75885. var defaultColor = visualMapModel.get('contentColor');
  75886. visualObj.color = defaultColor;
  75887. }
  75888. function getter(key) {
  75889. return visualObj[key];
  75890. }
  75891. function setter(key, value) {
  75892. visualObj[key] = value;
  75893. }
  75894. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  75895. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  75896. each(visualTypes, function (type) {
  75897. var visualMapping = mappings[type];
  75898. if (opts.convertOpacityToAlpha && type === 'opacity') {
  75899. type = 'colorAlpha';
  75900. visualMapping = mappings.__alphaForOpacity;
  75901. }
  75902. if (VisualMapping.dependsOn(type, visualCluster)) {
  75903. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  75904. }
  75905. });
  75906. return visualObj[visualCluster];
  75907. };
  75908. VisualMapView.prototype.positionGroup = function (group) {
  75909. var model = this.visualMapModel;
  75910. var api = this.api;
  75911. positionElement(group, model.getBoxLayoutParams(), {
  75912. width: api.getWidth(),
  75913. height: api.getHeight()
  75914. });
  75915. };
  75916. VisualMapView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {};
  75917. VisualMapView.type = 'visualMap';
  75918. return VisualMapView;
  75919. }(ComponentView);
  75920. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  75921. /**
  75922. * @param visualMapModel
  75923. * @param api
  75924. * @param itemSize always [short, long]
  75925. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  75926. */
  75927. function getItemAlign(visualMapModel, api, itemSize) {
  75928. var modelOption = visualMapModel.option;
  75929. var itemAlign = modelOption.align;
  75930. if (itemAlign != null && itemAlign !== 'auto') {
  75931. return itemAlign;
  75932. } // Auto decision align.
  75933. var ecSize = {
  75934. width: api.getWidth(),
  75935. height: api.getHeight()
  75936. };
  75937. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  75938. var reals = paramsSet[realIndex];
  75939. var fakeValue = [0, null, 10];
  75940. var layoutInput = {};
  75941. for (var i = 0; i < 3; i++) {
  75942. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  75943. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  75944. }
  75945. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  75946. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  75947. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  75948. }
  75949. /**
  75950. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  75951. * dataIndexInside means filtered index.
  75952. */
  75953. // TODO: TYPE more specified payload types.
  75954. function makeHighDownBatch(batch, visualMapModel) {
  75955. each(batch || [], function (batchItem) {
  75956. if (batchItem.dataIndex != null) {
  75957. batchItem.dataIndexInside = batchItem.dataIndex;
  75958. batchItem.dataIndex = null;
  75959. }
  75960. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  75961. });
  75962. return batch;
  75963. }
  75964. var linearMap$2 = linearMap;
  75965. var each$g = each;
  75966. var mathMin$a = Math.min;
  75967. var mathMax$a = Math.max; // Arbitrary value
  75968. var HOVER_LINK_SIZE = 12;
  75969. var HOVER_LINK_OUT = 6; // Notice:
  75970. // Any "interval" should be by the order of [low, high].
  75971. // "handle0" (handleIndex === 0) maps to
  75972. // low data value: this._dataInterval[0] and has low coord.
  75973. // "handle1" (handleIndex === 1) maps to
  75974. // high data value: this._dataInterval[1] and has high coord.
  75975. // The logic of transform is implemented in this._createBarGroup.
  75976. var ContinuousView =
  75977. /** @class */
  75978. function (_super) {
  75979. __extends(ContinuousView, _super);
  75980. function ContinuousView() {
  75981. var _this = _super !== null && _super.apply(this, arguments) || this;
  75982. _this.type = ContinuousView.type;
  75983. _this._shapes = {};
  75984. _this._dataInterval = [];
  75985. _this._handleEnds = [];
  75986. _this._hoverLinkDataIndices = [];
  75987. return _this;
  75988. }
  75989. ContinuousView.prototype.doRender = function (visualMapModel, ecModel, api, payload) {
  75990. this._api = api;
  75991. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  75992. this._buildView();
  75993. }
  75994. };
  75995. ContinuousView.prototype._buildView = function () {
  75996. this.group.removeAll();
  75997. var visualMapModel = this.visualMapModel;
  75998. var thisGroup = this.group;
  75999. this._orient = visualMapModel.get('orient');
  76000. this._useHandle = visualMapModel.get('calculable');
  76001. this._resetInterval();
  76002. this._renderBar(thisGroup);
  76003. var dataRangeText = visualMapModel.get('text');
  76004. this._renderEndsText(thisGroup, dataRangeText, 0);
  76005. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  76006. this._updateView(true); // After updating view, inner shapes is built completely,
  76007. // and then background can be rendered.
  76008. this.renderBackground(thisGroup); // Real update view
  76009. this._updateView();
  76010. this._enableHoverLinkToSeries();
  76011. this._enableHoverLinkFromSeries();
  76012. this.positionGroup(thisGroup);
  76013. };
  76014. ContinuousView.prototype._renderEndsText = function (group, dataRangeText, endsIndex) {
  76015. if (!dataRangeText) {
  76016. return;
  76017. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  76018. var text = dataRangeText[1 - endsIndex];
  76019. text = text != null ? text + '' : '';
  76020. var visualMapModel = this.visualMapModel;
  76021. var textGap = visualMapModel.get('textGap');
  76022. var itemSize = visualMapModel.itemSize;
  76023. var barGroup = this._shapes.mainGroup;
  76024. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  76025. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  76026. var orient = this._orient;
  76027. var textStyleModel = this.visualMapModel.textStyleModel;
  76028. this.group.add(new ZRText({
  76029. style: {
  76030. x: position[0],
  76031. y: position[1],
  76032. verticalAlign: orient === 'horizontal' ? 'middle' : align,
  76033. align: orient === 'horizontal' ? align : 'center',
  76034. text: text,
  76035. font: textStyleModel.getFont(),
  76036. fill: textStyleModel.getTextColor()
  76037. }
  76038. }));
  76039. };
  76040. ContinuousView.prototype._renderBar = function (targetGroup) {
  76041. var visualMapModel = this.visualMapModel;
  76042. var shapes = this._shapes;
  76043. var itemSize = visualMapModel.itemSize;
  76044. var orient = this._orient;
  76045. var useHandle = this._useHandle;
  76046. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  76047. var mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
  76048. var gradientBarGroup = new Group();
  76049. mainGroup.add(gradientBarGroup); // Bar
  76050. gradientBarGroup.add(shapes.outOfRange = createPolygon());
  76051. 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.
  76052. gradientBarGroup.setClipPath(new Rect({
  76053. shape: {
  76054. x: 0,
  76055. y: 0,
  76056. width: itemSize[0],
  76057. height: itemSize[1],
  76058. r: 3
  76059. }
  76060. }));
  76061. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  76062. var textSize = mathMax$a(textRect.width, textRect.height); // Handle
  76063. if (useHandle) {
  76064. shapes.handleThumbs = [];
  76065. shapes.handleLabels = [];
  76066. shapes.handleLabelPoints = [];
  76067. this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
  76068. this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
  76069. }
  76070. this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
  76071. targetGroup.add(mainGroup);
  76072. };
  76073. ContinuousView.prototype._createHandle = function (visualMapModel, mainGroup, handleIndex, itemSize, textSize, orient) {
  76074. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  76075. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  76076. var handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
  76077. var handleThumb = createSymbol(visualMapModel.get('handleIcon'), -handleSize / 2, -handleSize / 2, handleSize, handleSize, null, true);
  76078. var cursor = getCursor$1(this._orient);
  76079. handleThumb.attr({
  76080. cursor: cursor,
  76081. draggable: true,
  76082. drift: onDrift,
  76083. ondragend: onDragEnd,
  76084. onmousemove: function (e) {
  76085. stop(e.event);
  76086. }
  76087. });
  76088. handleThumb.x = itemSize[0] / 2;
  76089. handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
  76090. handleThumb.setStyle({
  76091. strokeNoScale: true,
  76092. strokeFirst: true
  76093. });
  76094. handleThumb.style.lineWidth *= 2;
  76095. handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
  76096. setAsHighDownDispatcher(handleThumb, true);
  76097. mainGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  76098. // transform (orient/inverse). So label is built separately but not
  76099. // use zrender/graphic/helper/RectText, and is located based on view
  76100. // group (according to handleLabelPoint) but not barGroup.
  76101. var textStyleModel = this.visualMapModel.textStyleModel;
  76102. var handleLabel = new ZRText({
  76103. cursor: cursor,
  76104. draggable: true,
  76105. drift: onDrift,
  76106. onmousemove: function (e) {
  76107. // Fot mobile devicem, prevent screen slider on the button.
  76108. stop(e.event);
  76109. },
  76110. ondragend: onDragEnd,
  76111. style: {
  76112. x: 0,
  76113. y: 0,
  76114. text: '',
  76115. font: textStyleModel.getFont(),
  76116. fill: textStyleModel.getTextColor()
  76117. }
  76118. });
  76119. handleLabel.ensureState('blur').style = {
  76120. opacity: 0.1
  76121. };
  76122. handleLabel.stateTransition = {
  76123. duration: 200
  76124. };
  76125. this.group.add(handleLabel);
  76126. var handleLabelPoint = [handleSize, 0];
  76127. var shapes = this._shapes;
  76128. shapes.handleThumbs[handleIndex] = handleThumb;
  76129. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  76130. shapes.handleLabels[handleIndex] = handleLabel;
  76131. };
  76132. ContinuousView.prototype._createIndicator = function (visualMapModel, mainGroup, itemSize, textSize, orient) {
  76133. var scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
  76134. var indicator = createSymbol(visualMapModel.get('indicatorIcon'), -scale / 2, -scale / 2, scale, scale, null, true);
  76135. indicator.attr({
  76136. cursor: 'move',
  76137. invisible: true,
  76138. silent: true,
  76139. x: itemSize[0] / 2
  76140. });
  76141. var indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
  76142. if (indicator instanceof ZRImage) {
  76143. var pathStyle = indicator.style;
  76144. indicator.useStyle(extend({
  76145. // TODO other properties like x, y ?
  76146. image: pathStyle.image,
  76147. x: pathStyle.x,
  76148. y: pathStyle.y,
  76149. width: pathStyle.width,
  76150. height: pathStyle.height
  76151. }, indicatorStyle));
  76152. } else {
  76153. indicator.useStyle(indicatorStyle);
  76154. }
  76155. mainGroup.add(indicator);
  76156. var textStyleModel = this.visualMapModel.textStyleModel;
  76157. var indicatorLabel = new ZRText({
  76158. silent: true,
  76159. invisible: true,
  76160. style: {
  76161. x: 0,
  76162. y: 0,
  76163. text: '',
  76164. font: textStyleModel.getFont(),
  76165. fill: textStyleModel.getTextColor()
  76166. }
  76167. });
  76168. this.group.add(indicatorLabel);
  76169. var indicatorLabelPoint = [(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2, 0];
  76170. var shapes = this._shapes;
  76171. shapes.indicator = indicator;
  76172. shapes.indicatorLabel = indicatorLabel;
  76173. shapes.indicatorLabelPoint = indicatorLabelPoint;
  76174. this._firstShowIndicator = true;
  76175. };
  76176. ContinuousView.prototype._dragHandle = function (handleIndex, isEnd, // dx is event from ondragend if isEnd is true. It's not used
  76177. dx, dy) {
  76178. if (!this._useHandle) {
  76179. return;
  76180. }
  76181. this._dragging = !isEnd;
  76182. if (!isEnd) {
  76183. // Transform dx, dy to bar coordination.
  76184. var vertex = this._applyTransform([dx, dy], this._shapes.mainGroup, true);
  76185. this._updateInterval(handleIndex, vertex[1]);
  76186. this._hideIndicator(); // Considering realtime, update view should be executed
  76187. // before dispatch action.
  76188. this._updateView();
  76189. } // dragEnd do not dispatch action when realtime.
  76190. if (isEnd === !this.visualMapModel.get('realtime')) {
  76191. // jshint ignore:line
  76192. this.api.dispatchAction({
  76193. type: 'selectDataRange',
  76194. from: this.uid,
  76195. visualMapId: this.visualMapModel.id,
  76196. selected: this._dataInterval.slice()
  76197. });
  76198. }
  76199. if (isEnd) {
  76200. !this._hovering && this._clearHoverLinkToSeries();
  76201. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  76202. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  76203. }
  76204. };
  76205. ContinuousView.prototype._resetInterval = function () {
  76206. var visualMapModel = this.visualMapModel;
  76207. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  76208. var dataExtent = visualMapModel.getExtent();
  76209. var sizeExtent = [0, visualMapModel.itemSize[1]];
  76210. this._handleEnds = [linearMap$2(dataInterval[0], dataExtent, sizeExtent, true), linearMap$2(dataInterval[1], dataExtent, sizeExtent, true)];
  76211. };
  76212. /**
  76213. * @private
  76214. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  76215. * @param {number} dx
  76216. * @param {number} dy
  76217. */
  76218. ContinuousView.prototype._updateInterval = function (handleIndex, delta) {
  76219. delta = delta || 0;
  76220. var visualMapModel = this.visualMapModel;
  76221. var handleEnds = this._handleEnds;
  76222. var sizeExtent = [0, visualMapModel.itemSize[1]];
  76223. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbiden
  76224. 0);
  76225. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  76226. this._dataInterval = [linearMap$2(handleEnds[0], sizeExtent, dataExtent, true), linearMap$2(handleEnds[1], sizeExtent, dataExtent, true)];
  76227. };
  76228. ContinuousView.prototype._updateView = function (forSketch) {
  76229. var visualMapModel = this.visualMapModel;
  76230. var dataExtent = visualMapModel.getExtent();
  76231. var shapes = this._shapes;
  76232. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  76233. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  76234. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  76235. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  76236. shapes.inRange.setStyle({
  76237. fill: visualInRange.barColor // opacity: visualInRange.opacity
  76238. }).setShape('points', visualInRange.barPoints);
  76239. shapes.outOfRange.setStyle({
  76240. fill: visualOutOfRange.barColor // opacity: visualOutOfRange.opacity
  76241. }).setShape('points', visualOutOfRange.barPoints);
  76242. this._updateHandle(inRangeHandleEnds, visualInRange);
  76243. };
  76244. ContinuousView.prototype._createBarVisual = function (dataInterval, dataExtent, handleEnds, forceState) {
  76245. var opts = {
  76246. forceState: forceState,
  76247. convertOpacityToAlpha: true
  76248. };
  76249. var colorStops = this._makeColorGradient(dataInterval, opts);
  76250. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  76251. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  76252. return {
  76253. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  76254. barPoints: barPoints,
  76255. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  76256. };
  76257. };
  76258. ContinuousView.prototype._makeColorGradient = function (dataInterval, opts) {
  76259. // Considering colorHue, which is not linear, so we have to sample
  76260. // to calculate gradient color stops, but not only caculate head
  76261. // and tail.
  76262. var sampleNumber = 100; // Arbitrary value.
  76263. var colorStops = [];
  76264. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  76265. colorStops.push({
  76266. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  76267. offset: 0
  76268. });
  76269. for (var i = 1; i < sampleNumber; i++) {
  76270. var currValue = dataInterval[0] + step * i;
  76271. if (currValue > dataInterval[1]) {
  76272. break;
  76273. }
  76274. colorStops.push({
  76275. color: this.getControllerVisual(currValue, 'color', opts),
  76276. offset: i / sampleNumber
  76277. });
  76278. }
  76279. colorStops.push({
  76280. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  76281. offset: 1
  76282. });
  76283. return colorStops;
  76284. };
  76285. ContinuousView.prototype._createBarPoints = function (handleEnds, symbolSizes) {
  76286. var itemSize = this.visualMapModel.itemSize;
  76287. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  76288. };
  76289. ContinuousView.prototype._createBarGroup = function (itemAlign) {
  76290. var orient = this._orient;
  76291. var inverse = this.visualMapModel.get('inverse');
  76292. return new Group(orient === 'horizontal' && !inverse ? {
  76293. scaleX: itemAlign === 'bottom' ? 1 : -1,
  76294. rotation: Math.PI / 2
  76295. } : orient === 'horizontal' && inverse ? {
  76296. scaleX: itemAlign === 'bottom' ? -1 : 1,
  76297. rotation: -Math.PI / 2
  76298. } : orient === 'vertical' && !inverse ? {
  76299. scaleX: itemAlign === 'left' ? 1 : -1,
  76300. scaleY: -1
  76301. } : {
  76302. scaleX: itemAlign === 'left' ? 1 : -1
  76303. });
  76304. };
  76305. ContinuousView.prototype._updateHandle = function (handleEnds, visualInRange) {
  76306. if (!this._useHandle) {
  76307. return;
  76308. }
  76309. var shapes = this._shapes;
  76310. var visualMapModel = this.visualMapModel;
  76311. var handleThumbs = shapes.handleThumbs;
  76312. var handleLabels = shapes.handleLabels;
  76313. var itemSize = visualMapModel.itemSize;
  76314. var dataExtent = visualMapModel.getExtent();
  76315. each$g([0, 1], function (handleIndex) {
  76316. var handleThumb = handleThumbs[handleIndex];
  76317. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  76318. handleThumb.y = handleEnds[handleIndex];
  76319. var val = linearMap$2(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
  76320. var symbolSize = this.getControllerVisual(val, 'symbolSize');
  76321. handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
  76322. handleThumb.x = itemSize[0] - symbolSize / 2; // Update handle label position.
  76323. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  76324. handleLabels[handleIndex].setStyle({
  76325. x: textPoint[0],
  76326. y: textPoint[1],
  76327. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  76328. verticalAlign: 'middle',
  76329. align: this._orient === 'vertical' ? this._applyTransform('left', shapes.mainGroup) : 'center'
  76330. });
  76331. }, this);
  76332. };
  76333. ContinuousView.prototype._showIndicator = function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  76334. var visualMapModel = this.visualMapModel;
  76335. var dataExtent = visualMapModel.getExtent();
  76336. var itemSize = visualMapModel.itemSize;
  76337. var sizeExtent = [0, itemSize[1]];
  76338. var shapes = this._shapes;
  76339. var indicator = shapes.indicator;
  76340. if (!indicator) {
  76341. return;
  76342. }
  76343. indicator.attr('invisible', false);
  76344. var opts = {
  76345. convertOpacityToAlpha: true
  76346. };
  76347. var color = this.getControllerVisual(cursorValue, 'color', opts);
  76348. var symbolSize = this.getControllerVisual(cursorValue, 'symbolSize');
  76349. var y = linearMap$2(cursorValue, dataExtent, sizeExtent, true);
  76350. var x = itemSize[0] - symbolSize / 2;
  76351. var oldIndicatorPos = {
  76352. x: indicator.x,
  76353. y: indicator.y
  76354. }; // Update handle label position.
  76355. indicator.y = y;
  76356. indicator.x = x;
  76357. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  76358. var indicatorLabel = shapes.indicatorLabel;
  76359. indicatorLabel.attr('invisible', false);
  76360. var align = this._applyTransform('left', shapes.mainGroup);
  76361. var orient = this._orient;
  76362. var isHorizontal = orient === 'horizontal';
  76363. indicatorLabel.setStyle({
  76364. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  76365. verticalAlign: isHorizontal ? align : 'middle',
  76366. align: isHorizontal ? 'center' : align
  76367. });
  76368. var indicatorNewProps = {
  76369. x: x,
  76370. y: y,
  76371. style: {
  76372. fill: color
  76373. }
  76374. };
  76375. var labelNewProps = {
  76376. style: {
  76377. x: textPoint[0],
  76378. y: textPoint[1]
  76379. }
  76380. };
  76381. if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
  76382. var animationCfg = {
  76383. duration: 100,
  76384. easing: 'cubicInOut',
  76385. additive: true
  76386. };
  76387. indicator.x = oldIndicatorPos.x;
  76388. indicator.y = oldIndicatorPos.y;
  76389. indicator.animateTo(indicatorNewProps, animationCfg);
  76390. indicatorLabel.animateTo(labelNewProps, animationCfg);
  76391. } else {
  76392. indicator.attr(indicatorNewProps);
  76393. indicatorLabel.attr(labelNewProps);
  76394. }
  76395. this._firstShowIndicator = false;
  76396. var handleLabels = this._shapes.handleLabels;
  76397. if (handleLabels) {
  76398. for (var i = 0; i < handleLabels.length; i++) {
  76399. // Fade out handle labels.
  76400. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  76401. this._api.enterBlur(handleLabels[i]);
  76402. }
  76403. }
  76404. };
  76405. ContinuousView.prototype._enableHoverLinkToSeries = function () {
  76406. var self = this;
  76407. this._shapes.mainGroup.on('mousemove', function (e) {
  76408. self._hovering = true;
  76409. if (!self._dragging) {
  76410. var itemSize = self.visualMapModel.itemSize;
  76411. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.mainGroup, true, true); // For hover link show when hover handle, which might be
  76412. // below or upper than sizeExtent.
  76413. pos[1] = mathMin$a(mathMax$a(0, pos[1]), itemSize[1]);
  76414. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  76415. }
  76416. }).on('mouseout', function () {
  76417. // When mouse is out of handle, hoverLink still need
  76418. // to be displayed when realtime is set as false.
  76419. self._hovering = false;
  76420. !self._dragging && self._clearHoverLinkToSeries();
  76421. });
  76422. };
  76423. ContinuousView.prototype._enableHoverLinkFromSeries = function () {
  76424. var zr = this.api.getZr();
  76425. if (this.visualMapModel.option.hoverLink) {
  76426. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  76427. zr.on('mouseout', this._hideIndicator, this);
  76428. } else {
  76429. this._clearHoverLinkFromSeries();
  76430. }
  76431. };
  76432. ContinuousView.prototype._doHoverLinkToSeries = function (cursorPos, hoverOnBar) {
  76433. var visualMapModel = this.visualMapModel;
  76434. var itemSize = visualMapModel.itemSize;
  76435. if (!visualMapModel.option.hoverLink) {
  76436. return;
  76437. }
  76438. var sizeExtent = [0, itemSize[1]];
  76439. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  76440. cursorPos = mathMin$a(mathMax$a(sizeExtent[0], cursorPos), sizeExtent[1]);
  76441. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  76442. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  76443. var cursorValue = linearMap$2(cursorPos, sizeExtent, dataExtent, true);
  76444. 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,
  76445. // where china and india has very large population.
  76446. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  76447. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  76448. // otherwise labels overlap, especially when dragging.
  76449. if (hoverOnBar) {
  76450. if (valueRange[0] === -Infinity) {
  76451. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  76452. } else if (valueRange[1] === Infinity) {
  76453. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  76454. } else {
  76455. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  76456. }
  76457. } // When realtime is set as false, handles, which are in barGroup,
  76458. // also trigger hoverLink, which help user to realize where they
  76459. // focus on when dragging. (see test/heatmap-large.html)
  76460. // When realtime is set as true, highlight will not show when hover
  76461. // handle, because the label on handle, which displays a exact value
  76462. // but not range, might mislead users.
  76463. var oldBatch = this._hoverLinkDataIndices;
  76464. var newBatch = [];
  76465. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  76466. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  76467. }
  76468. var resultBatches = compressBatches(oldBatch, newBatch);
  76469. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  76470. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  76471. };
  76472. ContinuousView.prototype._hoverLinkFromSeriesMouseOver = function (e) {
  76473. var el = e.target;
  76474. var visualMapModel = this.visualMapModel;
  76475. if (!el || getECData(el).dataIndex == null) {
  76476. return;
  76477. }
  76478. var ecData = getECData(el);
  76479. var dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
  76480. if (!visualMapModel.isTargetSeries(dataModel)) {
  76481. return;
  76482. }
  76483. var data = dataModel.getData(ecData.dataType);
  76484. var value = data.get(visualMapModel.getDataDimension(data), ecData.dataIndex);
  76485. if (!isNaN(value)) {
  76486. this._showIndicator(value, value);
  76487. }
  76488. };
  76489. ContinuousView.prototype._hideIndicator = function () {
  76490. var shapes = this._shapes;
  76491. shapes.indicator && shapes.indicator.attr('invisible', true);
  76492. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  76493. var handleLabels = this._shapes.handleLabels;
  76494. if (handleLabels) {
  76495. for (var i = 0; i < handleLabels.length; i++) {
  76496. // Fade out handle labels.
  76497. // NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
  76498. this._api.leaveBlur(handleLabels[i]);
  76499. }
  76500. }
  76501. };
  76502. ContinuousView.prototype._clearHoverLinkToSeries = function () {
  76503. this._hideIndicator();
  76504. var indices = this._hoverLinkDataIndices;
  76505. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  76506. indices.length = 0;
  76507. };
  76508. ContinuousView.prototype._clearHoverLinkFromSeries = function () {
  76509. this._hideIndicator();
  76510. var zr = this.api.getZr();
  76511. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  76512. zr.off('mouseout', this._hideIndicator);
  76513. };
  76514. ContinuousView.prototype._applyTransform = function (vertex, element, inverse, global) {
  76515. var transform = getTransform(element, global ? null : this.group);
  76516. return isArray(vertex) ? applyTransform$1(vertex, transform, inverse) : transformDirection(vertex, transform, inverse);
  76517. }; // TODO: TYPE more specified payload types.
  76518. ContinuousView.prototype._dispatchHighDown = function (type, batch) {
  76519. batch && batch.length && this.api.dispatchAction({
  76520. type: type,
  76521. batch: batch
  76522. });
  76523. };
  76524. /**
  76525. * @override
  76526. */
  76527. ContinuousView.prototype.dispose = function () {
  76528. this._clearHoverLinkFromSeries();
  76529. this._clearHoverLinkToSeries();
  76530. };
  76531. /**
  76532. * @override
  76533. */
  76534. ContinuousView.prototype.remove = function () {
  76535. this._clearHoverLinkFromSeries();
  76536. this._clearHoverLinkToSeries();
  76537. };
  76538. ContinuousView.type = 'visualMap.continuous';
  76539. return ContinuousView;
  76540. }(VisualMapView);
  76541. function createPolygon(points, cursor, onDrift, onDragEnd) {
  76542. return new Polygon({
  76543. shape: {
  76544. points: points
  76545. },
  76546. draggable: !!onDrift,
  76547. cursor: cursor,
  76548. drift: onDrift,
  76549. onmousemove: function (e) {
  76550. // Fot mobile devicem, prevent screen slider on the button.
  76551. stop(e.event);
  76552. },
  76553. ondragend: onDragEnd
  76554. });
  76555. }
  76556. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  76557. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  76558. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  76559. if (hoverLinkDataSize) {
  76560. halfHoverLinkSize = linearMap$2(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  76561. }
  76562. return halfHoverLinkSize;
  76563. }
  76564. function useHoverLinkOnHandle(visualMapModel) {
  76565. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  76566. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  76567. }
  76568. function getCursor$1(orient) {
  76569. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  76570. }
  76571. /*
  76572. * Licensed to the Apache Software Foundation (ASF) under one
  76573. * or more contributor license agreements. See the NOTICE file
  76574. * distributed with this work for additional information
  76575. * regarding copyright ownership. The ASF licenses this file
  76576. * to you under the Apache License, Version 2.0 (the
  76577. * "License"); you may not use this file except in compliance
  76578. * with the License. You may obtain a copy of the License at
  76579. *
  76580. * http://www.apache.org/licenses/LICENSE-2.0
  76581. *
  76582. * Unless required by applicable law or agreed to in writing,
  76583. * software distributed under the License is distributed on an
  76584. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76585. * KIND, either express or implied. See the License for the
  76586. * specific language governing permissions and limitations
  76587. * under the License.
  76588. */
  76589. /**
  76590. * AUTO-GENERATED FILE. DO NOT MODIFY.
  76591. */
  76592. /*
  76593. * Licensed to the Apache Software Foundation (ASF) under one
  76594. * or more contributor license agreements. See the NOTICE file
  76595. * distributed with this work for additional information
  76596. * regarding copyright ownership. The ASF licenses this file
  76597. * to you under the Apache License, Version 2.0 (the
  76598. * "License"); you may not use this file except in compliance
  76599. * with the License. You may obtain a copy of the License at
  76600. *
  76601. * http://www.apache.org/licenses/LICENSE-2.0
  76602. *
  76603. * Unless required by applicable law or agreed to in writing,
  76604. * software distributed under the License is distributed on an
  76605. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  76606. * KIND, either express or implied. See the License for the
  76607. * specific language governing permissions and limitations
  76608. * under the License.
  76609. */
  76610. var visualMapActionInfo = {
  76611. type: 'selectDataRange',
  76612. event: 'dataRangeSelected',
  76613. // FIXME use updateView appears wrong
  76614. update: 'update'
  76615. };
  76616. var visualMapActionHander = function (payload, ecModel) {
  76617. ecModel.eachComponent({
  76618. mainType: 'visualMap',
  76619. query: payload
  76620. }, function (model) {
  76621. model.setSelected(payload.selected);
  76622. });
  76623. };
  76624. var visualMapEncodingHandlers = [{
  76625. createOnAllSeries: true,
  76626. reset: function (seriesModel, ecModel) {
  76627. var resetDefines = [];
  76628. ecModel.eachComponent('visualMap', function (visualMapModel) {
  76629. var pipelineContext = seriesModel.pipelineContext;
  76630. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  76631. return;
  76632. }
  76633. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimension(seriesModel.getData())));
  76634. });
  76635. return resetDefines;
  76636. }
  76637. }, // Only support color.
  76638. {
  76639. createOnAllSeries: true,
  76640. reset: function (seriesModel, ecModel) {
  76641. var data = seriesModel.getData();
  76642. var visualMetaList = [];
  76643. ecModel.eachComponent('visualMap', function (visualMapModel) {
  76644. if (visualMapModel.isTargetSeries(seriesModel)) {
  76645. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  76646. stops: [],
  76647. outerColors: []
  76648. };
  76649. var concreteDim = visualMapModel.getDataDimension(data);
  76650. var dimInfo = data.getDimensionInfo(concreteDim);
  76651. if (dimInfo != null) {
  76652. // visualMeta.dimension should be dimension index, but not concrete dimension.
  76653. visualMeta.dimension = dimInfo.index;
  76654. visualMetaList.push(visualMeta);
  76655. }
  76656. }
  76657. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  76658. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  76659. }
  76660. }]; // FIXME
  76661. // performance and export for heatmap?
  76662. // value can be Infinity or -Infinity
  76663. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  76664. var mappings = visualMapModel.targetVisuals[valueState];
  76665. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  76666. var resultVisual = {
  76667. color: getVisualFromData(seriesModel.getData(), 'color') // default color.
  76668. };
  76669. for (var i = 0, len = visualTypes.length; i < len; i++) {
  76670. var type = visualTypes[i];
  76671. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  76672. mapping && mapping.applyVisual(value, getVisual, setVisual);
  76673. }
  76674. return resultVisual.color;
  76675. function getVisual(key) {
  76676. return resultVisual[key];
  76677. }
  76678. function setVisual(key, value) {
  76679. resultVisual[key] = value;
  76680. }
  76681. }
  76682. var each$h = each;
  76683. function visualMapPreprocessor(option) {
  76684. var visualMap = option && option.visualMap;
  76685. if (!isArray(visualMap)) {
  76686. visualMap = visualMap ? [visualMap] : [];
  76687. }
  76688. each$h(visualMap, function (opt) {
  76689. if (!opt) {
  76690. return;
  76691. } // rename splitList to pieces
  76692. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  76693. opt.pieces = opt.splitList;
  76694. delete opt.splitList;
  76695. }
  76696. var pieces = opt.pieces;
  76697. if (pieces && isArray(pieces)) {
  76698. each$h(pieces, function (piece) {
  76699. if (isObject(piece)) {
  76700. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  76701. piece.min = piece.start;
  76702. }
  76703. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  76704. piece.max = piece.end;
  76705. }
  76706. }
  76707. });
  76708. }
  76709. });
  76710. }
  76711. function has$1(obj, name) {
  76712. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  76713. }
  76714. var installed$1 = false;
  76715. function installCommon$1(registers) {
  76716. if (installed$1) {
  76717. return;
  76718. }
  76719. installed$1 = true;
  76720. registers.registerSubTypeDefaulter('visualMap', function (option) {
  76721. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  76722. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  76723. });
  76724. registers.registerAction(visualMapActionInfo, visualMapActionHander);
  76725. each(visualMapEncodingHandlers, function (handler) {
  76726. registers.registerVisual(registers.PRIORITY.VISUAL.COMPONENT, handler);
  76727. });
  76728. registers.registerPreprocessor(visualMapPreprocessor);
  76729. }
  76730. function install$N(registers) {
  76731. registers.registerComponentModel(ContinuousModel);
  76732. registers.registerComponentView(ContinuousView);
  76733. installCommon$1(registers);
  76734. }
  76735. var PiecewiseModel =
  76736. /** @class */
  76737. function (_super) {
  76738. __extends(PiecewiseModel, _super);
  76739. function PiecewiseModel() {
  76740. var _this = _super !== null && _super.apply(this, arguments) || this;
  76741. _this.type = PiecewiseModel.type;
  76742. /**
  76743. * The order is always [low, ..., high].
  76744. * [{text: string, interval: Array.<number>}, ...]
  76745. */
  76746. _this._pieceList = [];
  76747. return _this;
  76748. }
  76749. PiecewiseModel.prototype.optionUpdated = function (newOption, isInit) {
  76750. _super.prototype.optionUpdated.apply(this, arguments);
  76751. this.resetExtent();
  76752. var mode = this._mode = this._determineMode();
  76753. this._pieceList = [];
  76754. resetMethods[this._mode].call(this, this._pieceList);
  76755. this._resetSelected(newOption, isInit);
  76756. var categories = this.option.categories;
  76757. this.resetVisual(function (mappingOption, state) {
  76758. if (mode === 'categories') {
  76759. mappingOption.mappingMethod = 'category';
  76760. mappingOption.categories = clone(categories);
  76761. } else {
  76762. mappingOption.dataExtent = this.getExtent();
  76763. mappingOption.mappingMethod = 'piecewise';
  76764. mappingOption.pieceList = map(this._pieceList, function (piece) {
  76765. piece = clone(piece);
  76766. if (state !== 'inRange') {
  76767. // FIXME
  76768. // outOfRange do not support special visual in pieces.
  76769. piece.visual = null;
  76770. }
  76771. return piece;
  76772. });
  76773. }
  76774. });
  76775. };
  76776. /**
  76777. * @protected
  76778. * @override
  76779. */
  76780. PiecewiseModel.prototype.completeVisualOption = function () {
  76781. // Consider this case:
  76782. // visualMap: {
  76783. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  76784. // }
  76785. // where no inRange/outOfRange set but only pieces. So we should make
  76786. // default inRange/outOfRange for this case, otherwise visuals that only
  76787. // appear in `pieces` will not be taken into account in visual encoding.
  76788. var option = this.option;
  76789. var visualTypesInPieces = {};
  76790. var visualTypes = VisualMapping.listVisualTypes();
  76791. var isCategory = this.isCategory();
  76792. each(option.pieces, function (piece) {
  76793. each(visualTypes, function (visualType) {
  76794. if (piece.hasOwnProperty(visualType)) {
  76795. visualTypesInPieces[visualType] = 1;
  76796. }
  76797. });
  76798. });
  76799. each(visualTypesInPieces, function (v, visualType) {
  76800. var exists = false;
  76801. each(this.stateList, function (state) {
  76802. exists = exists || has(option, state, visualType) || has(option.target, state, visualType);
  76803. }, this);
  76804. !exists && each(this.stateList, function (state) {
  76805. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  76806. });
  76807. }, this);
  76808. function has(obj, state, visualType) {
  76809. return obj && obj[state] && obj[state].hasOwnProperty(visualType);
  76810. }
  76811. _super.prototype.completeVisualOption.apply(this, arguments);
  76812. };
  76813. PiecewiseModel.prototype._resetSelected = function (newOption, isInit) {
  76814. var thisOption = this.option;
  76815. var pieceList = this._pieceList; // Selected do not merge but all override.
  76816. var selected = (isInit ? thisOption : newOption).selected || {};
  76817. thisOption.selected = selected; // Consider 'not specified' means true.
  76818. each(pieceList, function (piece, index) {
  76819. var key = this.getSelectedMapKey(piece);
  76820. if (!selected.hasOwnProperty(key)) {
  76821. selected[key] = true;
  76822. }
  76823. }, this);
  76824. if (thisOption.selectedMode === 'single') {
  76825. // Ensure there is only one selected.
  76826. var hasSel_1 = false;
  76827. each(pieceList, function (piece, index) {
  76828. var key = this.getSelectedMapKey(piece);
  76829. if (selected[key]) {
  76830. hasSel_1 ? selected[key] = false : hasSel_1 = true;
  76831. }
  76832. }, this);
  76833. } // thisOption.selectedMode === 'multiple', default: all selected.
  76834. };
  76835. /**
  76836. * @public
  76837. */
  76838. PiecewiseModel.prototype.getSelectedMapKey = function (piece) {
  76839. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  76840. };
  76841. /**
  76842. * @public
  76843. */
  76844. PiecewiseModel.prototype.getPieceList = function () {
  76845. return this._pieceList;
  76846. };
  76847. /**
  76848. * @return {string}
  76849. */
  76850. PiecewiseModel.prototype._determineMode = function () {
  76851. var option = this.option;
  76852. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  76853. };
  76854. /**
  76855. * @override
  76856. */
  76857. PiecewiseModel.prototype.setSelected = function (selected) {
  76858. this.option.selected = clone(selected);
  76859. };
  76860. /**
  76861. * @override
  76862. */
  76863. PiecewiseModel.prototype.getValueState = function (value) {
  76864. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  76865. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  76866. };
  76867. /**
  76868. * @public
  76869. * @param pieceIndex piece index in visualMapModel.getPieceList()
  76870. */
  76871. PiecewiseModel.prototype.findTargetDataIndices = function (pieceIndex) {
  76872. var result = [];
  76873. var pieceList = this._pieceList;
  76874. this.eachTargetSeries(function (seriesModel) {
  76875. var dataIndices = [];
  76876. var data = seriesModel.getData();
  76877. data.each(this.getDataDimension(data), function (value, dataIndex) {
  76878. // Should always base on model pieceList, because it is order sensitive.
  76879. var pIdx = VisualMapping.findPieceIndex(value, pieceList);
  76880. pIdx === pieceIndex && dataIndices.push(dataIndex);
  76881. }, this);
  76882. result.push({
  76883. seriesId: seriesModel.id,
  76884. dataIndex: dataIndices
  76885. });
  76886. }, this);
  76887. return result;
  76888. };
  76889. /**
  76890. * @private
  76891. * @param piece piece.value or piece.interval is required.
  76892. * @return Can be Infinity or -Infinity
  76893. */
  76894. PiecewiseModel.prototype.getRepresentValue = function (piece) {
  76895. var representValue;
  76896. if (this.isCategory()) {
  76897. representValue = piece.value;
  76898. } else {
  76899. if (piece.value != null) {
  76900. representValue = piece.value;
  76901. } else {
  76902. var pieceInterval = piece.interval || [];
  76903. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  76904. }
  76905. }
  76906. return representValue;
  76907. };
  76908. PiecewiseModel.prototype.getVisualMeta = function (getColorVisual) {
  76909. // Do not support category. (category axis is ordinal, numerical)
  76910. if (this.isCategory()) {
  76911. return;
  76912. }
  76913. var stops = [];
  76914. var outerColors = ['', ''];
  76915. var visualMapModel = this;
  76916. function setStop(interval, valueState) {
  76917. var representValue = visualMapModel.getRepresentValue({
  76918. interval: interval
  76919. }); // Not category
  76920. if (!valueState) {
  76921. valueState = visualMapModel.getValueState(representValue);
  76922. }
  76923. var color = getColorVisual(representValue, valueState);
  76924. if (interval[0] === -Infinity) {
  76925. outerColors[0] = color;
  76926. } else if (interval[1] === Infinity) {
  76927. outerColors[1] = color;
  76928. } else {
  76929. stops.push({
  76930. value: interval[0],
  76931. color: color
  76932. }, {
  76933. value: interval[1],
  76934. color: color
  76935. });
  76936. }
  76937. } // Suplement
  76938. var pieceList = this._pieceList.slice();
  76939. if (!pieceList.length) {
  76940. pieceList.push({
  76941. interval: [-Infinity, Infinity]
  76942. });
  76943. } else {
  76944. var edge = pieceList[0].interval[0];
  76945. edge !== -Infinity && pieceList.unshift({
  76946. interval: [-Infinity, edge]
  76947. });
  76948. edge = pieceList[pieceList.length - 1].interval[1];
  76949. edge !== Infinity && pieceList.push({
  76950. interval: [edge, Infinity]
  76951. });
  76952. }
  76953. var curr = -Infinity;
  76954. each(pieceList, function (piece) {
  76955. var interval = piece.interval;
  76956. if (interval) {
  76957. // Fulfill gap.
  76958. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  76959. setStop(interval.slice());
  76960. curr = interval[1];
  76961. }
  76962. }, this);
  76963. return {
  76964. stops: stops,
  76965. outerColors: outerColors
  76966. };
  76967. };
  76968. PiecewiseModel.type = 'visualMap.piecewise';
  76969. PiecewiseModel.defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, {
  76970. selected: null,
  76971. minOpen: false,
  76972. maxOpen: false,
  76973. align: 'auto',
  76974. itemWidth: 20,
  76975. itemHeight: 14,
  76976. itemSymbol: 'roundRect',
  76977. pieces: null,
  76978. categories: null,
  76979. splitNumber: 5,
  76980. selectedMode: 'multiple',
  76981. itemGap: 10,
  76982. hoverLink: true // Enable hover highlight.
  76983. });
  76984. return PiecewiseModel;
  76985. }(VisualMapModel);
  76986. /**
  76987. * Key is this._mode
  76988. * @type {Object}
  76989. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  76990. */
  76991. var resetMethods = {
  76992. splitNumber: function (outPieceList) {
  76993. var thisOption = this.option;
  76994. var precision = Math.min(thisOption.precision, 20);
  76995. var dataExtent = this.getExtent();
  76996. var splitNumber = thisOption.splitNumber;
  76997. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  76998. thisOption.splitNumber = splitNumber;
  76999. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  77000. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  77001. precision++;
  77002. }
  77003. thisOption.precision = precision;
  77004. splitStep = +splitStep.toFixed(precision);
  77005. if (thisOption.minOpen) {
  77006. outPieceList.push({
  77007. interval: [-Infinity, dataExtent[0]],
  77008. close: [0, 0]
  77009. });
  77010. }
  77011. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  77012. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  77013. outPieceList.push({
  77014. interval: [curr, max],
  77015. close: [1, 1]
  77016. });
  77017. }
  77018. if (thisOption.maxOpen) {
  77019. outPieceList.push({
  77020. interval: [dataExtent[1], Infinity],
  77021. close: [0, 0]
  77022. });
  77023. }
  77024. reformIntervals(outPieceList);
  77025. each(outPieceList, function (piece, index) {
  77026. piece.index = index;
  77027. piece.text = this.formatValueText(piece.interval);
  77028. }, this);
  77029. },
  77030. categories: function (outPieceList) {
  77031. var thisOption = this.option;
  77032. each(thisOption.categories, function (cate) {
  77033. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  77034. // 是否改一致。
  77035. outPieceList.push({
  77036. text: this.formatValueText(cate, true),
  77037. value: cate
  77038. });
  77039. }, this); // See "Order Rule".
  77040. normalizeReverse(thisOption, outPieceList);
  77041. },
  77042. pieces: function (outPieceList) {
  77043. var thisOption = this.option;
  77044. each(thisOption.pieces, function (pieceListItem, index) {
  77045. if (!isObject(pieceListItem)) {
  77046. pieceListItem = {
  77047. value: pieceListItem
  77048. };
  77049. }
  77050. var item = {
  77051. text: '',
  77052. index: index
  77053. };
  77054. if (pieceListItem.label != null) {
  77055. item.text = pieceListItem.label;
  77056. }
  77057. if (pieceListItem.hasOwnProperty('value')) {
  77058. var value = item.value = pieceListItem.value;
  77059. item.interval = [value, value];
  77060. item.close = [1, 1];
  77061. } else {
  77062. // `min` `max` is legacy option.
  77063. // `lt` `gt` `lte` `gte` is recommanded.
  77064. var interval = item.interval = [];
  77065. var close_1 = item.close = [0, 0];
  77066. var closeList = [1, 0, 1];
  77067. var infinityList = [-Infinity, Infinity];
  77068. var useMinMax = [];
  77069. for (var lg = 0; lg < 2; lg++) {
  77070. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  77071. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  77072. interval[lg] = pieceListItem[names[i]];
  77073. close_1[lg] = closeList[i];
  77074. useMinMax[lg] = i === 2;
  77075. }
  77076. interval[lg] == null && (interval[lg] = infinityList[lg]);
  77077. }
  77078. useMinMax[0] && interval[1] === Infinity && (close_1[0] = 0);
  77079. useMinMax[1] && interval[0] === -Infinity && (close_1[1] = 0);
  77080. if ("development" !== 'production') {
  77081. if (interval[0] > interval[1]) {
  77082. console.warn('Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.');
  77083. }
  77084. }
  77085. if (interval[0] === interval[1] && close_1[0] && close_1[1]) {
  77086. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  77087. // we use value to lift the priority when min === max
  77088. item.value = interval[0];
  77089. }
  77090. }
  77091. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  77092. outPieceList.push(item);
  77093. }, this); // See "Order Rule".
  77094. normalizeReverse(thisOption, outPieceList); // Only pieces
  77095. reformIntervals(outPieceList);
  77096. each(outPieceList, function (piece) {
  77097. var close = piece.close;
  77098. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  77099. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  77100. }, this);
  77101. }
  77102. };
  77103. function normalizeReverse(thisOption, pieceList) {
  77104. var inverse = thisOption.inverse;
  77105. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  77106. pieceList.reverse();
  77107. }
  77108. }
  77109. var PiecewiseVisualMapView =
  77110. /** @class */
  77111. function (_super) {
  77112. __extends(PiecewiseVisualMapView, _super);
  77113. function PiecewiseVisualMapView() {
  77114. var _this = _super !== null && _super.apply(this, arguments) || this;
  77115. _this.type = PiecewiseVisualMapView.type;
  77116. return _this;
  77117. }
  77118. PiecewiseVisualMapView.prototype.doRender = function () {
  77119. var thisGroup = this.group;
  77120. thisGroup.removeAll();
  77121. var visualMapModel = this.visualMapModel;
  77122. var textGap = visualMapModel.get('textGap');
  77123. var textStyleModel = visualMapModel.textStyleModel;
  77124. var textFont = textStyleModel.getFont();
  77125. var textFill = textStyleModel.getTextColor();
  77126. var itemAlign = this._getItemAlign();
  77127. var itemSize = visualMapModel.itemSize;
  77128. var viewData = this._getViewData();
  77129. var endsText = viewData.endsText;
  77130. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  77131. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  77132. each(viewData.viewPieceList, function (item) {
  77133. var piece = item.piece;
  77134. var itemGroup = new Group();
  77135. itemGroup.onclick = bind(this._onItemClick, this, piece);
  77136. this._enableHoverLink(itemGroup, item.indexInModelPieceList); // TODO Category
  77137. var representValue = visualMapModel.getRepresentValue(piece);
  77138. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  77139. if (showLabel) {
  77140. var visualState = this.visualMapModel.getValueState(representValue);
  77141. itemGroup.add(new ZRText({
  77142. style: {
  77143. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  77144. y: itemSize[1] / 2,
  77145. text: piece.text,
  77146. verticalAlign: 'middle',
  77147. align: itemAlign,
  77148. font: textFont,
  77149. fill: textFill,
  77150. opacity: visualState === 'outOfRange' ? 0.5 : 1
  77151. }
  77152. }));
  77153. }
  77154. thisGroup.add(itemGroup);
  77155. }, this);
  77156. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  77157. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  77158. this.renderBackground(thisGroup);
  77159. this.positionGroup(thisGroup);
  77160. };
  77161. PiecewiseVisualMapView.prototype._enableHoverLink = function (itemGroup, pieceIndex) {
  77162. var _this = this;
  77163. itemGroup.on('mouseover', function () {
  77164. return onHoverLink('highlight');
  77165. }).on('mouseout', function () {
  77166. return onHoverLink('downplay');
  77167. });
  77168. var onHoverLink = function (method) {
  77169. var visualMapModel = _this.visualMapModel; // TODO: TYPE More detailed action types
  77170. visualMapModel.option.hoverLink && _this.api.dispatchAction({
  77171. type: method,
  77172. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  77173. });
  77174. };
  77175. };
  77176. PiecewiseVisualMapView.prototype._getItemAlign = function () {
  77177. var visualMapModel = this.visualMapModel;
  77178. var modelOption = visualMapModel.option;
  77179. if (modelOption.orient === 'vertical') {
  77180. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  77181. } else {
  77182. // horizontal, most case left unless specifying right.
  77183. var align = modelOption.align;
  77184. if (!align || align === 'auto') {
  77185. align = 'left';
  77186. }
  77187. return align;
  77188. }
  77189. };
  77190. PiecewiseVisualMapView.prototype._renderEndsText = function (group, text, itemSize, showLabel, itemAlign) {
  77191. if (!text) {
  77192. return;
  77193. }
  77194. var itemGroup = new Group();
  77195. var textStyleModel = this.visualMapModel.textStyleModel;
  77196. itemGroup.add(new ZRText({
  77197. style: {
  77198. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  77199. y: itemSize[1] / 2,
  77200. verticalAlign: 'middle',
  77201. align: showLabel ? itemAlign : 'center',
  77202. text: text,
  77203. font: textStyleModel.getFont(),
  77204. fill: textStyleModel.getTextColor()
  77205. }
  77206. }));
  77207. group.add(itemGroup);
  77208. };
  77209. /**
  77210. * @private
  77211. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  77212. */
  77213. PiecewiseVisualMapView.prototype._getViewData = function () {
  77214. var visualMapModel = this.visualMapModel;
  77215. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  77216. return {
  77217. piece: piece,
  77218. indexInModelPieceList: index
  77219. };
  77220. });
  77221. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  77222. var orient = visualMapModel.get('orient');
  77223. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  77224. if (orient === 'horizontal' ? inverse : !inverse) {
  77225. viewPieceList.reverse();
  77226. } // Origin order of endsText is [high, low]
  77227. else if (endsText) {
  77228. endsText = endsText.slice().reverse();
  77229. }
  77230. return {
  77231. viewPieceList: viewPieceList,
  77232. endsText: endsText
  77233. };
  77234. };
  77235. PiecewiseVisualMapView.prototype._createItemSymbol = function (group, representValue, shapeParam) {
  77236. group.add(createSymbol( // symbol will be string
  77237. this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], // color will be string
  77238. this.getControllerVisual(representValue, 'color')));
  77239. };
  77240. PiecewiseVisualMapView.prototype._onItemClick = function (piece) {
  77241. var visualMapModel = this.visualMapModel;
  77242. var option = visualMapModel.option;
  77243. var selected = clone(option.selected);
  77244. var newKey = visualMapModel.getSelectedMapKey(piece);
  77245. if (option.selectedMode === 'single') {
  77246. selected[newKey] = true;
  77247. each(selected, function (o, key) {
  77248. selected[key] = key === newKey;
  77249. });
  77250. } else {
  77251. selected[newKey] = !selected[newKey];
  77252. }
  77253. this.api.dispatchAction({
  77254. type: 'selectDataRange',
  77255. from: this.uid,
  77256. visualMapId: this.visualMapModel.id,
  77257. selected: selected
  77258. });
  77259. };
  77260. PiecewiseVisualMapView.type = 'visualMap.piecewise';
  77261. return PiecewiseVisualMapView;
  77262. }(VisualMapView);
  77263. function install$O(registers) {
  77264. registers.registerComponentModel(PiecewiseModel);
  77265. registers.registerComponentView(PiecewiseVisualMapView);
  77266. installCommon$1(registers);
  77267. }
  77268. function install$P(registers) {
  77269. use(install$N);
  77270. use(install$O); // Do not install './dataZoomSelect',
  77271. // since it only work for toolbox dataZoom.
  77272. }
  77273. var DEFAULT_OPTION = {
  77274. label: {
  77275. enabled: true
  77276. },
  77277. decal: {
  77278. show: false
  77279. }
  77280. };
  77281. var inner$n = makeInner();
  77282. var decalPaletteScope = {};
  77283. function ariaVisual(ecModel, api) {
  77284. var ariaModel = ecModel.getModel('aria'); // See "area enabled" detection code in `GlobalModel.ts`.
  77285. if (!ariaModel.get('enabled')) {
  77286. return;
  77287. }
  77288. var defaultOption = clone(DEFAULT_OPTION);
  77289. merge(defaultOption.label, ecModel.getLocaleModel().get('aria'), false);
  77290. merge(ariaModel.option, defaultOption, false);
  77291. setDecal();
  77292. setLabel();
  77293. function setDecal() {
  77294. var decalModel = ariaModel.getModel('decal');
  77295. var useDecal = decalModel.get('show');
  77296. if (useDecal) {
  77297. // Each type of series use one scope.
  77298. // Pie and funnel are using diferrent scopes
  77299. var paletteScopeGroupByType_1 = createHashMap();
  77300. ecModel.eachSeries(function (seriesModel) {
  77301. if (!seriesModel.useColorPaletteOnData) {
  77302. return;
  77303. }
  77304. var decalScope = paletteScopeGroupByType_1.get(seriesModel.type);
  77305. if (!decalScope) {
  77306. decalScope = {};
  77307. paletteScopeGroupByType_1.set(seriesModel.type, decalScope);
  77308. }
  77309. inner$n(seriesModel).scope = decalScope;
  77310. });
  77311. ecModel.eachRawSeries(function (seriesModel) {
  77312. if (ecModel.isSeriesFiltered(seriesModel)) {
  77313. return;
  77314. }
  77315. if (typeof seriesModel.enableAriaDecal === 'function') {
  77316. // Let series define how to use decal palette on data
  77317. seriesModel.enableAriaDecal();
  77318. return;
  77319. }
  77320. var data = seriesModel.getData();
  77321. if (seriesModel.useColorPaletteOnData) {
  77322. var dataAll_1 = seriesModel.getRawData();
  77323. var idxMap_1 = {};
  77324. var decalScope_1 = inner$n(seriesModel).scope;
  77325. data.each(function (idx) {
  77326. var rawIdx = data.getRawIndex(idx);
  77327. idxMap_1[rawIdx] = idx;
  77328. });
  77329. var dataCount_1 = dataAll_1.count();
  77330. dataAll_1.each(function (rawIdx) {
  77331. var idx = idxMap_1[rawIdx];
  77332. var name = dataAll_1.getName(rawIdx) || rawIdx + '';
  77333. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, name, decalScope_1, dataCount_1);
  77334. var specifiedDecal = data.getItemVisual(idx, 'decal');
  77335. data.setItemVisual(idx, 'decal', mergeDecal(specifiedDecal, paletteDecal));
  77336. });
  77337. } else {
  77338. var paletteDecal = getDecalFromPalette(seriesModel.ecModel, seriesModel.name, decalPaletteScope, ecModel.getSeriesCount());
  77339. var specifiedDecal = data.getVisual('decal');
  77340. data.setVisual('decal', mergeDecal(specifiedDecal, paletteDecal));
  77341. }
  77342. function mergeDecal(specifiedDecal, paletteDecal) {
  77343. // Merge decal from palette to decal from itemStyle.
  77344. // User do not need to specify all of the decal props.
  77345. var resultDecal = specifiedDecal ? extend(extend({}, paletteDecal), specifiedDecal) : paletteDecal;
  77346. resultDecal.dirty = true;
  77347. return resultDecal;
  77348. }
  77349. });
  77350. }
  77351. }
  77352. function setLabel() {
  77353. var labelLocale = ecModel.getLocaleModel().get('aria');
  77354. var labelModel = ariaModel.getModel('label');
  77355. labelModel.option = defaults(labelModel.option, labelLocale);
  77356. if (!labelModel.get('enabled')) {
  77357. return;
  77358. }
  77359. var dom = api.getZr().dom;
  77360. if (labelModel.get('description')) {
  77361. dom.setAttribute('aria-label', labelModel.get('description'));
  77362. return;
  77363. }
  77364. var seriesCnt = ecModel.getSeriesCount();
  77365. var maxDataCnt = labelModel.get(['data', 'maxCount']) || 10;
  77366. var maxSeriesCnt = labelModel.get(['series', 'maxCount']) || 10;
  77367. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  77368. var ariaLabel;
  77369. if (seriesCnt < 1) {
  77370. // No series, no aria label
  77371. return;
  77372. } else {
  77373. var title = getTitle();
  77374. if (title) {
  77375. var withTitle = labelModel.get(['general', 'withTitle']);
  77376. ariaLabel = replace(withTitle, {
  77377. title: title
  77378. });
  77379. } else {
  77380. ariaLabel = labelModel.get(['general', 'withoutTitle']);
  77381. }
  77382. var seriesLabels_1 = [];
  77383. var prefix = seriesCnt > 1 ? labelModel.get(['series', 'multiple', 'prefix']) : labelModel.get(['series', 'single', 'prefix']);
  77384. ariaLabel += replace(prefix, {
  77385. seriesCount: seriesCnt
  77386. });
  77387. ecModel.eachSeries(function (seriesModel, idx) {
  77388. if (idx < displaySeriesCnt) {
  77389. var seriesLabel = void 0;
  77390. var seriesName = seriesModel.get('name');
  77391. var withName = seriesName ? 'withName' : 'withoutName';
  77392. seriesLabel = seriesCnt > 1 ? labelModel.get(['series', 'multiple', withName]) : labelModel.get(['series', 'single', withName]);
  77393. seriesLabel = replace(seriesLabel, {
  77394. seriesId: seriesModel.seriesIndex,
  77395. seriesName: seriesModel.get('name'),
  77396. seriesType: getSeriesTypeName(seriesModel.subType)
  77397. });
  77398. var data = seriesModel.getData();
  77399. if (data.count() > maxDataCnt) {
  77400. // Show part of data
  77401. var partialLabel = labelModel.get(['data', 'partialData']);
  77402. seriesLabel += replace(partialLabel, {
  77403. displayCnt: maxDataCnt
  77404. });
  77405. } else {
  77406. seriesLabel += labelModel.get(['data', 'allData']);
  77407. }
  77408. var dataLabels = [];
  77409. for (var i = 0; i < data.count(); i++) {
  77410. if (i < maxDataCnt) {
  77411. var name_1 = data.getName(i);
  77412. var value = retrieveRawValue(data, i);
  77413. var dataLabel = labelModel.get(['data', name_1 ? 'withName' : 'withoutName']);
  77414. dataLabels.push(replace(dataLabel, {
  77415. name: name_1,
  77416. value: value
  77417. }));
  77418. }
  77419. }
  77420. var middleSeparator_1 = labelModel.get(['data', 'separator', 'middle']);
  77421. var endSeparator_1 = labelModel.get(['data', 'separator', 'end']);
  77422. seriesLabel += dataLabels.join(middleSeparator_1) + endSeparator_1;
  77423. seriesLabels_1.push(seriesLabel);
  77424. }
  77425. });
  77426. var separatorModel = labelModel.getModel(['series', 'multiple', 'separator']);
  77427. var middleSeparator = separatorModel.get('middle');
  77428. var endSeparator = separatorModel.get('end');
  77429. ariaLabel += seriesLabels_1.join(middleSeparator) + endSeparator;
  77430. dom.setAttribute('aria-label', ariaLabel);
  77431. }
  77432. }
  77433. function replace(str, keyValues) {
  77434. if (typeof str !== 'string') {
  77435. return str;
  77436. }
  77437. var result = str;
  77438. each(keyValues, function (value, key) {
  77439. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  77440. });
  77441. return result;
  77442. }
  77443. function getTitle() {
  77444. var title = ecModel.get('title');
  77445. if (title && title.length) {
  77446. title = title[0];
  77447. }
  77448. return title && title.text;
  77449. }
  77450. function getSeriesTypeName(type) {
  77451. return ecModel.getLocaleModel().get(['series', 'typeNames'])[type] || '自定义图';
  77452. }
  77453. }
  77454. function ariaPreprocessor(option) {
  77455. if (!option || !option.aria) {
  77456. return;
  77457. }
  77458. var aria = option.aria; // aria.show is deprecated and should use aria.enabled instead
  77459. if (aria.show != null) {
  77460. aria.enabled = aria.show;
  77461. }
  77462. aria.label = aria.label || {}; // move description, general, series, data to be under aria.label
  77463. each(['description', 'general', 'series', 'data'], function (name) {
  77464. if (aria[name] != null) {
  77465. aria.label[name] = aria[name];
  77466. }
  77467. });
  77468. }
  77469. function install$Q(registers) {
  77470. registers.registerPreprocessor(ariaPreprocessor);
  77471. registers.registerVisual(registers.PRIORITY.VISUAL.ARIA, ariaVisual);
  77472. }
  77473. var RELATIONAL_EXPRESSION_OP_ALIAS_MAP = {
  77474. value: 'eq',
  77475. // PENDING: not good for literal semantic?
  77476. '<': 'lt',
  77477. '<=': 'lte',
  77478. '>': 'gt',
  77479. '>=': 'gte',
  77480. '=': 'eq',
  77481. '!=': 'ne',
  77482. '<>': 'ne' // Might mileading for sake of the different between '==' and '===',
  77483. // So dont support them.
  77484. // '==': 'eq',
  77485. // '===': 'seq',
  77486. // '!==': 'sne'
  77487. // PENDING: Whether support some common alias "ge", "le", "neq"?
  77488. // ge: 'gte',
  77489. // le: 'lte',
  77490. // neq: 'ne',
  77491. };
  77492. var RegExpEvaluator =
  77493. /** @class */
  77494. function () {
  77495. function RegExpEvaluator(rVal) {
  77496. // Support condVal: RegExp | string
  77497. var condValue = this._condVal = isString(rVal) ? new RegExp(rVal) : isRegExp(rVal) ? rVal : null;
  77498. if (condValue == null) {
  77499. var errMsg = '';
  77500. if ("development" !== 'production') {
  77501. errMsg = makePrintable('Illegal regexp', rVal, 'in');
  77502. }
  77503. throwError(errMsg);
  77504. }
  77505. }
  77506. RegExpEvaluator.prototype.evaluate = function (lVal) {
  77507. var type = typeof lVal;
  77508. return type === 'string' ? this._condVal.test(lVal) : type === 'number' ? this._condVal.test(lVal + '') : false;
  77509. };
  77510. return RegExpEvaluator;
  77511. }();
  77512. var ConstConditionInternal =
  77513. /** @class */
  77514. function () {
  77515. function ConstConditionInternal() {}
  77516. ConstConditionInternal.prototype.evaluate = function () {
  77517. return this.value;
  77518. };
  77519. return ConstConditionInternal;
  77520. }();
  77521. var AndConditionInternal =
  77522. /** @class */
  77523. function () {
  77524. function AndConditionInternal() {}
  77525. AndConditionInternal.prototype.evaluate = function () {
  77526. var children = this.children;
  77527. for (var i = 0; i < children.length; i++) {
  77528. if (!children[i].evaluate()) {
  77529. return false;
  77530. }
  77531. }
  77532. return true;
  77533. };
  77534. return AndConditionInternal;
  77535. }();
  77536. var OrConditionInternal =
  77537. /** @class */
  77538. function () {
  77539. function OrConditionInternal() {}
  77540. OrConditionInternal.prototype.evaluate = function () {
  77541. var children = this.children;
  77542. for (var i = 0; i < children.length; i++) {
  77543. if (children[i].evaluate()) {
  77544. return true;
  77545. }
  77546. }
  77547. return false;
  77548. };
  77549. return OrConditionInternal;
  77550. }();
  77551. var NotConditionInternal =
  77552. /** @class */
  77553. function () {
  77554. function NotConditionInternal() {}
  77555. NotConditionInternal.prototype.evaluate = function () {
  77556. return !this.child.evaluate();
  77557. };
  77558. return NotConditionInternal;
  77559. }();
  77560. var RelationalConditionInternal =
  77561. /** @class */
  77562. function () {
  77563. function RelationalConditionInternal() {}
  77564. RelationalConditionInternal.prototype.evaluate = function () {
  77565. var needParse = !!this.valueParser; // Call getValue with no `this`.
  77566. var getValue = this.getValue;
  77567. var tarValRaw = getValue(this.valueGetterParam);
  77568. var tarValParsed = needParse ? this.valueParser(tarValRaw) : null; // Relational cond follow "and" logic internally.
  77569. for (var i = 0; i < this.subCondList.length; i++) {
  77570. if (!this.subCondList[i].evaluate(needParse ? tarValParsed : tarValRaw)) {
  77571. return false;
  77572. }
  77573. }
  77574. return true;
  77575. };
  77576. return RelationalConditionInternal;
  77577. }();
  77578. function parseOption(exprOption, getters) {
  77579. if (exprOption === true || exprOption === false) {
  77580. var cond = new ConstConditionInternal();
  77581. cond.value = exprOption;
  77582. return cond;
  77583. }
  77584. var errMsg = '';
  77585. if (!isObjectNotArray(exprOption)) {
  77586. if ("development" !== 'production') {
  77587. errMsg = makePrintable('Illegal config. Expect a plain object but actually', exprOption);
  77588. }
  77589. throwError(errMsg);
  77590. }
  77591. if (exprOption.and) {
  77592. return parseAndOrOption('and', exprOption, getters);
  77593. } else if (exprOption.or) {
  77594. return parseAndOrOption('or', exprOption, getters);
  77595. } else if (exprOption.not) {
  77596. return parseNotOption(exprOption, getters);
  77597. }
  77598. return parseRelationalOption(exprOption, getters);
  77599. }
  77600. function parseAndOrOption(op, exprOption, getters) {
  77601. var subOptionArr = exprOption[op];
  77602. var errMsg = '';
  77603. if ("development" !== 'production') {
  77604. errMsg = makePrintable('"and"/"or" condition should only be `' + op + ': [...]` and must not be empty array.', 'Illegal condition:', exprOption);
  77605. }
  77606. if (!isArray(subOptionArr)) {
  77607. throwError(errMsg);
  77608. }
  77609. if (!subOptionArr.length) {
  77610. throwError(errMsg);
  77611. }
  77612. var cond = op === 'and' ? new AndConditionInternal() : new OrConditionInternal();
  77613. cond.children = map(subOptionArr, function (subOption) {
  77614. return parseOption(subOption, getters);
  77615. });
  77616. if (!cond.children.length) {
  77617. throwError(errMsg);
  77618. }
  77619. return cond;
  77620. }
  77621. function parseNotOption(exprOption, getters) {
  77622. var subOption = exprOption.not;
  77623. var errMsg = '';
  77624. if ("development" !== 'production') {
  77625. errMsg = makePrintable('"not" condition should only be `not: {}`.', 'Illegal condition:', exprOption);
  77626. }
  77627. if (!isObjectNotArray(subOption)) {
  77628. throwError(errMsg);
  77629. }
  77630. var cond = new NotConditionInternal();
  77631. cond.child = parseOption(subOption, getters);
  77632. if (!cond.child) {
  77633. throwError(errMsg);
  77634. }
  77635. return cond;
  77636. }
  77637. function parseRelationalOption(exprOption, getters) {
  77638. var errMsg = '';
  77639. var valueGetterParam = getters.prepareGetValue(exprOption);
  77640. var subCondList = [];
  77641. var exprKeys = keys(exprOption);
  77642. var parserName = exprOption.parser;
  77643. var valueParser = parserName ? getRawValueParser(parserName) : null;
  77644. for (var i = 0; i < exprKeys.length; i++) {
  77645. var keyRaw = exprKeys[i];
  77646. if (keyRaw === 'parser' || getters.valueGetterAttrMap.get(keyRaw)) {
  77647. continue;
  77648. }
  77649. var op = hasOwn(RELATIONAL_EXPRESSION_OP_ALIAS_MAP, keyRaw) ? RELATIONAL_EXPRESSION_OP_ALIAS_MAP[keyRaw] : keyRaw;
  77650. var condValueRaw = exprOption[keyRaw];
  77651. var condValueParsed = valueParser ? valueParser(condValueRaw) : condValueRaw;
  77652. var evaluator = createFilterComparator(op, condValueParsed) || op === 'reg' && new RegExpEvaluator(condValueParsed);
  77653. if (!evaluator) {
  77654. if ("development" !== 'production') {
  77655. errMsg = makePrintable('Illegal relational operation: "' + keyRaw + '" in condition:', exprOption);
  77656. }
  77657. throwError(errMsg);
  77658. }
  77659. subCondList.push(evaluator);
  77660. }
  77661. if (!subCondList.length) {
  77662. if ("development" !== 'production') {
  77663. errMsg = makePrintable('Relational condition must have at least one operator.', 'Illegal condition:', exprOption);
  77664. } // No relational operator always disabled in case of dangers result.
  77665. throwError(errMsg);
  77666. }
  77667. var cond = new RelationalConditionInternal();
  77668. cond.valueGetterParam = valueGetterParam;
  77669. cond.valueParser = valueParser;
  77670. cond.getValue = getters.getValue;
  77671. cond.subCondList = subCondList;
  77672. return cond;
  77673. }
  77674. function isObjectNotArray(val) {
  77675. return isObject(val) && !isArrayLike(val);
  77676. }
  77677. var ConditionalExpressionParsed =
  77678. /** @class */
  77679. function () {
  77680. function ConditionalExpressionParsed(exprOption, getters) {
  77681. this._cond = parseOption(exprOption, getters);
  77682. }
  77683. ConditionalExpressionParsed.prototype.evaluate = function () {
  77684. return this._cond.evaluate();
  77685. };
  77686. return ConditionalExpressionParsed;
  77687. }();
  77688. function parseConditionalExpression(exprOption, getters) {
  77689. return new ConditionalExpressionParsed(exprOption, getters);
  77690. }
  77691. var filterTransform = {
  77692. type: 'echarts:filter',
  77693. // PEDING: enhance to filter by index rather than create new data
  77694. transform: function (params) {
  77695. // [Caveat] Fail-Fast:
  77696. // Do not return the whole dataset unless user config indicate it explicitly.
  77697. // For example, if no condition specified by mistake, return an empty result
  77698. // is better than return the entire raw soruce for user to find the mistake.
  77699. var upstream = params.upstream;
  77700. var rawItem;
  77701. var condition = parseConditionalExpression(params.config, {
  77702. valueGetterAttrMap: createHashMap({
  77703. dimension: true
  77704. }),
  77705. prepareGetValue: function (exprOption) {
  77706. var errMsg = '';
  77707. var dimLoose = exprOption.dimension;
  77708. if (!hasOwn(exprOption, 'dimension')) {
  77709. if ("development" !== 'production') {
  77710. errMsg = makePrintable('Relation condition must has prop "dimension" specified.', 'Illegal condition:', exprOption);
  77711. }
  77712. throwError(errMsg);
  77713. }
  77714. var dimInfo = upstream.getDimensionInfo(dimLoose);
  77715. if (!dimInfo) {
  77716. if ("development" !== 'production') {
  77717. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal condition:', exprOption, '.\n');
  77718. }
  77719. throwError(errMsg);
  77720. }
  77721. return {
  77722. dimIdx: dimInfo.index
  77723. };
  77724. },
  77725. getValue: function (param) {
  77726. return upstream.retrieveValueFromItem(rawItem, param.dimIdx);
  77727. }
  77728. });
  77729. var resultData = [];
  77730. for (var i = 0, len = upstream.count(); i < len; i++) {
  77731. rawItem = upstream.getRawDataItem(i);
  77732. if (condition.evaluate()) {
  77733. resultData.push(rawItem);
  77734. }
  77735. }
  77736. return {
  77737. data: resultData
  77738. };
  77739. }
  77740. };
  77741. var sampleLog = '';
  77742. if ("development" !== 'production') {
  77743. sampleLog = ['Valid config is like:', '{ dimension: "age", order: "asc" }', 'or [{ dimension: "age", order: "asc"], { dimension: "date", order: "desc" }]'].join(' ');
  77744. }
  77745. var sortTransform = {
  77746. type: 'echarts:sort',
  77747. transform: function (params) {
  77748. var upstream = params.upstream;
  77749. var config = params.config;
  77750. var errMsg = ''; // Normalize
  77751. // const orderExprList: OrderExpression[] = isArray(config[0])
  77752. // ? config as OrderExpression[]
  77753. // : [config as OrderExpression];
  77754. var orderExprList = normalizeToArray(config);
  77755. if (!orderExprList.length) {
  77756. if ("development" !== 'production') {
  77757. errMsg = 'Empty `config` in sort transform.';
  77758. }
  77759. throwError(errMsg);
  77760. }
  77761. var orderDefList = [];
  77762. each(orderExprList, function (orderExpr) {
  77763. var dimLoose = orderExpr.dimension;
  77764. var order = orderExpr.order;
  77765. var parserName = orderExpr.parser;
  77766. var incomparable = orderExpr.incomparable;
  77767. if (dimLoose == null) {
  77768. if ("development" !== 'production') {
  77769. errMsg = 'Sort transform config must has "dimension" specified.' + sampleLog;
  77770. }
  77771. throwError(errMsg);
  77772. }
  77773. if (order !== 'asc' && order !== 'desc') {
  77774. if ("development" !== 'production') {
  77775. errMsg = 'Sort transform config must has "order" specified.' + sampleLog;
  77776. }
  77777. throwError(errMsg);
  77778. }
  77779. if (incomparable && incomparable !== 'min' && incomparable !== 'max') {
  77780. var errMsg_1 = '';
  77781. if ("development" !== 'production') {
  77782. errMsg_1 = 'incomparable must be "min" or "max" rather than "' + incomparable + '".';
  77783. }
  77784. throwError(errMsg_1);
  77785. }
  77786. if (order !== 'asc' && order !== 'desc') {
  77787. var errMsg_2 = '';
  77788. if ("development" !== 'production') {
  77789. errMsg_2 = 'order must be "asc" or "desc" rather than "' + order + '".';
  77790. }
  77791. throwError(errMsg_2);
  77792. }
  77793. var dimInfo = upstream.getDimensionInfo(dimLoose);
  77794. if (!dimInfo) {
  77795. if ("development" !== 'production') {
  77796. errMsg = makePrintable('Can not find dimension info via: ' + dimLoose + '.\n', 'Existing dimensions: ', upstream.cloneAllDimensionInfo(), '.\n', 'Illegal config:', orderExpr, '.\n');
  77797. }
  77798. throwError(errMsg);
  77799. }
  77800. var parser = parserName ? getRawValueParser(parserName) : null;
  77801. if (parserName && !parser) {
  77802. if ("development" !== 'production') {
  77803. errMsg = makePrintable('Invalid parser name ' + parserName + '.\n', 'Illegal config:', orderExpr, '.\n');
  77804. }
  77805. throwError(errMsg);
  77806. }
  77807. orderDefList.push({
  77808. dimIdx: dimInfo.index,
  77809. parser: parser,
  77810. comparator: new SortOrderComparator(order, incomparable)
  77811. });
  77812. }); // TODO: support it?
  77813. var sourceFormat = upstream.sourceFormat;
  77814. if (sourceFormat !== SOURCE_FORMAT_ARRAY_ROWS && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  77815. if ("development" !== 'production') {
  77816. errMsg = 'sourceFormat "' + sourceFormat + '" is not supported yet';
  77817. }
  77818. throwError(errMsg);
  77819. } // Other upstream format are all array.
  77820. var resultData = [];
  77821. for (var i = 0, len = upstream.count(); i < len; i++) {
  77822. resultData.push(upstream.getRawDataItem(i));
  77823. }
  77824. resultData.sort(function (item0, item1) {
  77825. for (var i = 0; i < orderDefList.length; i++) {
  77826. var orderDef = orderDefList[i];
  77827. var val0 = upstream.retrieveValueFromItem(item0, orderDef.dimIdx);
  77828. var val1 = upstream.retrieveValueFromItem(item1, orderDef.dimIdx);
  77829. if (orderDef.parser) {
  77830. val0 = orderDef.parser(val0);
  77831. val1 = orderDef.parser(val1);
  77832. }
  77833. var result = orderDef.comparator.evaluate(val0, val1);
  77834. if (result !== 0) {
  77835. return result;
  77836. }
  77837. }
  77838. return 0;
  77839. });
  77840. return {
  77841. data: resultData
  77842. };
  77843. }
  77844. };
  77845. function install$R(registers) {
  77846. registers.registerTransform(filterTransform);
  77847. registers.registerTransform(sortTransform);
  77848. }
  77849. var DatasetModel =
  77850. /** @class */
  77851. function (_super) {
  77852. __extends(DatasetModel, _super);
  77853. function DatasetModel() {
  77854. var _this = _super !== null && _super.apply(this, arguments) || this;
  77855. _this.type = 'dataset';
  77856. return _this;
  77857. }
  77858. DatasetModel.prototype.init = function (option, parentModel, ecModel) {
  77859. _super.prototype.init.call(this, option, parentModel, ecModel);
  77860. this._sourceManager = new SourceManager(this);
  77861. disableTransformOptionMerge(this);
  77862. };
  77863. DatasetModel.prototype.mergeOption = function (newOption, ecModel) {
  77864. _super.prototype.mergeOption.call(this, newOption, ecModel);
  77865. disableTransformOptionMerge(this);
  77866. };
  77867. DatasetModel.prototype.optionUpdated = function () {
  77868. this._sourceManager.dirty();
  77869. };
  77870. DatasetModel.prototype.getSourceManager = function () {
  77871. return this._sourceManager;
  77872. };
  77873. DatasetModel.type = 'dataset';
  77874. DatasetModel.defaultOption = {
  77875. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN
  77876. };
  77877. return DatasetModel;
  77878. }(ComponentModel);
  77879. var DatasetView =
  77880. /** @class */
  77881. function (_super) {
  77882. __extends(DatasetView, _super);
  77883. function DatasetView() {
  77884. var _this = _super !== null && _super.apply(this, arguments) || this;
  77885. _this.type = 'dataset';
  77886. return _this;
  77887. }
  77888. DatasetView.type = 'dataset';
  77889. return DatasetView;
  77890. }(ComponentView);
  77891. function install$S(registers) {
  77892. registers.registerComponentModel(DatasetModel);
  77893. registers.registerComponentView(DatasetView);
  77894. }
  77895. // Render engines
  77896. // -----------------
  77897. // Render via Canvas.
  77898. // echarts.init(dom, null, { renderer: 'canvas' })
  77899. use([install$1]); // Render via SVG.
  77900. // echarts.init(dom, null, { renderer: 'svg' })
  77901. use([install]); // ----------------
  77902. // Charts (series)
  77903. // ----------------
  77904. // All of the series types, for example:
  77905. // chart.setOption({
  77906. // series: [{
  77907. // type: 'line' // or 'bar', 'pie', ...
  77908. // }]
  77909. // });
  77910. 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]); // -------------------
  77911. // Coordinate systems
  77912. // -------------------
  77913. // All of the axis modules have been included in the
  77914. // coordinate system module below, do not need to
  77915. // make extra import.
  77916. // `cartesian` coordinate system. For some historical
  77917. // reasons, it is named as grid, for example:
  77918. // chart.setOption({
  77919. // grid: {...},
  77920. // xAxis: {...},
  77921. // yAxis: {...},
  77922. // series: [{...}]
  77923. // });
  77924. use(install$t); // `polar` coordinate system, for example:
  77925. // chart.setOption({
  77926. // polar: {...},
  77927. // radiusAxis: {...},
  77928. // angleAxis: {...},
  77929. // series: [{
  77930. // coordinateSystem: 'polar'
  77931. // }]
  77932. // });
  77933. use(install$u); // `geo` coordinate system, for example:
  77934. // chart.setOption({
  77935. // geo: {...},
  77936. // series: [{
  77937. // coordinateSystem: 'geo'
  77938. // }]
  77939. // });
  77940. use(install$9); // `singleAxis` coordinate system (notice, it is a coordinate system
  77941. // with only one axis, work for chart like theme river), for example:
  77942. // chart.setOption({
  77943. // singleAxis: {...}
  77944. // series: [{type: 'themeRiver', ...}]
  77945. // });
  77946. use(install$v); // `parallel` coordinate system, only work for parallel series, for example:
  77947. // chart.setOption({
  77948. // parallel: {...},
  77949. // parallelAxis: [{...}, ...],
  77950. // series: [{
  77951. // type: 'parallel'
  77952. // }]
  77953. // });
  77954. use(install$g); // `calendar` coordinate system. for example,
  77955. // chart.setOptionp({
  77956. // calendar: {...},
  77957. // series: [{
  77958. // coordinateSystem: 'calendar'
  77959. // }]
  77960. // );
  77961. use(install$w); // ------------------
  77962. // Other components
  77963. // ------------------
  77964. // `graphic` component, for example:
  77965. // chart.setOption({
  77966. // graphic: {...}
  77967. // });
  77968. use(install$x); // `toolbox` component, for example:
  77969. // chart.setOption({
  77970. // toolbox: {...}
  77971. // });
  77972. use(install$z); // `tooltip` component, for example:
  77973. // chart.setOption({
  77974. // tooltip: {...}
  77975. // });
  77976. use(install$A); // `axisPointer` component, for example:
  77977. // chart.setOption({
  77978. // tooltip: {axisPointer: {...}, ...}
  77979. // });
  77980. // Or
  77981. // chart.setOption({
  77982. // axisPointer: {...}
  77983. // });
  77984. use(install$s); // `brush` component, for example:
  77985. // chart.setOption({
  77986. // brush: {...}
  77987. // });
  77988. // Or
  77989. // chart.setOption({
  77990. // tooltip: {feature: {brush: {...}}
  77991. // })
  77992. use(install$B); // `title` component, for example:
  77993. // chart.setOption({
  77994. // title: {...}
  77995. // });
  77996. use(install$C); // `timeline` component, for example:
  77997. // chart.setOption({
  77998. // timeline: {...}
  77999. // });
  78000. use(install$D); // `markPoint` component, for example:
  78001. // chart.setOption({
  78002. // series: [{markPoint: {...}}]
  78003. // });
  78004. use(install$E); // `markLine` component, for example:
  78005. // chart.setOption({
  78006. // series: [{markLine: {...}}]
  78007. // });
  78008. use(install$F); // `markArea` component, for example:
  78009. // chart.setOption({
  78010. // series: [{markArea: {...}}]
  78011. // });
  78012. use(install$G); // `legend` component not scrollable. for example:
  78013. // chart.setOption({
  78014. // legend: {...}
  78015. // });
  78016. use(install$J); // `dataZoom` component including both `dataZoomInside` and `dataZoomSlider`.
  78017. use(install$M); // `dataZoom` component providing drag, pinch, wheel behaviors
  78018. // inside coodinate system, for example:
  78019. // chart.setOption({
  78020. // dataZoom: {type: 'inside'}
  78021. // });
  78022. use(install$K); // `dataZoom` component providing a slider bar, for example:
  78023. // chart.setOption({
  78024. // dataZoom: {type: 'slider'}
  78025. // });
  78026. use(install$L); // `dataZoom` component including both `visualMapContinuous` and `visualMapPiecewise`.
  78027. use(install$P); // `visualMap` component providing continuous bar, for example:
  78028. // chart.setOption({
  78029. // visualMap: {type: 'continuous'}
  78030. // });
  78031. use(install$N); // `visualMap` component providing pieces bar, for example:
  78032. // chart.setOption({
  78033. // visualMap: {type: 'piecewise'}
  78034. // });
  78035. use(install$O); // `aria` component providing aria, for example:
  78036. // chart.setOption({
  78037. // aria: {...}
  78038. // });
  78039. use(install$Q); // dataset transform
  78040. // chart.setOption({
  78041. // dataset: {
  78042. // transform: []
  78043. // }
  78044. // });
  78045. use(install$R);
  78046. use(install$S);
  78047. export { Axis, ChartView, ComponentModel, ComponentView, 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, registerVisual, setCanvasCreator, throttle, time, use, util$1 as util, vector, version$1 as version, util as zrUtil, zrender };
  78048. //# sourceMappingURL=echarts.esm.js.map